From aba17a98341722af5d831b649a38fd9ac44cbb90 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Thu, 15 Oct 2026 21:40:00 -0400 Subject: [PATCH] Snapshot for release 2026.10.15.3 (internal ea85b68) --- .../Compatibility/MemoryUse.cs | 152 ++++++++++++++++++ src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs | 2 + src/RynthCore.Engine/EntryPoint.cs | 1 + src/RynthCore.Engine/ImGui/DX9Backend.cs | 10 ++ .../ImGui/EngineFrameController.cs | 6 + src/RynthCore.Engine/ImGui/ImGuiFonts.cs | 88 +++++++++- src/RynthCore.Engine/Plugins/PluginManager.cs | 6 + 7 files changed, 260 insertions(+), 5 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/MemoryUse.cs diff --git a/src/RynthCore.Engine/Compatibility/MemoryUse.cs b/src/RynthCore.Engine/Compatibility/MemoryUse.cs new file mode 100644 index 0000000..a262447 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MemoryUse.cs @@ -0,0 +1,152 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MemoryUse.cs +// +// Where the memory goes while the engine and its plugins start (a client start or a +// hot reload). 2026-10-15: a reload frees the old engine (~550 MB of address space +// back) and the new one takes ~400 MB again within two seconds of the plugins starting, +// all of it freshly touched, so the working set jumps from ~480 MB to ~1.1 GB. The log +// had no per-plugin numbers, so nobody could say what takes it. +// +// Mark(label) logs one "[Mem]" line with private bytes (committed), the .NET heap +// (all managed plugins share the one runtime), the working set and free address +// space, each with its change since the last mark. StartBurst samples every 100 ms for +// a while and logs every rise of BurstStepMb or more in private bytes with the last +// mark's label, so work a plugin does after its Init returns (a background load, its +// first ticks) is still caught. Never throws; any thread. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static class MemoryUse +{ + /// A burst logs each rise in private bytes of at least this much. + private const long BurstStepMb = 16; + + [StructLayout(LayoutKind.Sequential)] + private struct PROCESS_MEMORY_COUNTERS_EX + { + public uint cb; + public uint PageFaultCount; + public nuint PeakWorkingSetSize; + public nuint WorkingSetSize; + public nuint QuotaPeakPagedPoolUsage; + public nuint QuotaPagedPoolUsage; + public nuint QuotaPeakNonPagedPoolUsage; + public nuint QuotaNonPagedPoolUsage; + public nuint PagefileUsage; + public nuint PeakPagefileUsage; + public nuint PrivateUsage; + } + + [DllImport("kernel32.dll")] + private static extern IntPtr GetCurrentProcess(); + + [DllImport("psapi.dll", SetLastError = true)] + private static extern bool GetProcessMemoryInfo(IntPtr process, out PROCESS_MEMORY_COUNTERS_EX counters, uint size); + + /// One reading, in MB (-1 when a value couldn't be read). + internal readonly record struct Reading(long PrivateMb, long WorkingSetMb, long GcHeapMb, long GcCommittedMb, long VaFreeMb); + + private static readonly object Gate = new(); + private static Reading _lastMark; + private static bool _haveMark; + private static volatile string _label = "start"; + private static int _burstRunning; + + public static Reading Read() + { + long priv = -1, ws = -1, gcHeap = -1, gcCommit = -1; + try + { + var c = new PROCESS_MEMORY_COUNTERS_EX { cb = (uint)Marshal.SizeOf() }; + if (GetProcessMemoryInfo(GetCurrentProcess(), out c, c.cb)) + { + priv = (long)((ulong)c.PrivateUsage >> 20); + ws = (long)((ulong)c.WorkingSetSize >> 20); + } + } + catch { } + try + { + GCMemoryInfo gc = GC.GetGCMemoryInfo(); + gcHeap = gc.HeapSizeBytes >> 20; + gcCommit = gc.TotalCommittedBytes >> 20; + } + catch { } + long va = AddressSpace.FreeAndLargestMb().FreeMb; + return new Reading(priv, ws, gcHeap, gcCommit, va); + } + + /// Logs a reading with its change since the last mark, and names what runs next. + public static void Mark(string label) + { + try + { + Reading now = Read(); + Reading prev; + bool had; + lock (Gate) + { + prev = _lastMark; + had = _haveMark; + _lastMark = now; + _haveMark = true; + _label = label; + } + RynthLog.Info($"[Mem] {label}: {Format(now, had ? prev : (Reading?)null)}"); + } + catch { } + } + + /// + /// Samples every 100 ms for and logs each rise in private + /// bytes of BurstStepMb or more, with the label of the last . One + /// burst at a time. + /// + public static void StartBurst(int seconds, string why) + { + if (Interlocked.Exchange(ref _burstRunning, 1) == 1) return; + try + { + var t = new Thread(() => + { + try + { + Reading start = Read(); + Reading last = start; + RynthLog.Info($"[Mem] burst for {seconds} s ({why}): {Format(start, null)}"); + long end = Environment.TickCount64 + seconds * 1000L; + while (Environment.TickCount64 < end) + { + Thread.Sleep(100); + Reading r = Read(); + if (r.PrivateMb >= 0 && last.PrivateMb >= 0 && r.PrivateMb - last.PrivateMb >= BurstStepMb) + { + RynthLog.Info($"[Mem] +{r.PrivateMb - last.PrivateMb} MB private during '{_label}': {Format(r, last)}"); + last = r; + } + } + Reading done = Read(); + RynthLog.Info($"[Mem] burst done ({why}): {Format(done, start)} (change over the whole burst)"); + } + catch { } + finally { Interlocked.Exchange(ref _burstRunning, 0); } + }) + { IsBackground = true, Name = "RynthCore.MemoryUse" }; + t.Start(); + } + catch { Interlocked.Exchange(ref _burstRunning, 0); } + } + + private static string Format(Reading r, Reading? prev) + { + static string D(long now, long? before) => before is long b && b >= 0 && now >= 0 ? $" ({now - b:+0;-0})" : ""; + return $"private {r.PrivateMb} MB{D(r.PrivateMb, prev?.PrivateMb)}, .NET heap {r.GcHeapMb} MB{D(r.GcHeapMb, prev?.GcHeapMb)}" + + $" (committed {r.GcCommittedMb}{D(r.GcCommittedMb, prev?.GcCommittedMb)}), working set {r.WorkingSetMb} MB{D(r.WorkingSetMb, prev?.WorkingSetMb)}," + + $" free address space {r.VaFreeMb} MB{D(r.VaFreeMb, prev?.VaFreeMb)}"; + } +} diff --git a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs index 7b2b5a0..d7a6bf9 100644 --- a/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs +++ b/src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs @@ -80,7 +80,9 @@ internal static class D3D9Bootstrapper if (earlyModule != IntPtr.Zero) { RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device."); + Compatibility.MemoryUse.Mark("D3D9 bootstrap: NULLREF device for the vtable"); EndSceneHook.Install("post-login-vtable"); + Compatibility.MemoryUse.Mark("EndScene hook installed"); return; } diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 6d79c83..3a70045 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -1153,6 +1153,7 @@ public static class EntryPoint if (avalonia && !dcompTest) AvaloniaOverlay.Start(); RynthLog.Info("RynthCore bootstrap initialized."); + Compatibility.MemoryUse.Mark("bootstrap initialized"); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 1152a97..92a2b1d 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -951,6 +951,16 @@ internal static unsafe class DX9Backend // Store texture ID for ImGui io.Fonts.SetTexID(_fontTexture); + + // The glyphs are baked and uploaded: the atlas's input data is no longer read. ImGui + // copies the whole TTF into the atlas for every font it adds (main font, Segoe UI + // Symbol and Phosphor per size, ~3.8 MB each), so with the panel text sizes in use + // that was ~400 MB kept for the life of the atlas (2026-10-15, [Mem] lines). Every + // re-bake builds a fresh atlas from ImGuiFonts' own copies, and the pixels and TexReady + // stay, so nothing needs it back. + Compatibility.MemoryUse.Mark("font atlas uploaded"); + io.Fonts.ClearInputData(); + Compatibility.MemoryUse.Mark("font input data freed"); return true; } diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index e625a32..945e34c 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -134,14 +134,17 @@ internal static class EngineFrameController // Before any context exists: the loaded cimgui.dll must be the exact // build ImGui.NET wraps, or every struct read below is at wrong offsets. + Compatibility.MemoryUse.Mark("ImGui init: before the self-test"); if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle)) return false; + Compatibility.MemoryUse.Mark("ImGui self-test done"); IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); if (previousContext != IntPtr.Zero) RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); _context = ImGuiNET.ImGui.CreateContext(); + Compatibility.MemoryUse.Mark("ImGui context created"); bool initSucceeded = false; try { @@ -179,6 +182,7 @@ internal static class EngineFrameController _uiScale = UiScale.ForWindow(_gameHwnd); RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##})."); RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale); + Compatibility.MemoryUse.Mark("ImGui theme applied"); ImGuiFonts.Build(io, _uiScale); if (!Win32Backend.Init(_gameHwnd)) @@ -187,11 +191,13 @@ internal static class EngineFrameController return false; } + Compatibility.MemoryUse.Mark("Win32 backend ready"); if (!DX9Backend.InitImGui(pDevice)) { _initFailStep = "DX9Backend.InitImGui"; return false; } + Compatibility.MemoryUse.Mark("DX9 backend ready (font texture)"); _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index 2f09d46..85cc710 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -8,8 +8,13 @@ // Consolas 9/10/12 (Tracker, Log, Meta rows), Cascadia Mono 12 (Meta // source; Consolas if missing), and the chat monospace at 8-18 in steps // of 2 (the chat font slider snaps to the nearest). -// The few symbol glyphs still drawn as text (SymbolCodepoints) are merged in -// from Segoe UI Symbol wherever the main font lacks them. +// The few symbol glyphs still drawn as text (SymbolCodepoints) come from the +// main font itself (Segoe UI, Consolas and Cascadia Mono all have them); Segoe UI +// Symbol is merged only into a font whose file lacks one (HasGlyphs). ImGui copies +// the whole TTF into the atlas for every font it adds, and Segoe UI Symbol is +// 2.4 MB: merged into every size (~107 with the panel text sizes) it made ~250 MB +// of the atlas's input data for three glyphs (2026-10-15). DX9Backend frees the +// input data once the texture is uploaded (ClearInputData). // // Icons: the Phosphor icon font (MIT, Assets/Fonts/Phosphor.ttf, embedded in // this assembly) is merged into every baked font, the scaled sets included, @@ -57,7 +62,8 @@ internal static unsafe class ImGuiFonts private static readonly string FontsDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts); // Main text: Basic Latin + Latin-1, general punctuation (— – … • ‘ ’ “ ”), arrows. - private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0 }; + // Plus the SymbolCodepoints (≤ ≥ ●), which the main fonts have. + private static readonly ushort[] MainRanges = { 0x0020, 0x00FF, 0x2010, 0x2027, 0x2190, 0x21FF, 0x2264, 0x2265, 0x25CF, 0x25CF, 0 }; // Symbols still drawn as text, merged from Segoe UI Symbol where the main font // lacks them. The panels' other symbols (⚔ ✦ ➤ ◫ ♥ ◆ ⚙ ▾ ▴ ↗ ↙ ◢ ✕ ☑ ☐ ▶ ▼ ▲ ◀ ■ @@ -81,6 +87,8 @@ internal static unsafe class ImGuiFonts // Phosphor's regular strokes are 1/16 em: at 9-13 px they rasterize thin and grey. private const float IconRasterizerMultiply = 1.2f; private static volatile bool _preloaded; + // Fonts the last AddAll merged Segoe UI Symbol into (their file lacked a symbol glyph). + private static int _symbolMerges; private static readonly List NativeBuffers = new(); private static readonly ImFontPtr[] Fonts = new ImFontPtr[(int)UiFont.Count]; @@ -197,6 +205,7 @@ internal static unsafe class ImGuiFonts { long t0 = Stopwatch.GetTimestamp(); PrepareNativeData(); + Compatibility.MemoryUse.Mark("font files read"); ScaledFonts.Clear(); AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts); @@ -208,8 +217,9 @@ internal static unsafe class ImGuiFonts double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; RynthLog.UI($"ImGuiFonts: {CountBaked()} fonts queued at scale {scale:0.##} in {ms:0.0} ms " + - $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols {(_symbol != null ? "merged" : "missing")}, " + + $"(Cascadia Mono {(_cascadia != null ? "found" : "missing, using Consolas")}, symbols from the main fonts{(_symbolMerges > 0 ? $" (Segoe UI Symbol merged into {_symbolMerges})" : "")}, " + $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")})."); + Compatibility.MemoryUse.Mark("ImGui fonts queued"); } /// The font files and glyph ranges as native memory, made once (rebuilds reuse them). AC thread. @@ -250,6 +260,16 @@ internal static unsafe class ImGuiFonts ImFontPtr[] target = baseSet; float factor = 1f; + // Whether each main font file lacks a symbol glyph (only then is Segoe UI Symbol merged in). + _symbolMerges = 0; + var needsSymbol = new Dictionary(ReferenceEqualityComparer.Instance); + bool NeedsSymbol(byte[] b) + { + if (!needsSymbol.TryGetValue(b, out bool need)) + needsSymbol[b] = need = !HasGlyphs(b, SymbolCodepoints); + return need; + } + void Add(UiFont id, IntPtr data, byte[]? bytes, FaceMetrics metrics, float px) { if (data == IntPtr.Zero || bytes == null) return; @@ -259,8 +279,9 @@ internal static unsafe class ImGuiFonts { cfg.FontDataOwnedByAtlas = false; target[(int)id] = atlas.AddFontFromMemoryTTF(data, bytes.Length, size, cfg, (IntPtr)mainRanges); - if (symbol != IntPtr.Zero && _symbol != null) + if (symbol != IntPtr.Zero && _symbol != null && NeedsSymbol(bytes)) { + _symbolMerges++; cfg.MergeMode = true; cfg.GlyphMinAdvanceX = 0; atlas.AddFontFromMemoryTTF(symbol, _symbol.Length, size, cfg, (IntPtr)symbolRanges); @@ -534,6 +555,63 @@ internal static unsafe class ImGuiFonts private static int IconCount() => new HashSet(PhosphorIcons.Baked).Count; + /// + /// True when the TrueType font has a glyph for every code point (its cmap, format 4: + /// the Basic Multilingual Plane). False when unreadable, so the caller falls back to + /// merging. Pure: tools\PanelTextScaleTests can drive it. + /// + internal static bool HasGlyphs(byte[]? ttf, ushort[] codepoints) + { + if (ttf == null || ttf.Length < 12) return false; + try + { + static int U16(byte[] b, int at) => b[at] << 8 | b[at + 1]; + static int U32(byte[] b, int at) => b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]; + int cmap = -1; + int tables = U16(ttf, 4); + for (int i = 0; i < tables; i++) + { + int rec = 12 + i * 16; + if (U32(ttf, rec) == 0x636D6170) { cmap = U32(ttf, rec + 8); break; } // "cmap" + } + if (cmap < 0) return false; + int subtables = U16(ttf, cmap + 2); + for (int s = 0; s < subtables; s++) + { + int sub = cmap + U32(ttf, cmap + 4 + s * 8 + 4); + if (U16(ttf, sub) != 4) continue; + int segX2 = U16(ttf, sub + 6), ends = sub + 14, starts = ends + segX2 + 2; + int deltas = starts + segX2, offsets = deltas + segX2; + bool all = true; + foreach (ushort cp in codepoints) + { + int glyph = 0; + for (int k = 0; k < segX2 / 2; k++) + { + int end = U16(ttf, ends + k * 2), start = U16(ttf, starts + k * 2); + if (cp > end) continue; + if (cp < start) break; + int delta = (short)U16(ttf, deltas + k * 2), ro = U16(ttf, offsets + k * 2); + if (ro == 0) glyph = (cp + delta) & 0xFFFF; + else + { + glyph = U16(ttf, offsets + k * 2 + ro + 2 * (cp - start)); + if (glyph != 0) glyph = (glyph + delta) & 0xFFFF; + } + break; + } + if (glyph == 0) { all = false; break; } + } + return all; + } + return false; + } + catch (IndexOutOfRangeException) + { + return false; + } + } + /// /// A TrueType font's em as a fraction of the ImGui pixel size (ImGui sizes a /// font so hhea ascent - descent = the size) and half its cap height in em. diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 3a4555e..59c3e08 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -328,6 +328,9 @@ internal static partial class PluginManager public static void LoadPlugins(string engineDir) { + // Where the memory goes while the plugins start (Compatibility/MemoryUse.cs). + Compatibility.MemoryUse.Mark("before the plugins load"); + Compatibility.MemoryUse.StartBurst(60, "plugins starting"); if (_loaded) return; @@ -2688,6 +2691,7 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath} (va before: {Compatibility.AddressSpace.Describe()})"); var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration); RynthLog.Plugin($"PluginManager: loaded {Path.GetFileName(dllPath)}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); + Compatibility.MemoryUse.Mark($"{Path.GetFileNameWithoutExtension(dllPath)} loaded"); if (plugin != null) { plugin.Manifest = manifest; @@ -2827,6 +2831,7 @@ internal static partial class PluginManager plugin.UIInitializedDispatched = false; plugin.LoginCompleteDispatched = false; RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); + Compatibility.MemoryUse.Mark($"{plugin.DisplayName} Init"); } else { @@ -2939,6 +2944,7 @@ internal static partial class PluginManager plugin.OnLoginComplete(); plugin.LoginCompleteDispatched = true; RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete."); + Compatibility.MemoryUse.Mark($"{plugin.DisplayName} OnLoginComplete"); } catch (Exception ex) {