RynthCore/src/RynthCore.Engine/Plugins/EngineSettings.cs

533 lines
23 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.Plugins;
internal static class EngineSettings
{
// RYNTHCORE_ENGINE_SETTINGS points a test client at its own engine.json (its own
// plugin list, no Avalonia, ...) without touching the one real clients share.
private static readonly string SettingsPath =
Environment.GetEnvironmentVariable("RYNTHCORE_ENGINE_SETTINGS") is { Length: > 0 } overridePath
? overridePath
: Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"engine.json");
private static List<string> _pluginPaths = new();
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true;
private static bool _enableHangMinidump = true;
private static bool _preventIdleLogoff = true;
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
// "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name.
private static readonly HashSet<string> _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase);
private static bool _serverMessageStream = true;
private static bool _flightRecorder = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
{
get
{
EnsureLoaded();
return _pluginPaths;
}
}
/// <summary>Force-disabled in code: RynthCore's in-AC UI is the Avalonia overlay, so the
/// ImGui shell (RynthCoreShell bar + plugin ImGui windows) never renders. engine.json and
/// the launcher Plugins tab can no longer toggle this; the persisted field is now a no-op.
/// A developer can opt back in for debugging by setting env var RYNTHCORE_FORCE_IMGUI=1
/// before launching AC — normal users never set this.</summary>
public static bool EnableImGuiShell
=> string.Equals(
System.Environment.GetEnvironmentVariable("RYNTHCORE_FORCE_IMGUI"),
"1", System.StringComparison.Ordinal);
/// <summary>When false, PluginManager.LoadPlugins is skipped so no plugin DLLs load,
/// init, tick, or render. Decal-coexistence plugin pump is also skipped. Default true.</summary>
public static bool EnablePlugins
{
get
{
EnsureLoaded();
return _enablePlugins;
}
}
/// <summary>When false, DatFileShareHooks.Initialize is skipped so kernel32!CreateFileA/W
/// are NOT detoured and no DAT-extension access/share rewriting happens. Multi-client DAT
/// coexistence with Decal-injected clients sharing the same install will fall back to the
/// stricter share semantics those clients negotiated. Default true. Use to isolate the
/// hook for crash diagnostics.</summary>
public static bool EnableDatShareHook
{
get
{
EnsureLoaded();
return _enableDatShareHook;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
/// (when enabled) plugins still load. Default true. Use to confirm whether the engine
/// runs cleanly without Avalonia.</summary>
public static bool EnableAvaloniaOverlay
{
get
{
EnsureLoaded();
#if ENGINE_CORECLR
// Avalonia can't live in an unloadable engine (docs/UNLOADABLE_ENGINE_PLAN.md,
// Phase 5): Skia/HarfBuzz keep strong GC handles for their native callbacks, so
// the generation never unloads, and the next generation's copy finds the old
// one's assemblies ("Call from invalid thread"). The in-game panels are ImGui;
// pop-outs return as ImGui windows (IMGUI_PARITY_PLAN P5).
if (_enableAvaloniaOverlay && System.Threading.Interlocked.Exchange(ref _avaloniaOffLogged, 1) == 0)
RynthLog.Info("EngineSettings: EnableAvaloniaOverlay ignored - the CoreCLR engine runs without Avalonia (it can't be unloaded).");
return false;
#else
return _enableAvaloniaOverlay;
#endif
}
}
#if ENGINE_CORECLR
private static int _avaloniaOffLogged;
#endif
/// <summary>When false, D3D9Bootstrapper.Start() is skipped at LoginComplete so neither
/// Direct3DCreate9/CreateDevice nor IDirect3DDevice9::EndScene get hooked. Eliminates the
/// entire D3D9 detour path, ImGui per-frame work, and the in-AC overlay bar. Compatibility
/// hooks and Avalonia (when enabled) still run. Default true. Use to confirm whether the
/// engine runs cleanly without the EndScene detour.</summary>
public static bool EnableD3D9Hook
{
get
{
EnsureLoaded();
return _enableD3D9Hook;
}
}
/// <summary>When false, InitWorker installs no Compatibility/* hooks, no
/// LoginLifecycleHooks subscriber chain, no OverlayHost panels, no Avalonia,
/// no D3D9. Only the early items (CrashLogger, ProcessExitHooks,
/// MultiClientHooks, DatFileShareHooks, HeartbeatLogger) that fire before
/// InitWorker stay active. Use to confirm whether the recursive AV is in
/// the engine's main hook path or in something earlier (loader, NativeAOT
/// runtime, MultiClientHooks/DatFileShareHooks).</summary>
public static bool EnableEngine
{
get
{
EnsureLoaded();
return _enableEngine;
}
}
/// <summary>Cap on how many of InitWorker's RunInitStep calls actually fire.
/// Default = int.MaxValue (= install all 36). Set to 18 to install only the
/// first half, 9 for the first quarter, etc — use for binary-search
/// bisection of which Compatibility hook is causing the recursive AV.
/// Has no effect if EnableEngine is false.</summary>
public static int EngineHookCount
{
get
{
EnsureLoaded();
return _engineHookCount;
}
}
/// <summary>When false, EngineFrameController.OnEndScene skips its
/// ImGui-specific block (Win32Backend.NewFrame, DX9Backend.NewFrame,
/// ImGui.NewFrame/EndFrame/Render, RynthCoreShell + plugin RenderAll,
/// DX9Backend.RenderDrawData, viewport pump). The always-on engine work
/// (GameMatrixCapture, Nav3DRenderInjector, PluginManager init/tick/
/// pending-action drains, DX9Backend.RenderNav3D fallback) still runs
/// every frame. Diagnostic for whether the per-frame ImGui path is the
/// recurser.</summary>
public static bool EnableImGuiBackend
{
get
{
EnsureLoaded();
return _enableImGuiBackend;
}
set
{
// Set in game with /rc imgui on|off; persisted to engine.json.
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_enableImGuiBackend == value) return;
_enableImGuiBackend = value;
Save();
}
}
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which
/// dumped on every clean exit too). Default true.</summary>
public static bool EnableHangMinidump
{
get
{
EnsureLoaded();
return _enableHangMinidump;
}
}
/// <summary>When true (default), the engine keeps the retail client's idle clock fresh
/// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff
/// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's
/// actions aren't keyboard/mouse input, so the client counted it as idle. Set false in
/// engine.json to get the retail behaviour back.</summary>
public static bool PreventIdleLogoff
{
get
{
EnsureLoaded();
return _preventIdleLogoff;
}
}
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
/// within a short wait; otherwise the old coexistence mode.
/// On - bridge mode whenever Decal is loaded (no fallback; for testing).
/// Off - never bridge mode (the old coexistence mode).
/// Without Decal the setting is never read past this flag.</summary>
public static DecalBridgeMode DecalBridgeMode
{
get
{
EnsureLoaded();
return _decalBridgeMode;
}
}
/// <summary>"DecalInGameImGui" in engine.json (default true since 2026-09-30, after the
/// Reset, UB and soak checks in docs/DECAL_BRIDGE_PLAN.md). Only read when Decal is loaded
/// in the same client and bridge mode is on: true installs the normal EndScene hook and
/// ImGui renderer there (the device is found without creating one); false keeps the old
/// Decal-coexistence "no D3D9" path. RYNTHCORE_DECAL_IMGUI=1/0 overrides it for one client.
/// Without Decal it is never read.</summary>
public static bool DecalInGameImGui
{
get
{
string? env = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_IMGUI");
if (env == "1") return true;
if (env == "0") return false;
EnsureLoaded();
return _decalInGameImGui;
}
}
/// <summary>"DecalStandDown" in engine.json (default true, 2026-10-03). Only read when
/// Decal is loaded in the same client and the Decal bridge is NOT active (not registered
/// as the client sees it, no hello, protocol mismatch): true makes the engine stand down
/// (EntryPoint.InitWorker) - no plugins, no overlay, none of the hooks that collide with
/// Decal; only what the "bridge isn't loaded" chat line needs. The old coexistence path
/// (no overlay, then crashes) ran there before. false brings that path back.
/// DecalBridge=Off always keeps the old path (tests). Without Decal it is never read.</summary>
public static bool DecalStandDown
{
get
{
EnsureLoaded();
return _decalStandDown;
}
}
/// <summary>"DisabledUiHooks" in engine.json: an array of UI hook names
/// (Compatibility/UiHookRegistry: UseNewMode, ClientCleanup, StartTooltip, ResetTooltip,
/// CheckTooltip, StartDragandDrop, CatchDroppedItem). A listed hook is not installed at
/// the next start. Missing = every hook on. /rc hooks on|off &lt;name&gt; edits it.</summary>
public static bool IsUiHookEnabled(string name)
{
EnsureLoaded();
return !_disabledUiHooks.Contains(name);
}
/// <summary>Switches a UI hook on or off for the next start, and saves engine.json.</summary>
public static void SetUiHookEnabled(string name, bool enabled)
{
EnsureLoaded();
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
if (changed)
Save();
}
/// <summary>"ServerMessageStream" in engine.json (default true): the kill switch for the
/// reassembled server-message stream (Net/ServerMessageStream.cs, plugin API v78). Even when
/// true, nothing is copied off the receive hook until a plugin asks for messages (or
/// /rc netmsg log|capture is on). false = the RecvFrom detour does exactly what it did
/// before the stream existed; /rc netmsg on can't override it.</summary>
public static bool ServerMessageStream
{
get
{
EnsureLoaded();
return _serverMessageStream;
}
}
/// <summary>"FlightRecorder" in engine.json (default true): the always-on flight recorder
/// (Net/FlightRecorder.cs, /rc flightdump): a sendto hook plus a ring of the last minutes of
/// client/server traffic and engine markers. false = no sendto hook and nothing recorded,
/// from the next client start.</summary>
public static bool FlightRecorder
{
get
{
EnsureLoaded();
return _flightRecorder;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
string full = Path.GetFullPath(path);
for (int i = 0; i < _pluginPaths.Count; i++)
{
if (string.Equals(_pluginPaths[i], full, StringComparison.OrdinalIgnoreCase))
return;
}
_pluginPaths.Add(full);
Save();
}
public static void RemovePluginPath(int index)
{
EnsureLoaded();
if (index >= 0 && index < _pluginPaths.Count)
{
_pluginPaths.RemoveAt(index);
Save();
}
}
private static void EnsureLoaded()
{
if (_loaded) return;
_loaded = true;
try
{
if (!File.Exists(SettingsPath)) return;
// ReadAllText detects + strips the UTF-8/UTF-16 BOM that some editors
// (PowerShell 5.1 Set-Content -Encoding utf8, Notepad) silently prepend.
// ReadAllBytes + JsonDocument.Parse trips on a leading BOM with
// "'0xEF' is an invalid start of a value", which then sends every
// EngineSettings flag back to its default — silently re-enables
// EnableImGuiBackend etc. with no surfaced error.
using var doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
if (doc.RootElement.TryGetProperty("PluginPaths", out var arr) &&
arr.ValueKind == JsonValueKind.Array)
{
foreach (var el in arr.EnumerateArray())
{
string? val = el.GetString();
if (!string.IsNullOrWhiteSpace(val))
_pluginPaths.Add(val);
}
}
if (doc.RootElement.TryGetProperty("EnableImGuiShell", out var shellEl) &&
(shellEl.ValueKind == JsonValueKind.True || shellEl.ValueKind == JsonValueKind.False))
{
_enableImGuiShell = shellEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnablePlugins", out var pluginsEl) &&
(pluginsEl.ValueKind == JsonValueKind.True || pluginsEl.ValueKind == JsonValueKind.False))
{
_enablePlugins = pluginsEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableDatShareHook", out var datEl) &&
(datEl.ValueKind == JsonValueKind.True || datEl.ValueKind == JsonValueKind.False))
{
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{
_enableAvaloniaOverlay = avEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableD3D9Hook", out var d3dEl) &&
(d3dEl.ValueKind == JsonValueKind.True || d3dEl.ValueKind == JsonValueKind.False))
{
_enableD3D9Hook = d3dEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableEngine", out var engEl) &&
(engEl.ValueKind == JsonValueKind.True || engEl.ValueKind == JsonValueKind.False))
{
_enableEngine = engEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EngineHookCount", out var ehcEl) &&
ehcEl.ValueKind == JsonValueKind.Number &&
ehcEl.TryGetInt32(out int ehc))
{
_engineHookCount = ehc;
}
if (doc.RootElement.TryGetProperty("EnableImGuiBackend", out var ibEl) &&
(ibEl.ValueKind == JsonValueKind.True || ibEl.ValueKind == JsonValueKind.False))
{
_enableImGuiBackend = ibEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{
_enableHangMinidump = hmEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DecalBridge", out var dbEl))
{
if (dbEl.ValueKind == JsonValueKind.True) _decalBridgeMode = DecalBridgeMode.On;
else if (dbEl.ValueKind == JsonValueKind.False) _decalBridgeMode = DecalBridgeMode.Off;
else if (dbEl.ValueKind == JsonValueKind.String &&
Enum.TryParse(dbEl.GetString(), ignoreCase: true, out DecalBridgeMode dbm))
_decalBridgeMode = dbm;
}
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out var dimEl) &&
(dimEl.ValueKind == JsonValueKind.True || dimEl.ValueKind == JsonValueKind.False))
_decalInGameImGui = dimEl.GetBoolean();
if (doc.RootElement.TryGetProperty("DecalStandDown", out var dsdEl) &&
(dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False))
_decalStandDown = dsdEl.GetBoolean();
if (doc.RootElement.TryGetProperty("ServerMessageStream", out var smsEl) &&
(smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False))
_serverMessageStream = smsEl.GetBoolean();
if (doc.RootElement.TryGetProperty("FlightRecorder", out var frEl) &&
(frEl.ValueKind == JsonValueKind.True || frEl.ValueKind == JsonValueKind.False))
_flightRecorder = frEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
duhEl.ValueKind == JsonValueKind.Array)
{
foreach (var el in duhEl.EnumerateArray())
{
if (el.ValueKind == JsonValueKind.String && el.GetString() is { Length: > 0 } hookName)
_disabledUiHooks.Add(hookName.Trim());
}
}
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineSettings: Failed to load {SettingsPath}: {ex.Message}");
}
}
/// <summary>Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from
/// memory (one written only when not the default is left out, as before) and keeps every
/// other key as the file had it. A new engine.json setting goes here too
/// (tools/EngineSettingsTests checks this list against this file).</summary>
internal static readonly HashSet<string> OwnedKeys = new(StringComparer.Ordinal)
{
"PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook",
"EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount",
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder",
};
private static void Save()
{
try
{
string? dir = Path.GetDirectoryName(SettingsPath);
if (dir != null) Directory.CreateDirectory(dir);
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteStartArray("PluginPaths");
foreach (string p in _pluginPaths)
w.WriteStringValue(p);
w.WriteEndArray();
w.WriteBoolean("EnableImGuiShell", _enableImGuiShell);
w.WriteBoolean("EnablePlugins", _enablePlugins);
w.WriteBoolean("EnableDatShareHook", _enableDatShareHook);
w.WriteBoolean("EnableAvaloniaOverlay", _enableAvaloniaOverlay);
w.WriteBoolean("EnableD3D9Hook", _enableD3D9Hook);
w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
w.WriteString("DecalBridge", _decalBridgeMode.ToString());
if (!_decalInGameImGui) // default true: leave the file as it was
w.WriteBoolean("DecalInGameImGui", false);
if (!_decalStandDown) // default true: leave the file as it was
w.WriteBoolean("DecalStandDown", false);
if (_disabledUiHooks.Count > 0) // default none: leave the file as it was
{
w.WriteStartArray("DisabledUiHooks");
foreach (string hookName in _disabledUiHooks)
w.WriteStringValue(hookName);
w.WriteEndArray();
}
if (!_serverMessageStream) // default true: leave the file as it was
w.WriteBoolean("ServerMessageStream", false);
if (!_flightRecorder) // default true: leave the file as it was
w.WriteBoolean("FlightRecorder", false);
w.WriteEndObject();
}
// Keep the keys others write (the launcher's), and swap the file in atomically.
string? existing = File.Exists(SettingsPath) ? File.ReadAllText(SettingsPath) : null;
byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError);
if (merged == null)
{
RynthLog.Warn($"EngineSettings: not saving - {SettingsPath} can't be read ({readError}), and rewriting it would lose what it holds. The change holds until the client closes; fix or delete the file to save again.");
return;
}
EngineSettingsFile.WriteAtomic(SettingsPath, merged);
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}");
}
}
}
/// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary>
internal enum DecalBridgeMode { Auto = 0, On = 1, Off = 2 }