Snapshot for release 2026.10.31.4 (internal 34cea02)

This commit is contained in:
Tom Bohar 2026-11-01 18:47:28 -05:00
commit b1c182b05d
114 changed files with 8691 additions and 452 deletions

View file

@ -23,6 +23,10 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatCommandReplies.cs" Link="Engine\ChatCommandReplies.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatRateLimiter.cs" Link="Engine\ChatRateLimiter.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Hotkeys\HotkeyModel.cs" Link="Engine\HotkeyModel.cs" />
<!-- /rc sense's usage and argument check (the Sense panel's look commands). -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\SenseModel.cs" Link="Engine\SenseModel.cs" />
<!-- The Lua panel's live reload toggle: the /lua line a click sends. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\LuaLiveReload.cs" Link="Engine\LuaLiveReload.cs" />
</ItemGroup>
</Project>

View file

@ -26,6 +26,7 @@ internal static class Program
ReplyTexts();
SourceMatchesCatalog();
ChatBurst();
ControlsRunTheirCommands();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
@ -98,12 +99,19 @@ internal static class Program
("inventory", "inv", "inv now"),
("inventory", "inventory", "inventory now"),
("sense", "sense", "sense now"),
("sense", "sense compact on", "sense compact maybe"),
("sense", "sense collapse off", "sense collapse on off"),
("sense", "sense view collapsed", "sense view huge"),
("sense", "sense compact", "sense frob on"),
("characters", "chars", "characters now"),
("itemcount", "itemhud", "itemcount now"),
("resetbar", "barreset", "resetbar now"),
("actionstate", "actions", "actionstate now"),
("unlockactions", "unlock", "unlockactions now"),
("vitals", "hud", "vitals now"),
("layout", "layout", "layout frob"),
("layout", "layout reset confirm", "layout reset now"),
("layout", "layout default", "layout default now"),
};
private static void EveryVerbValidAndInvalid()
@ -155,6 +163,7 @@ internal static class Program
("report", "report the map froze", "report", "ProblemReport (alone: opens the panel)"),
("flight", "flight mark here", "flight frob", "FlightRecorder.HandleCommand: its usage"),
("autoid", "autoid limited", "autoid frob", "AutoIdService.HandleCommand: its usage"),
("uicost", "uicost 80", "uicost frob", "UiCost.HandleCommand: its usage"),
("netmsg", "netmsg log on", "netmsg frob", "ServerMessageStream.HandleCommand: its usage"),
("hotkeys", "hotkeys", "hotkeys frob", "HotkeyCommandParser: unknown verb + usage"),
("settings", "settings Hotkeys", "settings frob", "SettingsCommand: no tab called 'frob' (tabs: ...)"),
@ -372,6 +381,32 @@ internal static class Program
Check(spam <= 22, $"a retry loop sending every 5 ms for 1 s: at most 12 + 10 (got {spam})");
}
// ── controls that run a command (2026-10-31: buttons for what commands do) ──
private static void ControlsRunTheirCommands()
{
Case("the Sense panel's view switch: each button names a /rc sense command that runs");
foreach (RynthCore.Engine.UI.Data.SenseLayoutMode to in new[] { RynthCore.Engine.UI.Data.SenseLayoutMode.Full,
RynthCore.Engine.UI.Data.SenseLayoutMode.Compact, RynthCore.Engine.UI.Data.SenseLayoutMode.Collapsed })
{
string tip = RynthCore.Engine.UI.Data.SenseLayout.SwitchTip(to);
Match m = Regex.Match(tip, @"/rc (sense [a-z ]+)\)");
Check(m.Success, $"the {to} button's tip names its command: {tip}");
if (!m.Success) continue;
ChatVerbCheck c = ChatCommandReplies.Check(m.Groups[1].Value);
Check(c.Problem == null && c.Verb?.Name == "sense", $"'/rc {m.Groups[1].Value}' runs");
}
Case("the Lua panel's live reload toggle");
Check(RynthCore.Engine.UI.Data.LuaLiveReload.Label(null) == null, "a RynthLua without live reload: no toggle");
Check(RynthCore.Engine.UI.Data.LuaLiveReload.Label(true) == "Live reload: on"
&& RynthCore.Engine.UI.Data.LuaLiveReload.Label(false) == "Live reload: off", "it says the value now");
Check(RynthCore.Engine.UI.Data.LuaLiveReload.ClickArgs(true) == "livereload off"
&& RynthCore.Engine.UI.Data.LuaLiveReload.ClickArgs(false) == "livereload on", "a click sends the other value (/lua livereload on|off)");
Check(RynthCore.Engine.UI.Data.LuaLiveReload.Tip(true).Contains("/lua livereload on|off", StringComparison.Ordinal)
&& RynthCore.Engine.UI.Data.LuaLiveReload.Tip(false).Contains("/lua livereload on|off", StringComparison.Ordinal), "the tip names the command");
}
private static void Case(string name)
{
_case = name;

View file

@ -60,6 +60,11 @@ internal static class Program
LineColorRetail();
LineColorPrecedence();
LineColorJson();
HighlightRouting();
HighlightPrecedence();
HighlightBand();
HighlightJson();
HighlightOldReader();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
@ -468,6 +473,216 @@ internal static class Program
Check(!ChatLineColors.AnySet, "loading a file without it clears them");
}
// ── Highlight line (2026-11-01): a band behind the whole line ──────────
// ChatColorMode.Highlight -> ChatRoute.HighlightArgb (the rule's colour); the face draws
// ChatColorModes.BandArgb of it behind all the line's rows. The first matching Highlight
// rule wins the band, on its own: Line and Match rules still colour the text.
private const uint HlA = 0xFF3366FF, HlB = 0xFFFF6633, LineC = 0xFF00FF00, MatchC = 0xFFFF00FF;
private static ChatFilterRule ColourRule(string pattern, ChatColorMode mode, uint argb,
ChatRuleAction action = ChatRuleAction.Color, string when = "", string tab = "")
{
ChatFilterRule r = Rule(pattern, action, when, tab);
r.ColorMode = mode;
r.ColorArgb = argb;
return r;
}
private static ChatRoute Route(string text, string channel, int type, out List<ChatRouter.Step> trace, params ChatFilterRule[] rules)
{
trace = new List<ChatRouter.Step>();
var router = RetailRouter(rules);
ChatRoute traced = router.Evaluate(text, channel, type, trace);
ChatRoute quiet = router.Evaluate(text, channel, type, null);
// The pump routes without a trace, the test box with one: they must agree.
Check(traced.HighlightArgb == quiet.HighlightArgb && traced.LineArgb == quiet.LineArgb
&& traced.Hidden == quiet.Hidden && traced.InHome == quiet.InHome
&& (traced.Spans?.Length ?? 0) == (quiet.Spans?.Length ?? 0), $"'{text}': traced and untraced routes agree");
return traced;
}
private static bool Says(List<ChatRouter.Step> trace, int rule, string what) =>
trace.Any(s => s.Rule == rule && s.What.Contains(what, StringComparison.Ordinal));
private static void HighlightRouting()
{
Case("highlight: the route carries the rule's colour");
try
{
ResetPresets();
ChatRoute r = Route("Bob tells you, \"hi\"", "Chat", 3, out var trace, ColourRule("tells you", ChatColorMode.Highlight, HlA));
Check(r.HighlightArgb == HlA, "a matching Highlight rule sets HighlightArgb to its colour");
Check(r.LineArgb == null && r.Spans == null, "...and leaves the text colour alone");
Check(!r.Hidden && r.InHome && r.Tabs == null, "...and the routing alone");
Check(Says(trace, 0, "highlights the line"), "the test box says it highlights the line");
ChatRoute none = Route("Bob says, \"hi\"", "Chat", 2, out var t2, ColourRule("tells you", ChatColorMode.Highlight, HlA));
Check(ReferenceEquals(none, ChatRoute.Default), "no match: the shared default route (no allocation)");
Check(t2.Count == 0, "...and nothing in the test box");
var off = ColourRule("tells you", ChatColorMode.Highlight, HlA);
off.Enabled = false;
Check(Route("Bob tells you, \"hi\"", "Chat", 3, out _, off).HighlightArgb == null, "a rule that is off doesn't highlight");
var combatOnly = ColourRule("evaded", ChatColorMode.Highlight, HlA, when: "chan:Combat");
Check(Route("You evaded Tusker Guard!", "Combat", 6, out _, combatOnly).HighlightArgb == HlA, "When chan:Combat: a Combat line is highlighted");
Check(Route("Bob says, \"evaded\"", "Chat", 2, out _, combatOnly).HighlightArgb == null, "...a Chat line isn't");
ChatRoute moved = Route("Bob tells you, \"hi\"", "Chat", 3, out var t3,
ColourRule("tells you", ChatColorMode.Highlight, HlA, ChatRuleAction.Move, tab: "Tells"));
Check(moved.HighlightArgb == HlA && !moved.InHome && moved.Tabs is ["Tells"], "a Move rule can highlight: moved and highlighted");
Check(Says(t3, 0, "moves it to Tells") && Says(t3, 0, "highlights the line"), "...the test box says both");
ChatRoute hidden = Route("spam spam", "Chat", 2, out _,
Rule("spam", ChatRuleAction.Hide), ColourRule("spam", ChatColorMode.Highlight, HlA));
Check(hidden.Hidden && hidden.HighlightArgb == null, "a Hide rule above: hidden, nothing to highlight");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(ColourRule("spam", ChatColorMode.Highlight, HlA)), "buy spam now", 3),
"a Highlight rule never hides a line from the retail chat");
var mentionRouter = new ChatRouter(new[] { ColourRule("Tester", ChatColorMode.Highlight, HlA) },
new Regex(@"\bTester\b", RegexOptions.IgnoreCase), self: "", countHits: false);
ChatRoute both = mentionRouter.Evaluate("Bob says, \"Tester come here\"", "Chat", 2, null);
Check(both.Mention && both.HighlightArgb == HlA && both.Spans is { Length: 1 } && both.Spans[0].Argb == ChatRouter.MentionArgb,
"a mention keeps its tint and name colour on a highlighted line");
}
finally { ResetPresets(); }
}
private static void HighlightPrecedence()
{
Case("highlight: the first matching Highlight rule wins; Line and Match still colour the text");
try
{
ResetPresets();
const string line = "Critical hit! Olthoi Swarm Nymph nicks your head";
ChatRoute r = Route(line, "Combat", 6, out var trace,
ColourRule("Critical", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Highlight, HlB));
Check(r.HighlightArgb == HlA, "two Highlight rules: the higher one's colour");
Check(Says(trace, 1, "(highlight already set above)"), "the test box says the lower one was beaten");
ChatRoute nomatch = Route(line, "Combat", 6, out _,
ColourRule("nothing here", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Highlight, HlB));
Check(nomatch.HighlightArgb == HlB, "the higher one doesn't match: the lower one's colour");
ChatRoute lineFirst = Route(line, "Combat", 6, out _,
ColourRule("Critical", ChatColorMode.Line, LineC), ColourRule("Olthoi", ChatColorMode.Highlight, HlA));
Check(lineFirst.LineArgb == LineC && lineFirst.HighlightArgb == HlA, "Colour line above Highlight: both apply");
ChatRoute hlFirst = Route(line, "Combat", 6, out _,
ColourRule("Critical", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Line, LineC));
Check(hlFirst.LineArgb == LineC && hlFirst.HighlightArgb == HlA, "Highlight above Colour line: both apply");
ChatRoute lines = Route(line, "Combat", 6, out _,
ColourRule("Critical", ChatColorMode.Line, LineC), ColourRule("Olthoi", ChatColorMode.Line, HlB),
ColourRule("nicks", ChatColorMode.Highlight, HlA));
Check(lines.LineArgb == LineC && lines.HighlightArgb == HlA, "Colour line unchanged: still the first one wins");
ChatRoute match = Route(line, "Combat", 6, out _,
ColourRule("Olthoi", ChatColorMode.Match, MatchC), ColourRule("Critical", ChatColorMode.Highlight, HlA));
Check(match.HighlightArgb == HlA && match.Spans is { Length: 1 } && match.Spans[0].Argb == MatchC
&& line.Substring(match.Spans[0].Start, match.Spans[0].Length) == "Olthoi", "Colour match and Highlight: the match coloured on the band");
Check(match.LineArgb == null, "...the rest of the text keeps its normal colour");
// A Highlight rule takes no part in routing order: a Move below it still decides.
ChatRoute route = Route(line, "Combat", 6, out _,
ColourRule("Critical", ChatColorMode.Highlight, HlA), Rule("Olthoi", ChatRuleAction.Move, tab: "Crits"));
Check(route.HighlightArgb == HlA && route.Tabs is ["Crits"] && !route.InHome, "a Move below a Highlight still moves it");
}
finally { ResetPresets(); }
}
private static void HighlightBand()
{
Case("highlight: the band is the swatch colour at 40%");
Check(ChatColorModes.BandAlpha == 0x66, "40% (0x66) for an opaque colour");
Check(ChatColorModes.BandArgb(0xFF3366FF) == 0x663366FF, "an opaque swatch: same RGB, alpha 0x66");
Check(ChatColorModes.BandArgb(0xFFFFFFFF) == 0x66FFFFFF, "white: alpha 0x66");
Check(ChatColorModes.BandArgb(0x80112233) == 0x33112233, "an imported translucent colour: fainter still (0x80 -> 0x33)");
Check(ChatColorModes.BandArgb(0x01112233) >> 24 == 0, "a nearly clear colour: nearly no band");
Check((ChatColorModes.BandArgb(ChatFilterRule.DefaultColor) & 0xFFFFFF) == (ChatFilterRule.DefaultColor & 0xFFFFFF), "the default amber keeps its RGB");
}
private static void HighlightJson()
{
Case("highlight: colorMode \"highlight\" in the settings file and Export / Import");
Check((int)ChatColorMode.None == 0 && (int)ChatColorMode.Line == 1 && (int)ChatColorMode.Match == 2 && (int)ChatColorMode.Highlight == 3,
"the old values keep their numbers (the dropdown is indexed by them)");
foreach (ChatColorMode m in Enum.GetValues<ChatColorMode>())
Check(ChatColorModes.Parse(ChatColorModes.ToJson(m)) == m, $"{m} round-trips");
Check(ChatColorModes.ToJson(ChatColorMode.None) == null, "None writes no colorMode (as before)");
Check(ChatColorModes.ToJson(ChatColorMode.Line) == "line" && ChatColorModes.ToJson(ChatColorMode.Match) == "match", "line / match written as before");
Check(ChatColorModes.ToJson(ChatColorMode.Highlight) == "highlight", "Highlight writes \"highlight\"");
Check(ChatColorModes.Parse("HIGHLIGHT") == ChatColorMode.Highlight && ChatColorModes.Parse(" highlight ") == ChatColorMode.Highlight, "any case, spaces");
Check(ChatColorModes.Parse("text") == ChatColorMode.Match, "\"text\" still reads as match");
Check(ChatColorModes.Parse(null) == ChatColorMode.None && ChatColorModes.Parse("") == ChatColorMode.None
&& ChatColorModes.Parse("sparkle") == ChatColorMode.None, "absent / unknown: None");
var opts = RynthChatJsonContext.Default.RynthChatSettingsDto;
RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!;
foreach (RynthChatFilterDto f in old.Filters!)
Check(ChatColorModes.ToJson(ChatColorModes.Parse(f.ColorMode)) == f.ColorMode, $"an old rule's colorMode ({f.ColorMode ?? "none"}) is written back unchanged");
old.Filters[2].ColorMode = ChatColorModes.ToJson(ChatColorMode.Highlight);
old.Filters[2].Color = ChatLineColors.FormatColor(HlA);
string saved = JsonSerializer.Serialize(old, opts);
Check(saved.Contains("\"colorMode\":\"highlight\"", StringComparison.Ordinal), "saved as colorMode:highlight");
RynthChatSettingsDto back = JsonSerializer.Deserialize(saved, opts)!;
Check(ChatColorModes.Parse(back.Filters![2].ColorMode) == ChatColorMode.Highlight, "loads back as Highlight");
Check(ChatLineColors.ParseColor(back.Filters[2].Color) == HlA, "...with its colour");
Check(JsonSerializer.Serialize(back, opts) == saved, "load + save is stable");
var set = new RynthChatRuleSetDto { Format = RynthChatRuleSetDto.FormatName, Rules = back.Filters, Tabs = back.CustomTabs };
string exported = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto);
RynthChatRuleSetDto imported = JsonSerializer.Deserialize(exported, RynthChatJsonContext.Default.RynthChatRuleSetDto)!;
Check(ChatColorModes.Parse(imported.Rules![2].ColorMode) == ChatColorMode.Highlight
&& ChatLineColors.ParseColor(imported.Rules[2].Color) == HlA, "Export / Import keeps the highlight and its colour");
RynthChatFilterDto[]? bare = JsonSerializer.Deserialize("[{\"pattern\":\"x\",\"colorMode\":\"highlight\",\"color\":\"#3366FF\"}]",
RynthChatJsonContext.Default.RynthChatFilterDtoArray);
Check(bare != null && ChatColorModes.Parse(bare[0].ColorMode) == ChatColorMode.Highlight, "a bare rule array imports the highlight");
}
/// <summary>
/// The colorMode reading of RynthCore release/2026.10.31.4 (ChatModel.FromDto), copied as it was:
/// what an older client does with a file that has "highlight" in it.
/// </summary>
private static ChatColorMode OldReader(string? colorMode) => (colorMode ?? "").ToLowerInvariant() switch
{
"line" => ChatColorMode.Line,
"match" or "text" => ChatColorMode.Match,
_ => ChatColorMode.None,
};
/// <summary>The colorMode writing of release/2026.10.31.4 (ChatModel.ToDto), copied as it was.</summary>
private static string? OldWriter(ChatColorMode m) => m switch { ChatColorMode.Line => "line", ChatColorMode.Match => "match", _ => null };
private static void HighlightOldReader()
{
Case("highlight: an older RynthCore reads a file with \"highlight\" without breaking");
const string newFile = """
{"version":2,"customTabs":["Junk"],
"filters":[{"pattern":"tells you","tab":"","enabled":true,"action":"color","colorMode":"highlight","color":"#3366FF"},
{"pattern":"In portal Space","tab":"Junk","enabled":true,"action":"move","colorMode":"highlight","color":"#FF6633"},
{"pattern":"fizzled","tab":"","enabled":true,"action":"color","colorMode":"match","color":"#FFD27A"}]}
""";
RynthChatSettingsDto? dto = null;
try { dto = JsonSerializer.Deserialize(newFile, RynthChatJsonContext.Default.RynthChatSettingsDto); }
catch (JsonException) { }
Check(dto?.Filters is { Length: 3 }, "the file reads (colorMode is a string: no JSON error)");
if (dto?.Filters is not { Length: 3 } f) return;
Check(OldReader(f[0].ColorMode) == ChatColorMode.None, "an old reader takes \"highlight\" as no colour");
Check(ChatLineColors.ParseColor(f[0].Color) == HlA, "...the rule's colour is still read");
Check(f[1].Action == "move" && f[1].Tab == "Junk" && OldReader(f[1].ColorMode) == ChatColorMode.None, "...a highlighting Move rule still moves");
Check(OldReader(f[2].ColorMode) == ChatColorMode.Match, "...the other rules are unaffected");
// An old client that saves again: the mode is dropped, the colour kept (ToDto writes a
// non-default colour even with no colour mode), so turning it back on finds the colour.
Check(OldWriter(OldReader(f[0].ColorMode)) == null, "an old client's save drops the highlight (no colorMode)");
Check(ChatColorModes.Parse(OldWriter(OldReader(f[2].ColorMode))) == ChatColorMode.Match, "...and keeps the other modes");
// And the new reader reads what an old client writes exactly as the old reader did.
foreach (string? s in new[] { null, "", "line", "match", "text", "LINE", "bogus" })
Check(ChatColorModes.Parse(s) == OldReader(s), $"the new reader agrees with the old on '{s ?? "null"}'");
}
private static void WhenParsing()
{
Case("When: the same reading as before");

View file

@ -8,7 +8,10 @@
src\RynthCore.Engine\Compatibility\ObjectFreshness.cs - when the server last sent anything
about an object (the safety check behind plugin API v83 RemoveClientObject: a "ghost"
creature the server talked about recently is real and is never removed).
Both compiled in; no game, no engine.
Also (2026-10-31) src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs: which unselected plate the HUD asks
the server's health for next (the server streams only the queried target), and which 0x01C0 replies are the
probe's (kept from plugins) versus the selection's / a plugin's.
All compiled in; no game, no engine.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
@ -22,6 +25,7 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CleaveHealth.cs" Link="Engine\CleaveHealth.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs" Link="Engine\HealthProbe.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ObjectFreshness.cs" Link="Engine\ObjectFreshness.cs" />
</ItemGroup>

View file

@ -16,6 +16,10 @@ internal static class Program
Run("cleave: never a kill, never a bad share, nothing to match", Bounds);
Run("cleave: an earlier estimate counts down further", EstimateChains);
Run("freshness: object messages are noted, a delete forgets, others are ignored", Freshness);
Run("health probe: fight plates first, then never-read, then old quiet ones; never the stream's owner", ProbeFightFirst);
Run("health probe: the stalest fight plate first, never-read plates nearest first", ProbeStalestAndNearest);
Run("health probe: nothing due (fresh, dead, no id) sends nothing", ProbeNothingDue);
Run("health probe: a probe's replies are the HUD's; the owner's and plugins' are theirs", ProbeReplies);
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
@ -109,4 +113,100 @@ internal static class Program
ObjectFreshness.Note(0xF74C, 0, 1);
Check(ObjectFreshness.AgeMs(0, 2) == -1, "id 0 ignored");
}
// ── HealthProbe: the unselected plates' health ──────────────────────
private static void ProbeFightFirst()
{
// 0x10 is the selection (streamed). 0x20 is in the fight, last read 3 s ago; 0x30 never read;
// 0x40 quiet at full health, read 20 s ago.
HealthProbe.Candidate[] c =
[
new(0x10, 1.0f, true, 5.0, true),
new(0x20, 4.0f, true, 3.0, true),
new(0x30, 2.0f, false, 0, false),
new(0x40, 1.5f, true, 20.0, false),
];
Check(HealthProbe.Pick(c, owner: 0x10) == 0x20, "a fight plate the server isn't streaming goes first");
Check(HealthProbe.Pick(c, owner: 0x20) == 0x10, "the stream's owner is never probed (the selection is, once it isn't the owner)");
HealthProbe.Candidate[] noFight = [c[2], c[3]];
Check(HealthProbe.Pick(noFight, owner: 0x10) == 0x30, "then a plate never read");
HealthProbe.Candidate[] quiet = [c[3]];
Check(HealthProbe.Pick(quiet, owner: 0x10) == 0x40, "then a quiet plate whose reading is old");
}
private static void ProbeStalestAndNearest()
{
HealthProbe.Candidate[] fight =
[
new(0x20, 1.0f, true, 2.5, true),
new(0x21, 9.0f, true, 6.0, true),
new(0x22, 3.0f, false, 0, true), // hitting you, never read: before any reading
];
Check(HealthProbe.Pick(fight, 0) == 0x22, "a fight plate never read beats every read one");
Check(HealthProbe.Pick(fight[..2], 0) == 0x21, "the stalest fight plate first");
HealthProbe.Candidate[] unseen =
[
new(0x30, 7.0f, false, 0, false),
new(0x31, 2.0f, false, 0, false),
new(0x32, 5.0f, false, 0, false),
];
Check(HealthProbe.Pick(unseen, 0) == 0x31, "never-read plates: the nearest first");
}
private static void ProbeNothingDue()
{
HealthProbe.Candidate[] c =
[
new(0x20, 1.0f, true, HealthProbe.ActiveRefreshSec - 0.1, true), // fresh fight plate
new(0x40, 1.0f, true, HealthProbe.IdleRefreshSec - 0.1, false), // quiet, read recently
new(0x50, 1.0f, true, 30.0, true, Dead: true), // dead
new(0, 1.0f, false, 0, true), // no id
];
Check(HealthProbe.Pick(c, 0) == 0, "nothing due: no query (no traffic)");
Check(HealthProbe.Pick(ReadOnlySpan<HealthProbe.Candidate>.Empty, 0) == 0, "no plates: nothing");
HealthProbe.Candidate[] nan = [new(0x20, 1.0f, true, double.NaN, true)];
Check(HealthProbe.Pick(nan, 0) == 0, "a NaN age is never due");
HealthProbe.Candidate[] due = [new(0x20, 1.0f, true, HealthProbe.ActiveRefreshSec, true)];
Check(HealthProbe.Pick(due, 0) == 0x20, "a fight plate exactly ActiveRefreshSec old is due");
}
private static void ProbeReplies()
{
HealthProbe.Reset();
Check(!HealthProbe.TryGetOwner(out _), "after a reset the stream's owner is unknown");
HealthProbe.NoteQuery(0x10); // the selection / a plugin asked for 0x10
Check(HealthProbe.TryGetOwner(out uint o) && o == 0x10, "the owner is the last queried id");
HealthProbe.NoteProbe(0x20, 1000);
Check(HealthProbe.IsProbeReply(0x20, 1150), "the reply to a probe is the HUD's");
Check(HealthProbe.IsProbeReply(0x20, 1300), "... every path that reports it (window, not consume-once)");
Check(!HealthProbe.IsProbeReply(0x10, 1150), "the owner's replies go to plugins");
Check(!HealthProbe.IsProbeReply(0x30, 1150), "an id nobody probed goes to plugins");
Check(!HealthProbe.IsProbeReply(0x20, 1000 + HealthProbe.ReplyWindowMs + 1), "after the window the id's replies go to plugins again");
Check(!HealthProbe.IsProbeReply(0x20, 1200), "... and the expired entry is gone");
HealthProbe.NoteProbe(0x21, 2000);
HealthProbe.NoteQuery(0x21); // a plugin asked for the same monster right after
Check(!HealthProbe.IsProbeReply(0x21, 2100), "a plugin's own query for a probed id takes its replies back");
Check(HealthProbe.TryGetOwner(out o) && o == 0x21, "... and owns the stream");
// No owner to hand the stream back to: the probed id keeps streaming to us, all of it the HUD's.
HealthProbe.NoteQuery(0);
HealthProbe.NoteProbe(0x22, 3000, sticky: true);
Check(HealthProbe.IsProbeReply(0x22, 3000 + 60_000), "sticky probe: still the HUD's a minute later");
HealthProbe.NoteQuery(0x10);
Check(!HealthProbe.IsProbeReply(0x22, 3000 + 60_001), "the next query moves the stream: sticky entry gone");
for (uint i = 1; i <= 20; i++) HealthProbe.NoteProbe(0x100 + i, 5000); // more than the ledger holds
Check(HealthProbe.IsProbeReply(0x114, 5100), "the newest probes are remembered when the ledger wraps");
Check(!HealthProbe.IsProbeReply(0x101, 5100), "the oldest are dropped (bounded)");
HealthProbe.NoteProbe(0, 5000);
Check(!HealthProbe.IsProbeReply(0, 5000), "id 0 never");
long before = HealthProbe.ProbeCount;
HealthProbe.NoteProbe(0x200, 6000);
Check(HealthProbe.ProbeCount == before + 1, "probes are counted");
HealthProbe.Reset();
Check(!HealthProbe.IsProbeReply(0x114, 5100) && !HealthProbe.TryGetOwner(out _), "reset (logout) forgets everything");
}
}

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the line under a monster in the Damage panel (src\RynthCore.Engine\UI\Data\
DamageRowStats.cs, compiled in as is): the optional "mstats" of a RynthPluginGetMonsterDamageJson
row (a plugin's evades and resists both ways), how it is read (missing, partial, bad and negative
numbers), and the words DamageFace draws under the row and in its tooltip. Nothing native.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>DamageRowStatsTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\DamageRowStats.cs" Link="Engine\DamageRowStats.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,102 @@
using System.Text.Json;
using RynthCore.Engine.UI.Data;
namespace DamageRowStatsTests;
/// <summary>
/// The line under a monster in the Damage panel (DamageRowStats): RynthAi's "mstats" on a
/// RynthPluginGetMonsterDamageJson row, read and worded. The JSON here is the shape RynthAi
/// writes (RynthSuite RynthAiHostTests MonsterStatsTests checks RynthAi's side of it).
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static void Check(bool cond, string what)
{
_checks++;
if (cond) return;
_failed++;
Console.WriteLine(" [FAIL] " + what);
}
private static void Eq<T>(T actual, T expected, string what)
=> Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected '{expected}', got '{actual}'");
private static DamageRowStats? Row(string json)
{
using var doc = JsonDocument.Parse(json);
return DamageRowStats.Parse(doc.RootElement);
}
private static int Main()
{
Reads();
Missing();
Words();
Percents();
Console.WriteLine($"DamageRowStatsTests: {_checks} checks, {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private const string Full =
"{\"wcid\":7,\"name\":\"Drudge Skulker\",\"mstats\":{\"sw\":61,\"ev\":14,\"sp\":30,\"rs\":3,\"ne\":2,"
+ "\"at\":120,\"yev\":50,\"ysp\":8,\"yrs\":1,\"yne\":0,\"k\":12,\"dd\":12345,\"dt\":2345}}";
private static void Reads()
{
DamageRowStats? s = Row(Full);
Check(s != null, "a row with mstats reads");
if (s == null) return;
Eq((s.Swings, s.Evaded, s.Spells, s.Resisted, s.NoEffect), (61, 14, 30, 3, 2), "your side");
Eq((s.Attacks, s.YouEvaded, s.SpellsAtYou, s.YouResisted, s.NoEffectOnYou), (120, 50, 8, 1, 0), "its side");
Eq((s.Kills, s.Dealt, s.Taken), (12, 12345L, 2345L), "kills and damage");
DamageRowStats? part = Row("{\"mstats\":{\"at\":4,\"yev\":3}}");
Check(part != null && part.Attacks == 4 && part.YouEvaded == 3 && part.Swings == 0 && part.Dealt == 0, "missing numbers are 0");
DamageRowStats? odd = Row("{\"mstats\":{\"sw\":-5,\"ev\":\"x\",\"sp\":2.5,\"at\":3,\"yev\":1,\"dd\":-9}}");
Check(odd != null && odd.Swings == 0 && odd.Evaded == 0 && odd.Spells == 0 && odd.Dealt == 0 && odd.Attacks == 3,
"negative, text and fractional numbers read as 0");
DamageRowStats? big = Row("{\"mstats\":{\"sw\":99999999999,\"ev\":1}}");
Check(big != null && big.Swings == int.MaxValue, "a count past an int is capped");
}
private static void Missing()
{
Check(Row("{\"wcid\":7,\"name\":\"Drudge Skulker\",\"kills\":3}") == null, "an older RynthAi's row (no mstats): no line");
Check(Row("{\"mstats\":{}}") == null, "nothing counted: no line");
Check(Row("{\"mstats\":{\"sw\":0,\"at\":0}}") == null, "all zero: no line");
Check(Row("{\"mstats\":5}") == null, "mstats not an object");
Check(Row("[1,2]") == null, "not a row");
Check(Row("{\"mstats\":{\"k\":1}}") != null, "a kill alone is something");
}
private static void Words()
{
DamageRowStats s = Row(Full)!;
Eq(s.Line(), "It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) · You resist 13% (1/8)", "the line");
Eq(Row("{\"mstats\":{\"at\":4,\"yev\":3}}")!.Line(), "You evade 75% (3/4)", "only the parts with something to divide by");
Eq(Row("{\"mstats\":{\"k\":1}}")!.Line(), "", "a kill alone: no rates to show (the row stays one line)");
Eq(Row("{\"mstats\":{\"sw\":2000,\"ev\":1500}}")!.Line(), "It evades 75% (1,500/2,000)", "thousands");
string tip = s.Tip();
Check(tip.Contains("61 melee/missile attacks, 47 hit, it evaded 14 (23%)"), "tip: your attacks: " + tip);
Check(tip.Contains("30 spells reached it, it resisted 3 (10%), 2 no effect (immune)"), "tip: your spells");
Check(tip.Contains("12,345 damage, 12 kills"), "tip: damage and kills");
Check(tip.Contains("120 melee/missile attacks, 70 hit, you evaded 50 (42%)"), "tip: its attacks");
Check(tip.Contains("8 spells reached you, you resisted 1 (13%); 2,345 damage"), "tip: its spells (no 'no effect' when there is none)");
Check(Row("{\"mstats\":{\"k\":1,\"sw\":1}}")!.Tip().Contains("1 kill."), "one kill");
}
private static void Percents()
{
Eq(DamageRowStats.Percent(0, 0), "-", "nothing to divide by");
Eq(DamageRowStats.Percent(0, 5), "0%", "none");
Eq(DamageRowStats.Percent(5, 5), "100%", "all");
Eq(DamageRowStats.Percent(1, 8), "13%", "whole numbers from 10% (12.5 rounds up)");
Eq(DamageRowStats.Percent(1, 3), "33%", "a third");
Eq(DamageRowStats.Percent(2, 3), "67%", "two thirds");
Eq(DamageRowStats.Percent(9, 200), "4.5%", "one decimal below 10%");
Eq(DamageRowStats.Percent(7, 3), "100%", "clamped");
}
}

View file

@ -52,6 +52,8 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdDrain.cs" Link="Engine\AutoIdDrain.cs" />
<Compile Include="..\..\src\RynthCore.Engine\DumpBudget.cs" Link="Engine\DumpBudget.cs" />
<Compile Include="..\..\src\RynthCore.Engine\HangDumpCommand.cs" Link="Engine\HangDumpCommand.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\FontPixels.cs" Link="Engine\FontPixels.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PumpGuards.cs" Link="Engine\PumpGuards.cs" />
</ItemGroup>

View file

@ -51,6 +51,7 @@ internal static partial class Program
RunPumpGuardTests();
RunShutdownOrderTests();
RunReloadStallTests();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;

View file

@ -0,0 +1,65 @@
using RynthCore.Engine;
using RynthCore.Engine.ImGuiBackend;
namespace EngineRobustnessTests;
/// <summary>
/// The pure parts of the 2026-11-01 reload stall fix: the font atlas's RGBA->BGRA rows made by
/// the bake worker (FontPixels), and the hang dump's rundll32 command line (HangDumpCommand).
/// </summary>
internal static partial class Program
{
private static void RunReloadStallTests()
{
FontPixelsSwapRedAndBlue();
HangDumpCommandLine();
}
private static void FontPixelsSwapRedAndBlue()
{
_case = "font pixels";
// Little-endian RGBA words: R is the low byte. A8R8G8B8 in memory is B, G, R, A.
uint[] rgba = { 0xFF0000FFu /* opaque red */, 0x80FF0000u /* half blue */, 0x4000FF00u /* green */, 0x00000000u, 0x12345678u };
var bgra = new uint[rgba.Length];
FontPixels.RgbaToBgra(rgba, bgra);
Check(bgra[0] == 0xFFFF0000u, $"red lands in the R byte of A8R8G8B8 (0x{bgra[0]:X8})");
Check(bgra[1] == 0x800000FFu, $"blue lands in the low byte, alpha kept (0x{bgra[1]:X8})");
Check(bgra[2] == 0x4000FF00u, "green and alpha stay");
Check(bgra[3] == 0, "transparent black stays");
Check(bgra[4] == 0x12785634u, $"R and B swap, G and A stay (0x{bgra[4]:X8})");
// The bytes the old per-byte loop wrote: dst = { src[2], src[1], src[0], src[3] }.
var rnd = new System.Random(11);
var src = new uint[4096];
for (int i = 0; i < src.Length; i++) src[i] = (uint)rnd.Next() ^ ((uint)rnd.Next() << 16);
var dst = new uint[src.Length];
FontPixels.RgbaToBgra(src, dst);
bool same = true;
for (int i = 0; i < src.Length && same; i++)
{
byte[] s = System.BitConverter.GetBytes(src[i]), d = System.BitConverter.GetBytes(dst[i]);
same = d[0] == s[2] && d[1] == s[1] && d[2] == s[0] && d[3] == s[3];
}
Check(same, "the same bytes as the per-byte swizzle it replaces, for 4096 random pixels");
bool threw = false;
try { FontPixels.RgbaToBgra(new uint[4], new uint[3]); }
catch (System.ArgumentException) { threw = true; }
Check(threw, "a destination smaller than the source is refused");
}
private static void HangDumpCommandLine()
{
_case = "hang dump command";
string a = HangDumpCommand.Arguments(@"C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll",
@"C:\Games\RynthCore\Logs\dumps\hang_17132_20261031_211714.dmp", 17132);
Check(a == "\"C:\\Games\\RynthCore\\Runtime\\RynthCore.SehTrampoline.dll\",RC_DumpProcess 17132 C:\\Games\\RynthCore\\Logs\\dumps\\hang_17132_20261031_211714.dmp",
$"dll quoted, entry, pid, then the path as the rest of the line: {a}");
string spaced = HangDumpCommand.Arguments(@"C:\a b\x.dll", @"C:\Users\Some One's PC\d.dmp", 42);
Check(spaced.EndsWith(" 42 C:\\Users\\Some One's PC\\d.dmp", System.StringComparison.Ordinal),
"a path with spaces and an apostrophe is passed as it is (DumpArgs.h takes the rest of the line)");
Check(HangDumpCommand.DescribeExit(0) == "written", "0 = written");
Check(HangDumpCommand.DescribeExit(5) == "MiniDumpWriteDump failed", "5 = MiniDumpWriteDump failed");
Check(HangDumpCommand.DescribeExit(-1).Contains("rundll32"), "anything else is rundll32's own failure");
}
}

View file

@ -26,6 +26,8 @@
<!-- HoldReloadInWorldMaxMinutes: the default and the 1-240 clamp live with the gate. -->
<Compile Include="..\..\src\RynthCore.Engine\ReloadInWorldGate.cs" Link="Engine\ReloadInWorldGate.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<!-- UiCostThresholdMs: the default and the 5-2000 clamp live with the UI cost model. -->
<Compile Include="..\..\src\RynthCore.Engine\ImGui\UiCostModel.cs" Link="Engine\UiCostModel.cs" />
<!-- EditIltServerName starts from IltDetect's defaults (IltDetect shares a parser with AelrynthWire). -->
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />

View file

@ -61,6 +61,7 @@ namespace EngineSettingsTests
Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved);
Run(nameof(IltServerNamesEdit), IltServerNamesEdit);
Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved);
Run(nameof(PanelLayoutPerCharacterDefaultOnAndSaved), PanelLayoutPerCharacterDefaultOnAndSaved);
Run(nameof(BorderlessDecisions), BorderlessDecisions);
Run(nameof(PlacementDecisions), PlacementDecisions);
Run(nameof(PlacementFilesArePerClient), PlacementFilesArePerClient);
@ -121,11 +122,16 @@ namespace EngineSettingsTests
case "borderless-off": EngineSettings.BorderlessWindowed = false; break;
case "layout-on": EngineSettings.RememberWindowLayout = true; break;
case "layout-off": EngineSettings.RememberWindowLayout = false; break;
case "charlayout-on": EngineSettings.PanelLayoutPerCharacter = true; break;
case "charlayout-off": EngineSettings.PanelLayoutPerCharacter = false; break;
case "acpos-on": EngineSettings.RememberAcWindowPosition = true; break;
case "acpos-off": EngineSettings.RememberAcWindowPosition = false; break;
case "hold-on": EngineSettings.HoldReloadInWorld = true; break;
case "hold-off": EngineSettings.HoldReloadInWorld = false; break;
case "hold-minutes": EngineSettings.HoldReloadInWorldMaxMinutes = int.Parse(args[1]); break;
case "uicost-on": EngineSettings.UiCostLog = true; break;
case "uicost-off": EngineSettings.UiCostLog = false; break;
case "uicost-ms": EngineSettings.UiCostThresholdMs = int.Parse(args[1]); break;
case "autoid":
if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]);
EngineSettings.AutoIdMode = aim;
@ -144,6 +150,7 @@ namespace EngineSettingsTests
Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate);
Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed);
Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout);
Console.WriteLine("PanelLayoutPerCharacter=" + EngineSettings.PanelLayoutPerCharacter);
Console.WriteLine("RememberAcWindowPosition=" + EngineSettings.RememberAcWindowPosition);
Console.WriteLine("HoldReloadInWorld=" + EngineSettings.HoldReloadInWorld);
Console.WriteLine("HoldReloadInWorldMaxMinutes=" + EngineSettings.HoldReloadInWorldMaxMinutes);
@ -399,9 +406,12 @@ namespace EngineSettingsTests
(new[] { "insertrel-on" }, "InsertReleasesUi", "true"),
(new[] { "borderless-on" }, "BorderlessWindowed", "true"),
(new[] { "layout-off" }, "RememberWindowLayout", "false"),
(new[] { "charlayout-off" }, "PanelLayoutPerCharacter", "false"),
(new[] { "acpos-on" }, "RememberAcWindowPosition", "true"),
(new[] { "hold-on" }, "HoldReloadInWorld", "true"),
(new[] { "hold-minutes", "90" }, "HoldReloadInWorldMaxMinutes", "90"),
(new[] { "uicost-off" }, "UiCostLog", "false"),
(new[] { "uicost-ms", "120" }, "UiCostThresholdMs", "120"),
(new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null),
(new[] { "autoid", "all" }, "AutoIdMode", "\"All\""),
(new[] { "tgate-off" }, "TransitionGate", "false"),
@ -665,6 +675,34 @@ namespace EngineSettingsTests
}
}
// Settings > Display "Panel Layout Per Character" (UI/PanelLayout, 2026-10-30): on by default and
// not written while on; off is saved and read back (every client then shares the default layout,
// as before); a value that is not a boolean reads as on.
private static void PanelLayoutPerCharacterDefaultOnAndSaved()
{
string dir = NewDir("charlayout");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "True", "on by default");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "a save with the default");
Check(!ReadJson(path).TryGetProperty("PanelLayoutPerCharacter", out _), "the default isn't written to the file");
Eq(RunChild(path, "charlayout-off").Exit, 0, "switched off");
Eq(ReadJson(path).GetProperty("PanelLayoutPerCharacter").GetRawText(), "false", "off is saved");
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "False", "off read back at the next start");
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
Eq(ReadJson(path).GetProperty("PanelLayoutPerCharacter").GetRawText(), "false", "off survives other saves");
Eq(RunChild(path, "charlayout-on").Exit, 0, "back on");
Check(!ReadJson(path).TryGetProperty("PanelLayoutPerCharacter", out _), "back at the default: dropped from the file");
foreach (string bad in new[] { "\"no\"", "0", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"PanelLayoutPerCharacter\": {bad}, \"LoggingLevel\""));
Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "True", $"PanelLayoutPerCharacter={bad}: stays on");
}
}
// ── AcWindowChromePolicy: borderless windowed ───────────────────────
private const int Windowed = 0x14CF0000 | WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox;

View file

@ -0,0 +1,25 @@
# Builds and runs bench.c (x86, MSVC): one MinHook queued apply timed with and without the
# HIGH priority class the loader uses around each freeze, on a quiet machine and with every CPU
# busy above this process's LOWEST threads. Loads the machine for ~30 s at below-normal priority.
# Not part of Run-AllTests (no "Test" in the folder name): it measures, it doesn't pass or fail.
param([string]$MinHook = (Join-Path $PSScriptRoot "..\..\src\RynthCore.Engine\Native\minhook.x86.dll"))
$ErrorActionPreference = "Stop"
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
$out = Join-Path $env:TEMP "LoaderFreezeBench"
New-Item -ItemType Directory -Force $out | Out-Null
Push-Location $out
try {
& $cl /nologo /O2 /MT /W4 /wd4100 (Join-Path $PSScriptRoot "bench.c") /Fe:bench.exe
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\bench.exe (Resolve-Path $MinHook).Path
exit $LASTEXITCODE
} finally { Pop-Location }

View file

@ -0,0 +1,118 @@
// ============================================================================
// tools\LoaderFreezeBench\bench.c - how long one MinHook queued apply (the loader's
// "Hooks: N patch(es) applied in one freeze") takes while this process's LOWEST-priority
// threads can't get a CPU, with and without the HIGH priority class the loader's
// BoostForFreeze (native\Loader\Hooks.c) puts around every freeze.
//
// The burner is a second copy of this program: BELOW_NORMAL class, a normal-priority spinning
// thread per CPU (+2), so it sits above this process's LOWEST threads (BELOW_NORMAL class too)
// but below every normal-priority process (the game clients keep their CPU). It runs ~15 s
// per starved phase. Not a gate test (it measures, it doesn't pass or fail, and it loads the
// machine): run it by hand with Run-Bench.ps1.
//
// 2026-11-01 on the 8-core PC with five clients running (the machine already busy): an apply
// took 0.4-13 s as is unstarved and 12-38 s starved; with the boost 85-110 ms either way.
// ============================================================================
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (__stdcall *fn0)(void);
typedef int (__stdcall *fncreate)(void*, void*, void**);
typedef int (__stdcall *fn1)(void*);
static volatile LONG g_stop;
static HANDLE g_never;
static DWORD WINAPI Spin(LPVOID p) { (void)p; volatile unsigned x = 0; while (!g_stop) x++; return 0; }
static DWORD WINAPI Idle(LPVOID p) { (void)p; WaitForSingleObject(g_never, INFINITE); return 0; }
__declspec(noinline) int __stdcall Target(int a) { return a * 3 + 1; }
__declspec(noinline) int __stdcall Detour(int a) { return a; }
static fn1 g_qen, g_qdis;
static fn0 g_apply;
static int g_enabled;
static double ApplyOnce(int boost)
{
(g_enabled ? g_qdis : g_qen)((void*)Target);
LARGE_INTEGER f, t0, t1;
QueryPerformanceFrequency(&f);
QueryPerformanceCounter(&t0);
DWORD before = GetPriorityClass(GetCurrentProcess());
if (boost) SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
int st = g_apply();
QueryPerformanceCounter(&t1); // the freeze is over here: every thread runs again
if (boost) SetPriorityClass(GetCurrentProcess(), before);
g_enabled = !g_enabled;
if (st != 0) printf(" MH_ApplyQueued = %d\n", st);
return (t1.QuadPart - t0.QuadPart) * 1000.0 / f.QuadPart;
}
static HANDLE StartBurner(int seconds)
{
char self[MAX_PATH], cmd[MAX_PATH + 32];
GetModuleFileNameA(NULL, self, MAX_PATH);
_snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\" burn %d", self, seconds);
STARTUPINFOA si = { sizeof si };
PROCESS_INFORMATION pi;
if (!CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return NULL;
CloseHandle(pi.hThread);
Sleep(1500); // every CPU busy before the first apply
return pi.hProcess;
}
static void Phase(const char* name, int boost, int trials, int burnSeconds)
{
HANDLE burner = burnSeconds > 0 ? StartBurner(burnSeconds) : NULL;
if (burnSeconds > 0 && !burner) { printf("%s: could not start the burner\n", name); return; }
for (int i = 0; i < trials; i++) {
if (burner && WaitForSingleObject(burner, 0) == WAIT_OBJECT_0) { printf("%s: burner ended, phase cut short\n", name); break; }
Sleep(300);
printf("%-22s trial %d: %8.1f ms\n", name, i, ApplyOnce(boost));
fflush(stdout);
}
if (burner) { TerminateProcess(burner, 0); CloseHandle(burner); }
}
int main(int argc, char** argv)
{
if (argc >= 3 && strcmp(argv[1], "burn") == 0) {
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
SYSTEM_INFO si;
GetSystemInfo(&si);
for (DWORD i = 0; i < si.dwNumberOfProcessors + 2; i++) CloseHandle(CreateThread(NULL, 0, Spin, NULL, 0, NULL));
Sleep(atoi(argv[2]) * 1000);
return 0;
}
if (argc < 2) { printf("bench <minhook.x86.dll>\n"); return 2; }
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
g_never = CreateEventA(NULL, TRUE, FALSE, NULL);
for (int i = 0; i < 6; i++) { // like AC's d3d9 worker threads: LOWEST, waiting
HANDLE t = CreateThread(NULL, 0, Idle, NULL, 0, NULL);
SetThreadPriority(t, THREAD_PRIORITY_LOWEST);
CloseHandle(t);
}
HMODULE mh = LoadLibraryA(argv[1]);
if (!mh) { printf("could not load %s\n", argv[1]); return 3; }
fn0 init = (fn0)GetProcAddress(mh, "MH_Initialize");
fncreate create = (fncreate)GetProcAddress(mh, "MH_CreateHook");
g_qen = (fn1)GetProcAddress(mh, "MH_QueueEnableHook");
g_qdis = (fn1)GetProcAddress(mh, "MH_QueueDisableHook");
g_apply = (fn0)GetProcAddress(mh, "MH_ApplyQueued");
void* orig;
if (!init || !create || !g_qen || !g_qdis || !g_apply || init() != 0 || create((void*)Target, (void*)Detour, &orig) != 0) {
printf("MinHook init/create failed\n");
return 4;
}
Phase("not starved, as is", 0, 3, 0);
Phase("not starved, boost", 1, 3, 0);
Phase("starved, boost", 1, 4, 15);
Phase("starved, as is", 0, 2, 15);
g_stop = 1;
return 0;
}

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Loot Editor's text-condition modes (src\RynthCore.Engine\UI\LootPatternText.cs):
contains / doesn't contain / starts with / ends with / is exactly / regex written as VTank regex, what
each pattern matches (case-insensitive, as RynthAi's evaluator), and patterns read back as the same
mode and words (and anything else as regex).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>LootPatternTextTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\LootPatternText.cs" Link="Engine\LootPatternText.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,92 @@
using System.Text.RegularExpressions;
using RynthCore.Engine.UI;
namespace LootPatternTextTests;
// Offline tests for the Loot Editor's text-condition modes. See the csproj.
internal static class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
// RynthAi's evaluator: Regex.IsMatch(value, pattern, IgnoreCase).
private static bool Matches(string pattern, string text) => Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase);
private static int Main()
{
try
{
Writes();
WhatTheyMatch();
ReadBack();
OtherPatternsAreRegex();
}
catch (Exception ex)
{
_fails++;
Console.WriteLine($" [FAIL] threw: {ex}");
}
Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} assertions)" : $"FAIL: {_fails} of {_asserts} assertions failed");
return _fails == 0 ? 0 : 1;
}
private static void Writes()
{
Check(LootPatternText.Build(LootTextMode.Contains, "Sanguine") == "Sanguine", "contains: the word");
Check(LootPatternText.Build(LootTextMode.NotContains, "Sanguine") == "^(?!.*Sanguine)", "doesn't contain: a lookahead");
Check(LootPatternText.Build(LootTextMode.NotContains, "Sanguine, Tattered") == "^(?!.*(Sanguine|Tattered))", "doesn't contain: several words");
Check(LootPatternText.Build(LootTextMode.Contains, "Sanguine, Tattered") == "Sanguine|Tattered", "contains: several words");
Check(LootPatternText.Build(LootTextMode.StartsWith, "Ancient") == "^Ancient", "starts with");
Check(LootPatternText.Build(LootTextMode.EndsWith, "Robe") == "Robe$", "ends with");
Check(LootPatternText.Build(LootTextMode.Exactly, "Trade Note (250,000)") == "^Trade Note \\(250,000\\)$", "is exactly: brackets escaped, spaces kept");
Check(LootPatternText.Build(LootTextMode.Regex, "a.*b") == "a.*b", "regex: as typed");
Check(LootPatternText.Build(LootTextMode.NotContains, " ") == "", "no words: empty");
Check(LootPatternText.Build(LootTextMode.StartsWith, "") == "", "no words: empty (not a bare ^)");
Check(LootPatternText.Escape("a.b*c?") == "a\\.b\\*c\\?", "escape: metacharacters");
}
private static void WhatTheyMatch()
{
string not = LootPatternText.Build(LootTextMode.NotContains, "Sanguine");
Check(!Matches(not, "Sanguine Robe") && !Matches(not, "Robe of the sanguine"), "doesn't contain: any case, anywhere");
Check(Matches(not, "Frost Robe") && Matches(not, "") , "doesn't contain: other names (and an empty one) pass");
string notTwo = LootPatternText.Build(LootTextMode.NotContains, "Sanguine, Tattered");
Check(!Matches(notTwo, "Tattered Cloak") && !Matches(notTwo, "Sanguine Robe") && Matches(notTwo, "Fine Cloak"), "doesn't contain: either word");
string has = LootPatternText.Build(LootTextMode.Contains, "Sanguine, Tattered");
Check(Matches(has, "a TATTERED cloak") && !Matches(has, "Fine Cloak"), "contains: either word, any case");
Check(Matches(LootPatternText.Build(LootTextMode.StartsWith, "Ancient"), "Ancient Sword") && !Matches(LootPatternText.Build(LootTextMode.StartsWith, "Ancient"), "An Ancient Sword"), "starts with");
Check(Matches(LootPatternText.Build(LootTextMode.EndsWith, "Robe"), "Frost Robe") && !Matches(LootPatternText.Build(LootTextMode.EndsWith, "Robe"), "Robe of Frost"), "ends with");
string exact = LootPatternText.Build(LootTextMode.Exactly, "Trade Note (250,000)");
Check(Matches(exact, "Trade Note (250,000)") && !Matches(exact, "Trade Note (250,000) x2") && !Matches(exact, "Trade Note 250,000"), "is exactly: the whole name, brackets literal");
Check(Matches(LootPatternText.Build(LootTextMode.Contains, "a.b"), "a.b") && !Matches(LootPatternText.Build(LootTextMode.Contains, "a.b"), "axb"), "a dot typed is a dot");
}
private static void ReadBack()
{
foreach (var (mode, words) in new[]
{
(LootTextMode.Contains, "Sanguine"), (LootTextMode.NotContains, "Sanguine"), (LootTextMode.NotContains, "Sanguine, Tattered"),
(LootTextMode.Contains, "Sanguine, Tattered"), (LootTextMode.StartsWith, "Ancient"), (LootTextMode.EndsWith, "Robe"),
(LootTextMode.Exactly, "Trade Note (250,000)"), (LootTextMode.Contains, "a.b"), (LootTextMode.Exactly, "Mana Stone"),
})
{
var (m, w) = LootPatternText.Parse(LootPatternText.Build(mode, words));
Check(m == mode && w == words, $"round trip {mode} '{words}' -> {m} '{w}'");
}
Check(LootPatternText.Parse("") == (LootTextMode.Contains, ""), "an empty pattern: contains, no words");
// LootSdk's ExactPattern (the "Add to loot profile" rules): "^" + EscapeText(name) + "$".
Check(LootPatternText.Parse("^Pyreal$") == (LootTextMode.Exactly, "Pyreal"), "the add-item rules' exact names read as is exactly");
}
private static void OtherPatternsAreRegex()
{
foreach (string p in new[] { "a.*b", "^(Robe|Cloak)$", "Sword|", "\\d+", "^$", "^(?!.*Sanguine)Robe" })
Check(LootPatternText.Parse(p).Mode == LootTextMode.Regex, $"'{p}' is regex");
Check(LootPatternText.Parse("Robe\\$") == (LootTextMode.Contains, "Robe$"), "an escaped $ is a literal: contains 'Robe$'");
Check(LootPatternText.Parse("a.*b").Words == "a.*b", "regex: its words are the pattern");
}
}

View file

@ -30,12 +30,57 @@ internal static class Program
RowTextLeaves();
RowTextLists();
RowTextActions();
SaveIndicator();
Console.WriteLine();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks");
return _failed == 0 ? 0 : 1;
}
// ── The "Saved" indicator waits for RynthAi's answer (2026-11-01) ───────
private static void SaveIndicator()
{
Case("save indicator follows RynthAi's result");
var w = new MetaSaveWatch();
var loaded = new MetaSaveResult { Seq = 1, Ok = true, Text = "Loaded farm.af" };
Eq(w.State(0, loaded, 0), MetaSaveState.Saved, "nothing sent: saved");
w.Sent(1000, loaded.Seq, 0);
Eq(w.State(1100, loaded, 0), MetaSaveState.Saving, "sent, no answer yet");
var saved = new MetaSaveResult { Seq = 2, Ok = true, Text = "Saved farm.af (3 rules)" };
Eq(w.State(1200, saved, 0), MetaSaveState.Saved, "answered: saved");
Eq(w.State(99999, saved, 0), MetaSaveState.Saved, "and stays saved");
w.Sent(2000, saved.Seq, 0);
var failed = new MetaSaveResult { Seq = 3, Ok = false, Text = "NOT saved to farm.af: the file is open in another program." };
Eq(w.State(2100, failed, 0), MetaSaveState.Failed, "answered: failed");
Eq(w.State(60000, failed, 0), MetaSaveState.Failed, "a failure stays up until the next result");
w.Sent(61000, failed.Seq, 0);
Eq(w.State(61100, failed, 0), MetaSaveState.Saving, "the next change waits again");
Eq(w.State(61200, new MetaSaveResult { Seq = 4, Ok = true }, 0), MetaSaveState.Saved, "and its save clears the failure");
w.Sent(70000, 4, 0);
Eq(w.State(70000 + MetaSaveWatch.ConfirmMs - 1, new MetaSaveResult { Seq = 4 }, 0), MetaSaveState.Saving, "still waiting just before the limit");
Eq(w.State(70000 + MetaSaveWatch.ConfirmMs, new MetaSaveResult { Seq = 4 }, 0), MetaSaveState.Unconfirmed, "no answer: not confirmed (it used to say Saved)");
var d = new MetaSaveWatch();
d.Sent(0, 4, 7);
Eq(d.State(10, new MetaSaveResult { Seq = 4 }, 8), MetaSaveState.NotSent, "the command never reached RynthAi");
d.Sent(20, 4, 8); // a second change in the same burst
Eq(d.State(30, new MetaSaveResult { Seq = 4 }, 8), MetaSaveState.NotSent, "a dropped command earlier in the burst still shows");
var old = new MetaSaveWatch();
old.Sent(0, 0, 0);
Eq(old.State(100, null, 0), MetaSaveState.Saving, "a RynthAi without results: the old timer");
Eq(old.State(MetaSaveWatch.LegacySavingMs, null, 0), MetaSaveState.Saved, "then saved, as before");
var r = new MetaSaveWatch();
r.Sent(0, 1, 0);
r.Reset();
Eq(r.State(MetaSaveWatch.ConfirmMs * 2, new MetaSaveResult { Seq = 1 }, 0), MetaSaveState.Saved, "reopened panel: nothing pending");
}
// ── New state names ──────────────────────────────────────────────────
private static void StateNames()

View file

@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the panel layout per character (2026-10-30): src\RynthCore.Engine\UI\
PanelLayoutPolicy.cs (who owns a layout, its file names, which layout a client uses, the session
that decides when to switch and when panels may draw, /rc layout's parsing and replies),
PanelLayoutFiles.cs (seeding, reset, make default, the latest-text writes), PanelStateStore.cs
(switching its file, atomic saves), BarLayout.cs and EngineSettingsFile.cs (the atomic write) and
Compatibility\ChatCommandReplies.cs (the /rc layout verb), compiled in with a stub RynthLog and
EngineSettings. Two clients are two child processes of this test writing their own characters'
layouts at the same time in a temp folder. Never touches %LOCALAPPDATA% or C:\Games (the temp
folder is deleted at the end). Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PanelLayoutTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelLayoutPolicy.cs" Link="Engine\PanelLayoutPolicy.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelLayoutFiles.cs" Link="Engine\PanelLayoutFiles.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelStateStore.cs" Link="Engine\PanelStateStore.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ChatCommandReplies.cs" Link="Engine\ChatCommandReplies.cs" />
<!-- ChatCommandReplies' /rc sense row names SenseLayout (the Sense views, feature/sense-compact). -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\SenseModel.cs" Link="Engine\SenseModel.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,770 @@
using System.Diagnostics;
using System.Text;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
namespace RynthCore.Engine
{
/// <summary>Stub of the engine's log (PanelStateStore writes load/save problems to it).</summary>
internal static class RynthLog
{
internal static readonly List<string> Lines = new();
internal static void UI(string msg) { lock (Lines) Lines.Add(msg); }
}
}
namespace RynthCore.Engine.Plugins
{
/// <summary>Stub of the one engine.json setting PanelStateStore reads.</summary>
internal static class EngineSettings
{
public static bool RememberWindowLayout { get; set; } = true;
}
}
namespace PanelLayoutTests
{
/// <summary>
/// Panel layout per character without AC: the key and file names, seeding a new character from the
/// default, the switch at login and back at logout, a hot reload using the character's files from
/// the first frame (the decision logic), two clients never writing each other's files, the setting
/// off giving today's paths, and the /rc layout replies.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static string _root = "";
// Placeholders only: no real server or character names.
private const string ServerOne = "Server One", ServerTwo = "ServerTwo";
private const string CharA = "Character A", CharB = "Character B";
private static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "--client")
return Client(args.Skip(1).ToArray());
_root = Path.Combine(Path.GetTempPath(), "rynth-panel-layout-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
try
{
Run(KeyAndFileNames);
Run(SettingOffGivesTodaysPaths);
Run(SeedingFromTheDefault);
Run(ResetAndMakeDefaultFiles);
Run(LatestTextWritesKeepTheNewest);
Run(StoreSwitchesItsFile);
Run(SwitchAtLoginAndBackAtLogout);
Run(HotReloadUsesTheCharactersFilesFromTheFirstFrame);
Run(IdentityThatNeverComes);
Run(OneSwitchAtATimeAndReset);
Run(TwoSessionsNeverShareAFile);
Run(TwoClientsNeverWriteEachOthersFiles);
Run(AutoSaveRules);
Run(CommandReplies);
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL PANEL LAYOUT TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
private static void Run(Action test)
{
try { test(); }
catch (Exception ex) { _checks++; _failed++; Console.WriteLine($" FAIL [{_case}] threw {ex.GetType().Name}: {ex.Message}"); }
}
private static string NewDir(string name)
{
string dir = Path.Combine(_root, name);
Directory.CreateDirectory(dir);
return dir;
}
private static string DefaultIni(string root) => Path.Combine(root, "suite", "RynthAi", "imgui.ini");
// ── the key and the file names ───────────────────────────────────────
private static void KeyAndFileNames()
{
Case("the key: server and character, the file names");
Check(PanelLayoutPolicy.Owner(ServerOne, "") == null, "no character name: no owner (the default is used)");
Check(PanelLayoutPolicy.Owner(ServerOne, " ") == null, "a blank name is no name");
Check(PanelLayoutPolicy.Owner(null, null) == null, "nothing known: no owner");
LayoutOwner a = PanelLayoutPolicy.Owner(" " + ServerOne + " ", " " + CharA + " ")!;
Check(a.Server == ServerOne && a.Character == CharA, "names are trimmed");
Check(a.Equals(PanelLayoutPolicy.Owner(ServerOne.ToUpperInvariant(), CharA.ToLowerInvariant())), "the same character in another case is the same owner");
Check(a.GetHashCode() == PanelLayoutPolicy.Owner(ServerOne.ToUpperInvariant(), CharA.ToLowerInvariant())!.GetHashCode(), "...with the same hash");
Check(!a.Equals(PanelLayoutPolicy.Owner(ServerTwo, CharA)), "the same name on another server is another owner");
Check(!a.Equals(PanelLayoutPolicy.Owner(ServerOne, CharB)), "another character is another owner");
Eq(PanelLayoutPolicy.Describe(a), CharA + " on " + ServerOne, "described as 'name on server'");
Eq(PanelLayoutPolicy.Describe(PanelLayoutPolicy.Owner("", CharA)!), CharA, "no server: just the name");
string root = @"C:\Users\Someone\AppData\Local\RynthCore";
LayoutFiles f = PanelLayoutPolicy.CharacterFiles(root, a);
Eq(f.PanelState, Path.Combine(root, "layouts", ServerOne, CharA, "panel_state.txt"), "panel_state.txt in layouts\\<server>\\<character>");
Eq(f.ImGuiIni, Path.Combine(root, "layouts", ServerOne, CharA, "imgui.ini"), "imgui.ini beside it");
Eq(f.Folder, Path.Combine(root, "layouts", ServerOne, CharA), "the layout's folder");
Eq(PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner("", CharA)!).PanelState,
Path.Combine(root, "layouts", "_", CharA, "panel_state.txt"), "no server: the '_' folder");
Check(PanelLayoutPolicy.CharacterFiles(root, a).Folder != PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerTwo, CharA)!).Folder,
"the same name on two servers: two folders");
Case("safe file names");
Eq(PanelLayoutPolicy.SafeSegment(CharA), CharA, "a plain name (letters, a space) stays as it is");
Eq(PanelLayoutPolicy.SafeSegment("Some-Name'Here"), "Some-Name'Here", "hyphens and apostrophes are fine");
Eq(PanelLayoutPolicy.SafeSegment(""), "_", "empty: '_'");
Eq(PanelLayoutPolicy.SafeSegment(null), "_", "null: '_'");
string colon = PanelLayoutPolicy.SafeSegment("A:B"), question = PanelLayoutPolicy.SafeSegment("A?B");
Check(colon.StartsWith("A_B-", StringComparison.Ordinal) && question.StartsWith("A_B-", StringComparison.Ordinal), $"invalid characters become '_' ({colon}, {question})");
Check(colon != question, "two names that clean up alike stay apart (a hash of the original)");
Eq(PanelLayoutPolicy.SafeSegment("A:B"), colon, "the same name always gives the same folder");
foreach (string bad in new[] { "a/b", "a\\b", "a*b", "a|b", "a<b>", "a\"b", "tab\there", "dots..." , "space ", "CON", "nul", "com1.txt" })
{
string s = PanelLayoutPolicy.SafeSegment(bad);
Check(s.Length > 0 && s.IndexOfAny(Path.GetInvalidFileNameChars()) < 0, $"'{bad}' -> '{s}' has no invalid characters");
Check(!s.EndsWith('.') && !s.EndsWith(' '), $"'{bad}' -> '{s}' doesn't end with a dot or space");
string stem = s.Split('.')[0].Split('-')[0];
Check(!new[] { "CON", "NUL", "COM1" }.Contains(stem, StringComparer.OrdinalIgnoreCase), $"'{bad}' -> '{s}' isn't a device name");
string dir = Path.Combine(_root, "names", s);
Directory.CreateDirectory(dir);
Check(Directory.Exists(dir), $"'{s}' can be made as a folder");
}
string longName = new string('x', 200);
Check(PanelLayoutPolicy.SafeSegment(longName).Length <= 64 + 9, "a very long name is cut (plus its hash)");
}
private static void SettingOffGivesTodaysPaths()
{
Case("the setting off: today's files");
string root = @"C:\Users\Someone\AppData\Local\RynthCore";
string ini = @"C:\Games\RynthSuite\RynthAi\imgui.ini";
LayoutOwner who = PanelLayoutPolicy.Owner(ServerOne, CharA)!;
LayoutFiles today = PanelLayoutPolicy.DefaultFiles(root, ini);
Eq(today.PanelState, Path.Combine(root, "panel_state.txt"), "the default panel_state.txt is the file every client used");
Eq(today.ImGuiIni, ini, "the default imgui.ini is the file every client used");
Check(PanelLayoutPolicy.Choose(perCharacter: false, inWorld: true, who) == null, "setting off, in the world: the default");
Eq(PanelLayoutPolicy.FilesFor(root, ini, PanelLayoutPolicy.Choose(false, true, who)), today, "setting off: today's two files");
Check(PanelLayoutPolicy.Choose(true, inWorld: false, who) == null, "setting on, at character select: the default");
Check(PanelLayoutPolicy.Choose(true, true, null) == null, "setting on, in the world, no character name: the default");
Eq(PanelLayoutPolicy.Choose(true, true, who), who, "setting on, in the world with a name: the character's");
Eq(PanelLayoutPolicy.FilesFor(root, ini, who), PanelLayoutPolicy.CharacterFiles(root, who), "...and its files");
string expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_state.txt");
Eq(PanelStateStore.DefaultPath, expected, "PanelStateStore's default is today's %LOCALAPPDATA%\\RynthCore\\panel_state.txt (path only, not opened)");
Case("the setting off: a session never leaves the default");
var s = new PanelLayoutSession();
LayoutSwitch? first = s.Tick(0, perCharacter: false, inWorld: false, 0, false, null);
Check(first is { To: null }, "first frame: the default");
s.MarkApplied(first!.Value.Gen);
Check(s.Tick(10, false, inWorld: true, 10, identityRecorded: true, who) == null, "login with the setting off: no switch");
Check(s.ReadyToDraw(11, true, 10), "and the panels draw at once (the default is in place)");
Check(s.Tick(20, false, inWorld: false, 0, true, who) == null, "logout: still nothing to switch");
}
// ── seeding a new character from the default ─────────────────────────
private static void SeedingFromTheDefault()
{
Case("seed plan");
Eq(PanelLayoutPolicy.SeedPlan(false, false, true, true), (true, true), "nothing yet, default has both: copy both");
Eq(PanelLayoutPolicy.SeedPlan(true, true, true, true), (false, false), "the character has both: copy nothing");
Eq(PanelLayoutPolicy.SeedPlan(true, false, true, true), (false, true), "only the ini missing: copy the ini");
Eq(PanelLayoutPolicy.SeedPlan(false, true, true, true), (true, false), "only panel_state missing: copy it");
Eq(PanelLayoutPolicy.SeedPlan(false, false, false, false), (false, false), "no default (a fresh install): nothing to copy");
Eq(PanelLayoutPolicy.SeedPlan(false, false, true, false), (true, false), "the default has no ini: only panel_state");
Case("seeding files");
string root = NewDir("seed");
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, DefaultIni(root));
PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\npanel.Chat=open,10,20,300,200,docked,0,0\r\n");
PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][Plugin Window##x]\nPos=5,6\nSize=100,100\n");
LayoutFiles a = PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerOne, CharA)!);
Eq(PanelLayoutFiles.SeedMissing(defaults, a), (true, true), "a new character: both copied");
Eq(File.ReadAllText(a.PanelState), File.ReadAllText(defaults.PanelState), "panel_state.txt is the default's (nothing moves the first time)");
Eq(File.ReadAllText(a.ImGuiIni), File.ReadAllText(defaults.ImGuiIni), "imgui.ini is the default's");
File.WriteAllText(a.PanelState, "# mine\r\n");
Eq(PanelLayoutFiles.SeedMissing(defaults, a), (false, false), "seeded once: the next login copies nothing");
Eq(File.ReadAllText(a.PanelState), "# mine\r\n", "the character's own places are kept");
File.Delete(a.ImGuiIni);
Eq(PanelLayoutFiles.SeedMissing(defaults, a), (false, true), "one file gone: only that one is copied");
Eq(File.ReadAllText(a.PanelState), "# mine\r\n", "...and the other is kept");
string bare = NewDir("seed-nodefault");
LayoutFiles noDefaults = PanelLayoutPolicy.DefaultFiles(bare, DefaultIni(bare));
LayoutFiles b = PanelLayoutPolicy.CharacterFiles(bare, PanelLayoutPolicy.Owner(ServerOne, CharB)!);
Eq(PanelLayoutFiles.SeedMissing(noDefaults, b), (false, false), "no default yet: nothing copied");
Check(!File.Exists(b.PanelState) && !File.Exists(b.ImGuiIni), "...and nothing made up");
Check(!File.Exists(noDefaults.PanelState) && !File.Exists(noDefaults.ImGuiIni), "the default is never written by seeding");
NoTempFiles(root);
}
private static void ResetAndMakeDefaultFiles()
{
Case("reset: the default copied over the character's");
string root = NewDir("reset");
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, DefaultIni(root));
LayoutFiles a = PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerOne, CharA)!);
PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\n");
PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][D]\n");
PanelLayoutFiles.WriteText(a.PanelState, "# old A\r\n");
PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][OldA]\n");
PanelLayoutFiles.CopyOver(defaults, a);
Eq(File.ReadAllText(a.PanelState), "# default\r\n", "panel_state.txt is the default's");
Eq(File.ReadAllText(a.ImGuiIni), "[Window][D]\n", "imgui.ini is the default's");
File.Delete(defaults.ImGuiIni);
PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][OldA]\n");
PanelLayoutFiles.CopyOver(defaults, a);
Eq(File.ReadAllText(a.ImGuiIni), "", "the default has no imgui.ini: the character's is emptied, not kept");
Case("make default: the character's layout written as the default");
PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][A]\n");
PanelLayoutFiles.MakeDefault(a, defaults, "# from A\r\n", "[Window][A now]\n");
Eq(File.ReadAllText(defaults.PanelState), "# from A\r\n", "the default panel_state.txt is the store's text");
Eq(File.ReadAllText(defaults.ImGuiIni), "[Window][A now]\n", "the default imgui.ini is the context's windows");
PanelLayoutFiles.MakeDefault(a, defaults, "# from A again\r\n", null);
Eq(File.ReadAllText(defaults.ImGuiIni), "[Window][A]\n", "no context (ImGui off): the character's imgui.ini as saved");
Eq(File.ReadAllText(a.PanelState), "# default\r\n", "the character's own files are not changed by it");
NoTempFiles(root);
}
private static void LatestTextWritesKeepTheNewest()
{
Case("imgui.ini saves: the newest text wins, never an older one after it");
var written = new List<(string, string)>();
var w = new LatestTextWrites((p, t) => written.Add((p, t)));
Check(!w.Flush("x"), "nothing queued: nothing written");
w.Queue("x", "one");
w.Queue("x", "two");
Check(w.HasPending("x"), "queued");
Check(w.Flush("x"), "flushed");
Check(written.Count == 1 && written[0] == ("x", "two"), "only the newest is written, once");
Check(!w.Flush("x"), "a later flush (the writer's queued job after shutdown wrote it) writes nothing");
w.Queue("x", "three");
w.Queue("y", "other");
w.Flush("y");
Check(written[^1] == ("y", "other") && w.HasPending("x"), "files are separate");
string root = NewDir("latest");
string path = Path.Combine(root, "a", "imgui.ini");
var real = new LatestTextWrites(PanelLayoutFiles.WriteText);
var threads = new List<Thread>();
for (int t = 0; t < 4; t++)
{
int id = t;
var th = new Thread(() => { for (int i = 0; i < 50; i++) { real.Queue(path, $"t{id} i{i}"); real.Flush(path); } });
threads.Add(th);
th.Start();
}
foreach (var th in threads) th.Join();
real.Queue(path, "last");
real.Flush(path);
Eq(File.ReadAllText(path), "last", "concurrent saves: the file holds the last one, whole");
NoTempFiles(root);
}
private static void StoreSwitchesItsFile()
{
Case("PanelStateStore: switching its file, atomic saves");
string root = NewDir("store");
string def = Path.Combine(root, "panel_state.txt");
File.WriteAllText(def, "# default\r\nbar=1,2\r\npanel.Chat=open,10,20,300,200,docked,0,0\r\n");
byte[] defBytes = File.ReadAllBytes(def);
PanelStateStore.SwitchTo(def, flushCurrent: false);
Eq(PanelStateStore.CurrentPath, def, "the store reads the file it was switched to");
Check(PanelStateStore.TryGetPanel("Chat", out var chat) && chat.Left == 10, "its panels are read");
string a = Path.Combine(root, "layouts", "s", "a", "panel_state.txt");
Directory.CreateDirectory(Path.GetDirectoryName(a)!);
File.WriteAllText(a, "# A\r\npanel.Radar=open,500,40,200,200,docked,0,0\r\nbarlayout=2,0\r\n");
PanelStateStore.SwitchTo(a, flushCurrent: false);
Check(!PanelStateStore.TryGetPanel("Chat", out _), "nothing of the old layout is left in memory");
Check(PanelStateStore.TryGetPanel("Radar", out var radar) && radar.Left == 500, "the new layout's panels");
Eq(PanelStateStore.BarRows, (2, 0), "the new layout's bar rows");
Check(PanelStateStore.BarPosition == null, "no bar row: no bar position (not the old one)");
Eq(File.ReadAllBytes(def), defBytes, "switching away from the default never writes it");
PanelStateStore.SetPanel("Radar", new PanelStateStore.PanelEntry(true, 600, 50, 200, 200));
Check(File.ReadAllText(a).Contains("panel.Radar=open,600,50", StringComparison.Ordinal), "a save goes to the character's file");
Eq(File.ReadAllBytes(def), defBytes, "...and not the default");
Check(PanelStateStore.Snapshot().Contains("panel.Radar=open,600,50", StringComparison.Ordinal), "Snapshot is the text of what is in memory");
NoTempFiles(root);
string b = Path.Combine(root, "layouts", "s", "b", "panel_state.txt");
PanelStateStore.SwitchTo(b, flushCurrent: true);
Check(!File.Exists(b), "a character without a file starts empty (no file made by reading)");
Check(!PanelStateStore.TryGetPanel("Radar", out _), "and empty in memory");
PanelStateStore.SetBarPosition(7, 8);
Check(File.Exists(b) && File.ReadAllText(b).Contains("bar=7,8", StringComparison.Ordinal), "its first save makes it");
Check(!File.ReadAllText(a).Contains("bar=7,8", StringComparison.Ordinal), "the other character's file isn't touched");
Case("PanelStateStore: Remember Open Windows off");
RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = false;
try
{
string before = File.ReadAllText(b);
PanelStateStore.SetBarPosition(9, 9);
Eq(File.ReadAllText(b), before, "off: a change isn't saved");
PanelStateStore.SwitchTo(a, flushCurrent: true);
Eq(File.ReadAllText(b), before, "off: a switch doesn't write the file it leaves either");
PanelStateStore.Flush();
Check(File.ReadAllText(a).Contains("panel.Radar", StringComparison.Ordinal), "Save Layout Now still writes (the file in use)");
}
finally
{
RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = true;
}
NoTempFiles(root);
}
// ── the session: when to switch, when panels may draw ───────────────
private static readonly LayoutOwner WhoA = PanelLayoutPolicy.Owner(ServerOne, CharA)!;
private static readonly LayoutOwner WhoB = PanelLayoutPolicy.Owner(ServerOne, CharB)!;
private static void SwitchAtLoginAndBackAtLogout()
{
Case("the switch at login and back at logout");
var s = new PanelLayoutSession();
LayoutSwitch? sw = s.Tick(0, true, inWorld: false, 0, false, null);
Check(sw is { To: null, FromKnown: false } && !sw.Value.FlushFrom, "first frame at character select: the default, nothing written out");
Check(s.ReadyToDraw(1, false, 0), "nothing draws at character select anyway: never held");
Check(s.Tick(5, true, false, 0, false, null) == null, "while it loads: no second switch");
s.MarkApplied(sw!.Value.Gen);
Check(s.Tick(10, true, false, 0, false, null) == null, "the default in place: nothing to do");
const long login = 1000;
Check(s.Tick(1000, true, inWorld: true, login, identityRecorded: false, null) == null, "login, the name not recorded yet: no switch");
Check(!s.ReadyToDraw(1000, true, login), "...and panels wait");
sw = s.Tick(1016, true, true, login, identityRecorded: true, WhoA);
Check(sw is { } x1 && Equals(x1.To, WhoA) && x1.From == null && x1.FromKnown && !x1.FlushFrom,
"the name is in: switch to the character's layout; the default is not written out");
Check(!s.ReadyToDraw(1020, true, login), "panels still wait while it loads");
s.MarkApplied(sw!.Value.Gen);
Check(s.ReadyToDraw(1040, true, login), "applied: panels draw, in the character's places");
Eq(s.AppliedLayout, WhoA, "the character's layout is the one in use");
Check(s.Tick(1050, true, true, login, true, WhoA) == null, "in the world: nothing more to switch");
sw = s.Tick(5000, true, inWorld: false, 0, true, WhoA);
Check(sw is { } x2 && x2.To == null && Equals(x2.From, WhoA) && x2.FlushFrom,
"logout: back to the default, the character's files written out first");
Check(s.ReadyToDraw(5001, false, 0), "character select: not held");
s.MarkApplied(sw!.Value.Gen);
const long relogin = 9000;
sw = s.Tick(9000, true, true, relogin, identityRecorded: true, WhoA);
Check(sw is { } x3 && Equals(x3.To, WhoA) && x3.From == null && !x3.FlushFrom, "logging back in: the character's layout again");
Check(!s.ReadyToDraw(9001, true, relogin), "...held until it is in place");
s.MarkApplied(sw!.Value.Gen);
Check(s.ReadyToDraw(9002, true, relogin), "...then drawn");
Case("the setting changed in the world: switch, without hiding the panels");
sw = s.Tick(9100, perCharacter: false, true, relogin, true, WhoA);
Check(sw is { } x4 && x4.To == null && x4.FlushFrom, "off: to the default (the character's written out)");
Check(s.ReadyToDraw(9101, true, relogin), "the panels keep drawing while it loads");
s.MarkApplied(sw!.Value.Gen);
sw = s.Tick(9200, perCharacter: true, true, relogin, true, WhoA);
Check(sw is { } x5 && Equals(x5.To, WhoA) && !x5.FlushFrom, "on again: to the character's (the default not written)");
s.MarkApplied(sw!.Value.Gen);
}
private static void HotReloadUsesTheCharactersFilesFromTheFirstFrame()
{
Case("hot reload in the world: the character's files from the first frame");
// The new engine marks the login at init (MarkAlreadyComplete) and records the name; its
// session is new. Simulated frame by frame: drawing is allowed only with the character's
// layout applied, never with the default while in the world.
foreach (bool frameBeforeLoginMark in new[] { false, true })
{
var s = new PanelLayoutSession();
long login = 50_000;
LayoutOwner? applied = null;
bool anyApplied = false, drewWithDefault = false, drewWithCharacter = false;
LayoutSwitch? inFlight = null;
int switchesToCharacter = 0;
for (long t = 49_990; t < 50_200; t += 16)
{
bool inWorld = !frameBeforeLoginMark || t >= login;
bool recorded = inWorld && t >= login + 16; // the name lands a frame after the mark
// A switch asked for one frame is loaded by the writer and applied the next.
if (inFlight is { } done)
{
s.MarkApplied(done.Gen);
applied = done.To;
anyApplied = true;
inFlight = null;
}
LayoutSwitch? sw = s.Tick(t, true, inWorld, inWorld ? login : 0, recorded, recorded ? WhoA : null);
if (sw is { } x)
{
inFlight = x;
if (Equals(x.To, WhoA)) switchesToCharacter++;
}
if (inWorld && s.ReadyToDraw(t, true, login))
{
if (!anyApplied || applied == null) drewWithDefault = true;
else if (Equals(applied, WhoA)) drewWithCharacter = true;
}
}
string how = frameBeforeLoginMark ? " (a frame ran before the login was marked)" : "";
Check(!drewWithDefault, "panels never drew with the default layout in the world" + how);
Check(drewWithCharacter, "panels drew with the character's layout" + how);
Eq(switchesToCharacter, 1, "one switch to the character" + how);
}
Case("hot reload: the first switch goes straight to the character");
var direct = new PanelLayoutSession();
Check(direct.Tick(100, true, true, 100, identityRecorded: false, null) == null, "login marked, name not yet: no switch to the default first");
LayoutSwitch? first = direct.Tick(116, true, true, 100, true, WhoA);
Check(first is { } f && Equals(f.To, WhoA) && !f.FromKnown && !f.FlushFrom, "the first switch is the character's, nothing written out");
Check(!direct.ReadyToDraw(117, true, 100), "no frame draws before it is applied");
direct.MarkApplied(first!.Value.Gen);
Check(direct.ReadyToDraw(132, true, 100), "applied: the first frame that draws uses it");
Case("a login time not set yet in the world: wait for it");
var early = new PanelLayoutSession();
Check(early.Tick(10_000, true, inWorld: true, loginAtMs: 0, identityRecorded: true, WhoA) == null, "the flag without its time: no decision");
Check(!early.ReadyToDraw(10_000, true, 0), "...and no drawing");
}
private static void IdentityThatNeverComes()
{
Case("a name that never comes: the default after the wait");
var s = new PanelLayoutSession();
s.MarkApplied(s.Tick(0, true, false, 0, false, null)!.Value.Gen);
const long login = 2000;
Check(s.Tick(2000 + PanelLayoutPolicy.IdentityWaitMs - 1, true, true, login, false, null) == null, "just before the wait ends: still waiting");
Check(!s.ReadyToDraw(2000 + PanelLayoutPolicy.IdentityWaitMs - 1, true, login), "...not drawn");
Check(s.Tick(2000 + PanelLayoutPolicy.IdentityWaitMs, true, true, login, false, null) == null, "the wait over, no name: the default already in use, no switch");
Check(s.ReadyToDraw(2000 + PanelLayoutPolicy.IdentityWaitMs, true, login), "...and the panels draw with it");
var t = new PanelLayoutSession();
t.MarkApplied(t.Tick(0, true, false, 0, false, null)!.Value.Gen);
LayoutSwitch? late = t.Tick(login + PanelLayoutPolicy.IdentityWaitMs, true, true, login, false, WhoB);
Check(late is { } l && Equals(l.To, WhoB), "the wait over, a name known but never recorded: that name's layout");
}
private static void OneSwitchAtATimeAndReset()
{
Case("one switch at a time");
var s = new PanelLayoutSession();
LayoutSwitch first = s.Tick(0, true, false, 0, false, null)!.Value;
Check(s.InFlight, "in flight");
Check(s.Tick(1, true, true, 1, true, WhoA) == null, "the login during it: no second switch yet");
Check(!s.ReadyToDraw(2, true, 1), "...and nothing draws (the default isn't the login's layout)");
s.MarkApplied(first.Gen);
Check(!s.ReadyToDraw(3, true, 1), "the default applied: still not the login's layout");
LayoutSwitch next = s.Tick(4, true, true, 1, true, WhoA)!.Value;
Check(Equals(next.To, WhoA) && next.Gen == first.Gen + 1, "after it: the character's");
s.MarkApplied(first.Gen);
Check(s.InFlight, "an old switch marked again doesn't count");
s.MarkApplied(next.Gen);
Check(!s.InFlight && s.ReadyToDraw(5, true, 1), "done");
Case("a stuck switch stops holding the panels");
var stuck = new PanelLayoutSession();
stuck.Tick(10, true, true, 10, true, WhoA);
Check(!stuck.ReadyToDraw(10 + PanelLayoutPolicy.ApplyGiveUpMs - 1, true, 10), "held while it may still come");
Check(stuck.ReadyToDraw(10 + PanelLayoutPolicy.ApplyGiveUpMs, true, 10), "drawn after the give-up time");
Case("reset: the character's files reseeded from the default");
s.WantReseed();
LayoutSwitch? reset = s.Tick(6, true, true, 1, true, WhoA);
Check(reset is { } r && r.Reseed && Equals(r.To, WhoA) && Equals(r.From, WhoA) && !r.FlushFrom,
"a reseed switch to the same character, its current files not written out (they're being replaced)");
Check(s.ReadyToDraw(7, true, 1), "the panels keep drawing while it loads");
s.MarkApplied(reset!.Value.Gen);
Check(s.Tick(8, true, true, 1, true, WhoA) == null, "once: no second reset");
var none = new PanelLayoutSession();
none.MarkApplied(none.Tick(0, true, false, 0, false, null)!.Value.Gen);
none.WantReseed();
Check(none.Tick(1, true, false, 0, false, null) == null, "no character layout in use: a reset does nothing");
}
private static void TwoSessionsNeverShareAFile()
{
Case("two clients' sessions: the files each one writes are its own");
string root = @"C:\Users\Someone\AppData\Local\RynthCore";
string ini = @"C:\Games\RynthSuite\RynthAi\imgui.ini";
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini);
var written = new Dictionary<LayoutOwner, HashSet<string>> { [WhoA] = new(), [WhoB] = new() };
foreach (LayoutOwner who in new[] { WhoA, WhoB })
{
var s = new PanelLayoutSession();
long t = 0;
void Step(bool inWorld, long login)
{
LayoutSwitch? sw = s.Tick(t += 16, true, inWorld, login, true, who);
if (sw is not { } x) return;
// What a switch writes: the layout left (when FlushFrom) and the one it goes to (seeding).
if (x.FlushFrom) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, x.From); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); }
if (x.To != null) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, x.To); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); }
s.MarkApplied(x.Gen);
// In the world the saves go to the layout in use.
if (inWorld && s.AppliedLayout is { } inUse) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, inUse); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); }
}
Step(false, 0); Step(true, 100); Step(true, 100); Step(false, 0); Step(true, 900); Step(true, 900);
}
Check(written[WhoA].Count > 0 && written[WhoB].Count > 0, "both wrote their layouts");
Check(!written[WhoA].Overlaps(written[WhoB]), "client A and client B never write the same file");
Check(!written[WhoA].Contains(defaults.PanelState) && !written[WhoA].Contains(defaults.ImGuiIni)
&& !written[WhoB].Contains(defaults.PanelState) && !written[WhoB].Contains(defaults.ImGuiIni),
"neither writes the default (in the world, at a switch or a logout)");
}
// Two clients at once: child processes of this test, each a client of one character.
private static void TwoClientsNeverWriteEachOthersFiles()
{
Case("two clients at once, two characters: each writes only its own files");
string root = NewDir("clients");
string ini = DefaultIni(root);
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini);
PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\npanel.Shared=open,1,2,300,200,docked,0,0\r\n");
PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][Shared]\nPos=1,2\n");
byte[] defPanel = File.ReadAllBytes(defaults.PanelState), defIni = File.ReadAllBytes(defaults.ImGuiIni);
var clients = new[] { (ServerOne, CharA), (ServerOne, CharB), (ServerTwo, CharA) };
var procs = new List<Process>();
foreach (var (server, character) in clients)
{
string self = Environment.ProcessPath!;
var psi = new ProcessStartInfo(self) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
// Run as "dotnet PanelLayoutTests.dll": the child is the same dll.
if (Path.GetFileNameWithoutExtension(self).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
psi.ArgumentList.Add(typeof(Program).Assembly.Location);
foreach (string a in new[] { "--client", root, ini, server, character, "150" }) psi.ArgumentList.Add(a);
procs.Add(Process.Start(psi)!);
}
for (int i = 0; i < procs.Count; i++)
{
string output = procs[i].StandardOutput.ReadToEnd() + procs[i].StandardError.ReadToEnd();
procs[i].WaitForExit();
Check(procs[i].ExitCode == 0, $"client {i + 1} ran ({output.Trim()})");
}
Eq(File.ReadAllBytes(defaults.PanelState), defPanel, "the default panel_state.txt is unchanged");
Eq(File.ReadAllBytes(defaults.ImGuiIni), defIni, "the default imgui.ini is unchanged");
foreach (var (server, character) in clients)
{
LayoutOwner who = PanelLayoutPolicy.Owner(server, character)!;
LayoutFiles f = PanelLayoutPolicy.CharacterFiles(root, who);
string panel = File.Exists(f.PanelState) ? File.ReadAllText(f.PanelState) : "";
string iniText = File.Exists(f.ImGuiIni) ? File.ReadAllText(f.ImGuiIni) : "";
string mark = Marker(server, character);
Check(panel.Contains("panel." + mark + "=", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: its own panels are in its file");
Check(panel.Contains("panel.Shared=", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: seeded from the default");
Check(panel.Contains("panel.Last=open,149,", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: the last save is the one on disk");
Check(iniText.Contains("[Window][" + mark + "]", StringComparison.Ordinal) && iniText.Contains("Pos=149,149", StringComparison.Ordinal),
$"{PanelLayoutPolicy.Describe(who)}: its imgui.ini holds its own last save");
foreach (var (os, oc) in clients)
{
if (os == server && oc == character) continue;
string other = Marker(os, oc);
Check(!panel.Contains(other, StringComparison.Ordinal) && !iniText.Contains(other, StringComparison.Ordinal),
$"{PanelLayoutPolicy.Describe(who)}'s files have nothing of {os}/{oc}");
}
}
NoTempFiles(root);
}
private static string Marker(string server, string character) => ("M_" + server + "_" + character).Replace(' ', '_');
/// <summary>A client (child process): character select on the default, a login to its character, saves, a logout.</summary>
private static int Client(string[] a)
{
try
{
string root = a[0], ini = a[1], server = a[2], character = a[3];
int saves = int.Parse(a[4]);
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini);
PanelStateStore.SwitchTo(defaults.PanelState, flushCurrent: false); // character select: the default
LayoutOwner who = PanelLayoutPolicy.Owner(server, character)!;
LayoutFiles mine = PanelLayoutPolicy.CharacterFiles(root, who);
// The login: seed, switch (the default is never written out).
PanelLayoutFiles.SeedMissing(defaults, mine);
PanelStateStore.SwitchTo(mine.PanelState, flushCurrent: false);
var iniWrites = new LatestTextWrites(PanelLayoutFiles.WriteText);
string mark = Marker(server, character);
for (int i = 0; i < saves; i++)
{
PanelStateStore.SetPanel(mark, new PanelStateStore.PanelEntry(true, i, i, 200, 100));
PanelStateStore.SetPanel("Last", new PanelStateStore.PanelEntry(true, i, i, 200, 100));
PanelStateStore.SetBarPosition(i, i);
iniWrites.Queue(mine.ImGuiIni, $"[Window][{mark}]\nPos={i},{i}\nSize=100,100\n");
iniWrites.Flush(mine.ImGuiIni);
}
// The logout: the character's written out, back to the default (not written).
PanelStateStore.SwitchTo(defaults.PanelState, flushCurrent: true);
Console.WriteLine("client ok");
return 0;
}
catch (Exception ex)
{
Console.WriteLine($"client threw {ex.GetType().Name}: {ex.Message}");
return 2;
}
}
// ── saving rules and the commands ─────────────────────────────────
private static void AutoSaveRules()
{
Case("automatic imgui.ini saves");
Check(PanelLayoutPolicy.MayAutoSaveIni(characterLayout: true, perCharacter: true, inWorld: true, contextHeldCharacter: true), "a character's layout: always saved");
Check(PanelLayoutPolicy.MayAutoSaveIni(true, true, inWorld: false, contextHeldCharacter: true), "...also at a logout's last save");
Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: true, contextHeldCharacter: true), "the setting off: the shared default is saved, as before");
Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: false, contextHeldCharacter: false), "the setting off, at character select: saved, as before");
Check(PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: false), "in the world with no character name (the default in use): saved, as before");
Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: false),
"character select with the setting on: the default isn't written (it could undo another client's /rc layout default)");
Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: true), "the default after a character logged out: not saved (its windows would leak into it)");
Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: true), "the default in the world after a character's layout was used: not saved");
}
private static void CommandReplies()
{
Case("/rc layout: parsing");
Eq(PanelLayoutPolicy.ParseCommand(""), LayoutCommand.Status, "alone: the status");
Eq(PanelLayoutPolicy.ParseCommand(null), LayoutCommand.Status, "null: the status");
Eq(PanelLayoutPolicy.ParseCommand(" STATUS "), LayoutCommand.Status, "status, any case");
Eq(PanelLayoutPolicy.ParseCommand("default"), LayoutCommand.MakeDefault, "default");
Eq(PanelLayoutPolicy.ParseCommand("reset"), LayoutCommand.ResetAsk, "reset alone asks");
Eq(PanelLayoutPolicy.ParseCommand("reset Confirm"), LayoutCommand.ResetConfirm, "reset confirm, any spacing and case");
foreach (string bad in new[] { "frob", "default now", "reset now", "confirm", "reset confirm please" })
Eq(PanelLayoutPolicy.ParseCommand(bad), LayoutCommand.Invalid, $"'{bad}' is not a form");
Case("/rc layout: the check before it runs (ChatCommandReplies)");
foreach (string ok in new[] { "layout", "layout status", "layout default", "layout reset", "layout reset confirm", "LAYOUT Reset confirm" })
{
ChatVerbCheck c = ChatCommandReplies.Check(ok);
Check(c.Problem == null && c.Verb?.Name == "layout", $"'/rc {ok}' runs");
}
foreach (string bad in new[] { "layout frob", "layout default now", "layout reset please" })
{
ChatVerbCheck c = ChatCommandReplies.Check(bad);
Check(c.Verb?.Name == "layout" && c.Problem == PanelLayoutPolicy.Usage, $"'/rc {bad}' answers with the usage");
}
Eq(ChatCommandReplies.Usage("layout"), PanelLayoutPolicy.Usage, "the catalog's usage is the policy's");
Check(ChatCommandReplies.CommandList().Contains("layout", StringComparison.Ordinal), "/rc lists layout");
Check(ChatCommandReplies.KindOfLine(PanelLayoutPolicy.Usage) == ChatReplyKind.Fail, "the usage is a failure (red)");
Case("/rc layout: the status");
string root = @"C:\L", ini = @"C:\G\imgui.ini";
LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini);
LayoutFiles mine = PanelLayoutPolicy.CharacterFiles(root, WhoA);
string[] own = PanelLayoutPolicy.StatusLines(WhoA, mine, DefaultReason.None, defaults, true);
Check(own[0].Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && own[0].Contains(mine.PanelState, StringComparison.Ordinal)
&& own[0].Contains(mine.ImGuiIni, StringComparison.Ordinal), "a character's: whose, and both files");
Check(own.Length == 2 && own[1].Contains(defaults.PanelState, StringComparison.Ordinal) && own[1].Contains("/rc layout default", StringComparison.Ordinal)
&& own[1].Contains("/rc layout reset", StringComparison.Ordinal), "...and the default's files and the two commands");
Check(ChatCommandReplies.KindOfLines(own) == ChatReplyKind.Ok, "a state, not a failure");
foreach (DefaultReason why in new[] { DefaultReason.SettingOff, DefaultReason.NotInWorld, DefaultReason.NoCharacterName, DefaultReason.WaitingForName })
{
string[] d = PanelLayoutPolicy.StatusLines(null, defaults, why, defaults, perCharacter: why != DefaultReason.SettingOff);
Check(d[0].StartsWith("Panel layout: the PC-wide default (", StringComparison.Ordinal) && d[0].Contains(PanelLayoutPolicy.ReasonText(why), StringComparison.Ordinal)
&& d[0].Contains(defaults.PanelState, StringComparison.Ordinal) && d[0].Contains(defaults.ImGuiIni, StringComparison.Ordinal),
$"the default ({why}): why, and both files");
Check(ChatCommandReplies.KindOfLines(d) == ChatReplyKind.Ok, $"the default ({why}): a state");
}
string[] off = PanelLayoutPolicy.StatusLines(null, defaults, DefaultReason.NotRunning, defaults, false);
Check(off.Length == 1 && ChatCommandReplies.KindOfLine(off[0]) == ChatReplyKind.Fail, "not running: a failure, says why");
Case("/rc layout default and reset: why they can't run");
Check(PanelLayoutPolicy.CharacterLayoutProblem("x", true, true, true, WhoA, false) == null, "a character's layout in use: they run");
(bool running, bool per, bool inWorld, LayoutOwner? inUse, bool switching, string want)[] cases =
{
(false, true, true, WhoA, false, PanelLayoutPolicy.ReasonText(DefaultReason.NotRunning)),
(true, false, true, WhoA, false, PanelLayoutPolicy.ReasonText(DefaultReason.SettingOff)),
(true, true, false, null, false, PanelLayoutPolicy.ReasonText(DefaultReason.NotInWorld)),
(true, true, true, WhoA, true, "still switching"),
(true, true, true, null, false, PanelLayoutPolicy.ReasonText(DefaultReason.NoCharacterName)),
};
foreach (var c in cases)
{
string? p = PanelLayoutPolicy.CharacterLayoutProblem("make a default from this client", c.running, c.per, c.inWorld, c.inUse, c.switching);
Check(p != null && p.StartsWith("Can't make a default from this client: ", StringComparison.Ordinal) && p.Contains(c.want, StringComparison.Ordinal)
&& p.EndsWith(PanelLayoutPolicy.Usage, StringComparison.Ordinal), $"why not ({c.want}), with the usage: {p}");
Check(ChatCommandReplies.KindOfLine(p ?? "") == ChatReplyKind.Fail, $"a failure (red): {c.want}");
}
Case("/rc layout default and reset: the answers");
string ask = PanelLayoutPolicy.ResetAskReply(WhoA, defaults);
Check(ask.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && ask.Contains("/rc layout reset confirm", StringComparison.Ordinal)
&& ask.Contains(defaults.PanelState, StringComparison.Ordinal), "reset asks first: whose, from which file, and the confirm");
Check(ChatCommandReplies.KindOfLine(ask) == ChatReplyKind.Ok, "...as a state (nothing failed)");
string done = PanelLayoutPolicy.ResetDoneReply(WhoA);
Check(done.StartsWith(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && ChatCommandReplies.KindOfLine(done) == ChatReplyKind.Ok, "reset done");
string made = PanelLayoutPolicy.MakeDefaultDoneReply(WhoA, defaults);
Check(made.Contains(defaults.PanelState, StringComparison.Ordinal) && made.Contains(defaults.ImGuiIni, StringComparison.Ordinal)
&& ChatCommandReplies.KindOfLine(made) == ChatReplyKind.Ok, "make default done: the default's files");
string failed = PanelLayoutPolicy.FailedReply("make the default", "access denied");
Eq(failed, "Can't make the default: access denied.", "a failed file job says what and why");
Check(ChatCommandReplies.KindOfLine(failed) == ChatReplyKind.Fail, "...as a failure");
Check(ChatCommandReplies.KindOfLine(PanelLayoutPolicy.BusyReply) == ChatReplyKind.Fail && PanelLayoutPolicy.BusyReply.EndsWith(PanelLayoutPolicy.Usage, StringComparison.Ordinal),
"busy: a failure, with the usage");
Case("Settings > Display: the layout in use and the reset button");
string line = PanelLayoutPolicy.SettingsLine(WhoA, mine, DefaultReason.None);
Check(line.StartsWith("In use: ", StringComparison.Ordinal) && line.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal)
&& line.Contains(mine.Folder, StringComparison.Ordinal), $"a character's: whose, and its folder ({line})");
Check(!line.Contains(defaults.PanelState, StringComparison.Ordinal), "...not the default's file");
foreach (DefaultReason why in new[] { DefaultReason.SettingOff, DefaultReason.NotInWorld, DefaultReason.NoCharacterName, DefaultReason.WaitingForName })
{
string d = PanelLayoutPolicy.SettingsLine(null, defaults, why);
Check(d.StartsWith("In use: the PC-wide default (", StringComparison.Ordinal) && d.Contains(PanelLayoutPolicy.ReasonText(why), StringComparison.Ordinal)
&& d.Contains(defaults.PanelState, StringComparison.Ordinal), $"the default ({why}): why, and its file");
}
Check(PanelLayoutPolicy.SettingsLine(null, defaults, DefaultReason.NotRunning).Contains(PanelLayoutPolicy.ReasonText(DefaultReason.NotRunning), StringComparison.Ordinal),
"not running: says so");
string confirm = PanelLayoutPolicy.ResetConfirmText(WhoA);
Check(confirm.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && confirm.EndsWith("can't be undone.", StringComparison.Ordinal),
"the reset asks first: whose layout, and that it can't be undone");
Check(PanelLayoutPolicy.ResetConfirmText(null).Contains("nothing to reset", StringComparison.Ordinal), "no character's layout: nothing to reset");
// The button runs /rc layout reset confirm, the form the command takes.
Eq(PanelLayoutPolicy.ParseCommand("reset confirm"), LayoutCommand.ResetConfirm, "the button's command is reset confirm");
}
// ── helpers ────────────────────────────────────────────────────────
private static void NoTempFiles(string dir)
{
string[] left = Directory.GetFiles(dir, "*.tmp", SearchOption.AllDirectories);
Check(left.Length == 0, "no temp file left behind" + (left.Length > 0 ? ": " + string.Join(", ", left) : ""));
}
private static void Case(string name)
{
_case = name;
Console.WriteLine($"-- {name}");
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
private static void Eq<T>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected '{Show(expected)}', got '{Show(actual)}'");
private static void Eq(byte[] actual, byte[] expected, string what) =>
Check(actual.AsSpan().SequenceEqual(expected), what);
private static string Show<T>(T v) => v switch
{
null => "null",
string s => s,
_ => v.ToString() ?? "",
};
}
}

View file

@ -15,6 +15,8 @@
monster plates' and your plate's "Debuff icon size" default 100 %, an older file loads 100 %, they clamp to
50-200, round-trip on their own (apart from the text sizes), reset with the sizes, the chat form parses; the
row's lengths at 100 % are the old expressions exactly at every scale, and its height and width grow with it.
Also "Refresh others' health" (2026-10-31; src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs compiled in for its
range): on at 1 s by default and from an older file, round-trips, the interval clamps, reset restores it.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
@ -28,6 +30,7 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs" Link="Engine\MonsterHudSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs" Link="Engine\HealthProbe.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ArgbOpacity.cs" Link="Engine\ArgbOpacity.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\PlateClass.cs" Link="Engine\PlateClass.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\PlateMetrics.cs" Link="Engine\PlateMetrics.cs" />

View file

@ -56,6 +56,9 @@ namespace PlateSizingTests
DebuffRowScalesWithTheSetting();
DebuffRowWidthAndCover();
HealthRefreshDefaultsOn();
HealthRefreshRoundTripAndClamp();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED.");
@ -583,6 +586,48 @@ namespace PlateSizingTests
// ── harness ─────────────────────────────────────────────────────────
// ── refresh others' health (HealthProbe) ────────────────────────────
private static void HealthRefreshDefaultsOn()
{
Case("refresh others' health: on at 1 s by default, and after loading a file from before it");
S.ResetToDefaults();
Check(S.RefreshOthersHealth, "on by default");
Check(S.HealthRefreshSec == HealthProbe.DefaultIntervalSec && HealthProbe.DefaultIntervalSec == 1f, "1 s by default");
Check(HealthProbe.MinIntervalSec <= 1f && 1f <= HealthProbe.MaxIntervalSec, "the range holds the default");
string[] old = Written().Where(l => !l.StartsWith("refreshOthersHealth=", StringComparison.Ordinal) &&
!l.StartsWith("healthRefreshSec=", StringComparison.Ordinal)).ToArray();
Check(old.Length == Written().Length - 2, "the old file lacks exactly the two keys");
S.RefreshOthersHealth = false; S.HealthRefreshSec = 4f;
S.ResetToDefaults();
S.ApplyLines(old);
Check(S.RefreshOthersHealth && S.HealthRefreshSec == 1f, "on at 1 s after loading the old file");
Check(S.Describe().Contains("refresh others' health every 1.0 s"), "status line: " + S.Describe());
}
private static void HealthRefreshRoundTripAndClamp()
{
Case("refresh others' health: off and an interval round-trip, the interval clamps, reset restores");
S.ResetToDefaults();
S.RefreshOthersHealth = false; S.HealthRefreshSec = 2.5f;
string[] lines = Written();
Check(lines.Contains("refreshOthersHealth=0") && lines.Contains("healthRefreshSec=2.5"), "refreshOthersHealth=0, healthRefreshSec=2.5 written");
S.ResetToDefaults();
S.ApplyLines(lines);
Check(!S.RefreshOthersHealth && S.HealthRefreshSec == 2.5f, "off, 2.5 s after reload");
Check(lines.SequenceEqual(Written()), "identical text after a reload");
Check(S.Describe().Contains("refresh others' health off"), "status line says off");
S.ApplyLines(new[] { "healthRefreshSec=0.01" });
Check(S.HealthRefreshSec == HealthProbe.MinIntervalSec, $"0.01 floored at {HealthProbe.MinIntervalSec}");
S.ApplyLines(new[] { "healthRefreshSec=60" });
Check(S.HealthRefreshSec == HealthProbe.MaxIntervalSec, $"60 capped at {HealthProbe.MaxIntervalSec}");
S.ApplyLines(new[] { "healthRefreshSec=abc", "healthRefreshSec=" });
Check(S.HealthRefreshSec == HealthProbe.MaxIntervalSec, "junk leaves it alone");
S.ResetToDefaults();
Check(S.RefreshOthersHealth && S.HealthRefreshSec == 1f, "reset: on at 1 s");
S.ResetToDefaults();
}
private static void Case(string name)
{
_case = name;

View file

@ -40,6 +40,7 @@ namespace RadarSettingsTests
Run("CorpsesOffHidesYourCorpses", CorpsesOffHidesYourCorpses);
Run("UnknownKindsHidden", UnknownKindsHidden);
Run("SnapshotFiltersPerBox", SnapshotFiltersPerBox);
Run("SelectionDefaults", SelectionDefaults); // before FileRoundTrip: the store loads once, there
Run("FileRoundTrip", () => FileRoundTrip(root));
Run("NameAndSizeDefaults", NameAndSizeDefaults);
Run("NameAndSizeFileRoundTrip", () => NameAndSizeFileRoundTrip(root));
@ -47,6 +48,10 @@ namespace RadarSettingsTests
Run("WorldMapBackdropSettings", () => WorldMapBackdropSettings(root));
Run("RoundRadarAndClipping", () => RoundRadarAndClipping(root));
Run("ClickThroughWheelZoom", () => ClickThroughWheelZoom(root));
Run("SelectionSettingsSave", () => SelectionSettingsSave(root));
Run("WhichMarkerIsSelected", WhichMarkerIsSelected);
Run("SelectionEdgeArrow", SelectionEdgeArrow);
Run("SelectionLabelPlacement", SelectionLabelPlacement);
}
finally
{
@ -144,11 +149,21 @@ namespace RadarSettingsTests
var lines = new List<string> { "# test" };
for (int k = 0; k < RadarKind.Count; k++)
lines.Add($"{FileKeys[k]}={(k % 2 == 0 ? 0 : 1)}"); // even kinds off
// The selected-object highlight's three keys (the store loads once per process: here).
lines.Add("selectHighlight=0");
lines.Add("selectLabel=0");
lines.Add("selectedColor=FF112233");
File.WriteAllLines(seed, lines);
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", seed);
RadarSettingsStore.Load();
for (byte k = 0; k < RadarKind.Count; k++)
Check(RadarSettingsStore.ShowFlag(k) == (k % 2 == 1), $"loaded {FileKeys[k]}");
Check(!RadarSettingsStore.HighlightSelected, "loaded selectHighlight=0");
Check(!RadarSettingsStore.ShowSelectedLabel, "loaded selectLabel=0");
Check(RadarSettingsStore.SelectedColor == 0xFF112233, $"loaded selectedColor ({RadarSettingsStore.SelectedColor:X8})");
RadarSettingsStore.HighlightSelected = true;
RadarSettingsStore.ShowSelectedLabel = true;
RadarSettingsStore.SelectedColor = RadarSettingsStore.DefaultSelectedColor;
string saved = Path.Combine(root, "saved.txt");
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved);
@ -343,6 +358,156 @@ namespace RadarSettingsTests
Check(n >= 3 && Math.Abs(Area(outP, n) - circle / 2) < circle * 0.01f, $"half the circle ({Area(outP, n)} of {circle / 2})");
}
// ── The selected-object highlight (2026-10-31) ──────────────────────
// The ring starts on, its label off (the box covered the radar); the ring's colour is none of the kinds' default colours.
private static void SelectionDefaults()
{
Check(RadarSettingsStore.HighlightSelected, "highlight the selected object: on by default");
Check(!RadarSettingsStore.ShowSelectedLabel, "show its label: off by default");
Check(RadarSettingsStore.SelectedColor == RadarSettingsStore.DefaultSelectedColor, "ring colour default");
Check(Array.IndexOf(RadarSettingsStore.DefaultKindColors, RadarSettingsStore.DefaultSelectedColor) < 0,
"the ring's default colour is no kind's default colour");
}
// The switches save under their keys; the colour only when it isn't the default; Reset colours resets it.
private static void SelectionSettingsSave(string root)
{
string saved = Path.Combine(root, "selection.txt");
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved);
RadarSettingsStore.HighlightSelected = true;
RadarSettingsStore.ShowSelectedLabel = true;
RadarSettingsStore.SelectedColor = RadarSettingsStore.DefaultSelectedColor;
RadarSettingsStore.Save();
string text = File.ReadAllText(saved).Replace("\r\n", "\n");
Check(text.Contains("selectHighlight=1\n"), "saved selectHighlight=1");
Check(text.Contains("selectLabel=1\n"), "saved selectLabel=1");
Check(!text.Contains("selectedColor="), "the default colour is not written");
RadarSettingsStore.HighlightSelected = false;
RadarSettingsStore.ShowSelectedLabel = false;
RadarSettingsStore.SelectedColor = 0x80ABCDEF;
RadarSettingsStore.Save();
text = File.ReadAllText(saved).Replace("\r\n", "\n");
Check(text.Contains("selectHighlight=0\n"), "saved selectHighlight=0");
Check(text.Contains("selectLabel=0\n"), "saved selectLabel=0");
Check(text.Contains("selectedColor=80ABCDEF\n"), "saved selectedColor=80ABCDEF");
RadarSettingsStore.ResetKindColors();
Check(RadarSettingsStore.SelectedColor == RadarSettingsStore.DefaultSelectedColor, "Reset colours resets the ring's colour");
RadarSettingsStore.HighlightSelected = true;
RadarSettingsStore.ShowSelectedLabel = true;
}
private static RadarMarker Mk(byte kind, uint id, float x = 0, float y = 0) =>
new() { Kind = kind, Id = id, X = x, Y = y, Label = "m" + id };
// The selected marker is the one with the selected object's id; it clears with the selection, when
// the object leaves the markers, or when the setting is off; a hidden kind is still found.
private static void WhichMarkerIsSelected()
{
var markers = new List<RadarMarker>
{
Mk(RadarKind.Monster, 0x80000001), Mk(RadarKind.Portal, 0x70000002), Mk(RadarKind.Corpse, 0x80000003),
Mk(RadarKind.Door, 0x70000004), Mk(RadarKind.GroundItem, 0x80000005),
};
Check(RadarSelection.Find(markers, 0x70000002) == markers[1], "the portal's id finds the portal");
Check(RadarSelection.Find(markers, 0x80000003) == markers[2], "the corpse's id finds the corpse");
Check(RadarSelection.Find(markers, 0) == null, "nothing selected: none");
Check(RadarSelection.Find(markers, 0x12345678) == null, "an object with no marker (in a pack, gone): none");
Check(RadarSelection.Find(null, 0x80000001) == null, "no snapshot yet: none");
// Old RynthAi builds send no ids: a marker with id 0 is never the selection.
var noIds = new List<RadarMarker> { Mk(RadarKind.Monster, 0), Mk(RadarKind.Npc, 0) };
Check(RadarSelection.Find(noIds, 0) == null && RadarSelection.Find(noIds, 0x80000001) == null, "markers without ids never match");
// A kind this engine doesn't know (a newer RynthAi's): never highlighted (no shape or colour for it).
Check(RadarSelection.Find(new List<RadarMarker> { Mk(12, 0x80000009) }, 0x80000009) == null, "an unknown kind: none");
// The setting off: nothing is highlighted.
Check(RadarSelection.Highlighted(false, markers, 0x80000001) == null, "setting off: none");
Check(RadarSelection.Highlighted(true, markers, 0x80000001) == markers[0], "setting on: the monster");
// It follows the selection, and clears when the selection clears.
Check(RadarSelection.Highlighted(true, markers, 0x70000004) == markers[3], "selection moves to the door");
Check(RadarSelection.Highlighted(true, markers, 0) == null, "selection cleared: none");
// It follows the object as it moves: the next snapshot's marker (a new instance) is found by id.
var next = new List<RadarMarker> { Mk(RadarKind.Monster, 0x80000001, 25, -10) };
RadarMarker? moved = RadarSelection.Highlighted(true, next, 0x80000001);
Check(moved != null && moved.X == 25 && moved.Y == -10, "the moved monster's new marker");
// ...and the object leaving the radar's markers clears it, though it is still selected.
Check(RadarSelection.Highlighted(true, new List<RadarMarker>(), 0x80000001) == null, "left the markers: none");
// A kind whose box is off is still highlighted when it is the selection (items on the ground start hidden).
RadarSettingsStore.ShowGroundItems = false;
Check(RadarSelection.Highlighted(true, markers, 0x80000005) == markers[4], "a hidden kind's selected item is still found");
RadarSettingsStore.ShowGroundItems = true;
}
private static bool Near(System.Numerics.Vector2 a, System.Numerics.Vector2 b, float tol = 0.01f) =>
Math.Abs(a.X - b.X) <= tol && Math.Abs(a.Y - b.Y) <= tol;
// The arrow sits inset inside the picture's edge, on the line from the centre toward the marker.
private static void SelectionEdgeArrow()
{
var min = new System.Numerics.Vector2(0, 0);
var max = new System.Numerics.Vector2(200, 200);
var c = new System.Numerics.Vector2(100, 100);
System.Numerics.Vector2 tip, dir;
Check(!RadarSelection.EdgeArrow(c, new(150, 40), min, max, null, 3, out _, out _), "on the picture: no arrow");
Check(!RadarSelection.EdgeArrow(c, max, min, max, null, 3, out _, out _), "on the picture's corner: no arrow");
Check(!RadarSelection.EdgeArrow(c, c, min, max, null, 3, out _, out _), "at the centre: no arrow");
Check(!RadarSelection.EdgeArrow(c, new(float.NaN, 5), min, max, null, 3, out _, out _), "a NaN position: no arrow");
Check(RadarSelection.EdgeArrow(c, new(100, -50), min, max, null, 3, out tip, out dir)
&& Near(tip, new(100, 3)) && Near(dir, new(0, -1)), $"straight up: top edge ({tip}, {dir})");
Check(RadarSelection.EdgeArrow(c, new(400, 100), min, max, null, 3, out tip, out dir)
&& Near(tip, new(197, 100)) && Near(dir, new(1, 0)), $"right: right edge ({tip})");
Check(RadarSelection.EdgeArrow(c, new(-1000, -1000), min, max, null, 3, out tip, out _)
&& Near(tip, new(3, 3)), $"up-left far away: the corner ({tip})");
Check(RadarSelection.EdgeArrow(c, new(300, 150), min, max, null, 3, out tip, out _)
&& Near(tip, new(197, 124.25f)), $"right and a little down: the right edge, a quarter down ({tip})");
// Off-centre panel, wider than tall: the nearer side wins.
var wMin = new System.Numerics.Vector2(10, 20);
var wMax = new System.Numerics.Vector2(410, 120);
Check(RadarSelection.EdgeArrow(new(210, 70), new(410, 270), wMin, wMax, null, 0, out tip, out _)
&& Near(tip, new(260, 120)), $"wide panel, diagonal: the bottom edge ({tip})");
// The arrow's corners: point at the tip, base back toward the centre, inside the picture.
RadarSelection.EdgeArrow(c, new(100, -50), min, max, null, 3, out tip, out dir);
RadarSelection.ArrowCorners(tip, dir, 9, 5, out var a, out var b, out var cc);
Check(Near(a, tip), "the arrow points at the tip");
Check(Near((b + cc) * 0.5f, new(100, 12)) && Math.Abs((b - cc).Length() - 10) < 0.01f, $"its base 9 px in, 10 px wide ({b}, {cc})");
bool inside = true;
foreach (var p in new[] { a, b, cc })
if (p.X < min.X || p.Y < min.Y || p.X > max.X || p.Y > max.Y) inside = false;
Check(inside, "the whole arrow is inside the picture");
// Round: on the circle (less the inset), along the line; inside the circle no arrow.
var round = new RoundMask(c, 100);
Check(!RadarSelection.EdgeArrow(c, new(170, 170), min, max, round, 3, out _, out _), "round: inside the circle, no arrow");
Check(RadarSelection.EdgeArrow(c, new(180, 180), min, max, round, 3, out tip, out _)
&& Math.Abs((tip - c).Length() - 97) < 0.01f && Math.Abs(tip.X - tip.Y) < 0.01f,
$"round: in the box's corner but off the circle: on the circle, diagonal ({tip})");
Check(RadarSelection.EdgeArrow(c, new(100, 500), min, max, round, 3, out tip, out dir)
&& Near(tip, new(100, 197)) && Near(dir, new(0, 1)), $"round: straight down ({tip})");
}
// The label goes to the right of the marker, or the left at the right edge, and stays inside the panel.
private static void SelectionLabelPlacement()
{
var min = new System.Numerics.Vector2(0, 0);
var max = new System.Numerics.Vector2(300, 300);
var size = new System.Numerics.Vector2(80, 30);
Check(Near(RadarSelection.LabelPos(new(100, 100), 10, size, min, max), new(110, 85)), "right of the marker, centred");
Check(Near(RadarSelection.LabelPos(new(250, 100), 10, size, min, max), new(160, 85)), "at the right edge: on the left");
Check(Near(RadarSelection.LabelPos(new(100, 5), 10, size, min, max), new(110, 0)), "at the top: kept inside");
Check(Near(RadarSelection.LabelPos(new(100, 295), 10, size, min, max), new(110, 270)), "at the bottom: kept inside");
Check(Near(RadarSelection.LabelPos(new(40, 100), 50, new(200, 30), min, max), new(90, 85)), "a wide label still fits on the right");
Check(Near(RadarSelection.LabelPos(new(150, 150), 10, new(400, 400), min, max), min), "bigger than the panel: its top-left corner");
}
private static float Area(System.Numerics.Vector2[] p, int n)
{
float a = 0;

View file

@ -7,7 +7,8 @@
RadarSettingsStore.cs and UI\Data\RadarSnapshotJson.cs are compiled in, with a synchronous
UiBackgroundWriter stub. Every kind must have its own box, Corpses off must hide your corpses
too, unknown kinds stay hidden, a plugin-shaped snapshot filters per box, and every box must
round-trip through the settings file. Uses RYNTHCORE_RADAR_SETTINGS (temp files); never
round-trip through the settings file. The selected-object highlight (RadarSelection.cs): which
marker is the selected one, when it clears, the edge arrow and label maths, and its settings. Uses RYNTHCORE_RADAR_SETTINGS (temp files); never
touches %LOCALAPPDATA%\RynthCore.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
@ -26,6 +27,7 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\Panels\MarkerStyleSettings.cs" Link="Engine\MarkerStyleSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\CircleClip.cs" Link="Engine\CircleClip.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarWheel.cs" Link="Engine\RadarWheel.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\RadarSelection.cs" Link="Engine\RadarSelection.cs" />
</ItemGroup>
</Project>

View file

@ -28,6 +28,7 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs" Link="Engine\MonsterHudSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs" Link="Engine\HealthProbe.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\DebuffIcon.cs" Link="Engine\DebuffIcon.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\SelfDebuffs.cs" Link="Engine\SelfDebuffs.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\PlateMetrics.cs" Link="Engine\PlateMetrics.cs" />

248
tools/SenseTests/Program.cs Normal file
View file

@ -0,0 +1,248 @@
using RynthCore.Engine.UI.Data;
namespace SenseTests;
/// <summary>
/// The Sense panel's pure part (UI/Data/SenseModel.cs): the compact view's layout, the look
/// commands and their replies, and sense.txt.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main()
{
CompactColumns();
RowsAndSlots();
MouseOnTheBarePanel();
ViewSwitch();
CollapsedLine();
LookCommands();
CommandArguments();
FileRoundTrip();
OlderAndBadFiles();
TermRules();
Matching();
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine("FAIL: " + what);
}
private static bool Near(float a, float b) => Math.Abs(a - b) < 0.01f;
// ── layout ─────────────────────────────────────────────────────────
private static void CompactColumns()
{
// Arrow 16 + distance 52 always; the coordinates (104) when the name keeps 110, then the kind (50).
SenseCompactColumns narrow = SenseLayout.Compact(200);
Check(!narrow.Location && !narrow.Kind && Near(narrow.NameWidth, 132), $"200 px: arrow, name, distance only (name {narrow.NameWidth})");
SenseCompactColumns justLoc = SenseLayout.Compact(281);
Check(!justLoc.Location, "281 px: one short of the coordinates");
SenseCompactColumns loc = SenseLayout.Compact(282);
Check(loc.Location && !loc.Kind && Near(loc.NameWidth, 110), $"282 px: the coordinates come in, the name keeps 110 (got {loc.NameWidth})");
SenseCompactColumns notKind = SenseLayout.Compact(331);
Check(notKind.Location && !notKind.Kind && Near(notKind.NameWidth, 159), "331 px: coordinates, no kind yet");
SenseCompactColumns all = SenseLayout.Compact(332);
Check(all.Location && all.Kind && Near(all.NameWidth, 110), $"332 px: coordinates and kind (name {all.NameWidth})");
SenseCompactColumns big = SenseLayout.Compact(564, scale: 2f);
Check(big.Location && !big.Kind, "the widths grow with the text size: 564 px at 200% is 282 at 100%");
SenseCompactColumns tiny = SenseLayout.Compact(50);
Check(!tiny.Location && !tiny.Kind && Near(tiny.NameWidth, 24), "a very narrow window keeps a sliver of name");
Check(SenseLayout.CompactRowHeight < SenseLayout.FullRowHeight, "compact rows are tighter than the full view's");
}
private static void RowsAndSlots()
{
Check(SenseLayout.CompactFit(160, 16, 5) == (5, false), "five rows in a 160 px window: all of them");
Check(SenseLayout.CompactFit(160, 16, 12) == (9, true), "twelve rows in ten slots: nine and a +N more line");
Check(SenseLayout.CompactFit(10, 16, 3) == (0, true), "a window shorter than a row: just the +N more line");
Check(SenseLayout.CompactFit(100, 16, 0) == (0, false), "no rows: nothing");
Check(SenseLayout.MoreText(3) == "+3 more" && SenseLayout.MoreText(-1) == "+0 more", "the more line's text");
Check(SenseLayout.RowsThatFit(160, 16, 12) == 10 && SenseLayout.RowsThatFit(160, 0, 4) == 4, "rows that fit");
Check(SenseLayout.RowAt(105, 100, 16, 3) == 0, "the first row");
Check(SenseLayout.RowAt(131.9f, 100, 16, 3) == 1, "the second row's last pixel");
Check(SenseLayout.RowAt(148, 100, 16, 3) == -1, "just below the last row: none");
Check(SenseLayout.RowAt(99, 100, 16, 3) == -1 && SenseLayout.RowAt(105, 100, 16, 0) == -1, "above, or no rows: none");
}
private static void MouseOnTheBarePanel()
{
// Drew (0,0)-(200,48); the buttons beside the first line end at x 240, y 16.
Check(SenseLayout.IsHot(100, 20, 0, 0, 200, 48, 240, 16, wasHot: false), "over a row: the panel takes the mouse");
Check(!SenseLayout.IsHot(210, 10, 0, 0, 200, 48, 240, 16, wasHot: false), "right of the rows, coming from the game: clicks go through");
Check(SenseLayout.IsHot(210, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "from a row to the buttons: still the panel's");
Check(SenseLayout.IsHot(210, 40, 0, 0, 200, 48, 240, 16, wasHot: true), "the strip beside the rows, from the last row toward the buttons");
Check(!SenseLayout.IsHot(210, 50, 0, 0, 200, 48, 240, 16, wasHot: true), "below the rows: the game's");
Check(!SenseLayout.IsHot(250, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "past the buttons: the game's");
Check(!SenseLayout.IsHot(-1, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "left of the panel: the game's");
Check(!SenseLayout.IsHot(100, 60, 0, 0, 200, 48, 240, 16, wasHot: false), "the empty rest of the window: the game's");
// The view switch is always drawn (204..240 beside the first line), so it always takes the mouse.
Check(SenseLayout.TakesMouse(210, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "on the view switch, coming from the game: the panel's");
Check(!SenseLayout.TakesMouse(202, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "the gap before the switch, coming from the game: the game's");
Check(!SenseLayout.TakesMouse(210, 20, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "under the switch, coming from the game: the game's");
Check(!SenseLayout.TakesMouse(241, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "past the switch: the game's");
Check(SenseLayout.TakesMouse(100, 20, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "over a row: still the panel's");
Check(SenseLayout.TakesMouse(210, 40, 0, 0, 200, 48, 204, 240, 16, wasHot: true), "the strip toward the switch once hot: still the panel's");
Check(!SenseLayout.TakesMouse(210, -1, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "above the panel: the game's");
}
private static void ViewSwitch()
{
// Every look offers the two others, so the full / compact / collapsed switch is always one click away.
foreach (SenseLayoutMode mode in new[] { SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed })
{
(SenseLayoutMode a, SenseLayoutMode b) = SenseLayout.OtherViews(mode);
Check(a != mode && b != mode && a != b, $"{SenseLayout.LayoutName(mode)}: the switch offers the other two looks");
}
Check(SenseLayout.OtherViews(SenseLayoutMode.Full) == (SenseLayoutMode.Compact, SenseLayoutMode.Collapsed), "full: compact, then collapsed");
Check(SenseLayout.OtherViews(SenseLayoutMode.Compact) == (SenseLayoutMode.Collapsed, SenseLayoutMode.Full), "compact: collapse first (the caret up), then full");
Check(SenseLayout.OtherViews(SenseLayoutMode.Collapsed) == (SenseLayoutMode.Compact, SenseLayoutMode.Full), "collapsed: open to compact first (the caret down), then full");
// Each button's tooltip names the command that does the same, and that command is valid.
foreach (SenseLayoutMode to in new[] { SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed })
{
string tip = SenseLayout.SwitchTip(to);
string cmd = "view " + SenseLayout.LayoutName(to);
Check(tip.Contains("/rc sense " + cmd), $"the {SenseLayout.LayoutName(to)} button's tip names /rc sense {cmd}");
Check(SenseLayout.IsValidArgs(cmd) && SenseLayout.Apply(cmd, SenseLayoutMode.Full, true).Next == to, $"/rc sense {cmd} is the button's look");
}
}
private static void CollapsedLine()
{
Check(SenseLayout.CollapsedText(3) == "Sense: 3", "collapsed: Sense: N");
Check(SenseLayout.CollapsedText(0) == "Sense: 0" && SenseLayout.CollapsedText(-2) == "Sense: 0", "none (never negative)");
}
// ── commands ───────────────────────────────────────────────────────
private static void LookCommands()
{
var (full, compact, collapsed) = (SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed);
SenseLayoutAnswer a = SenseLayout.Apply("compact on", full, panelOpen: true);
Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense: now the compact view", StringComparison.Ordinal) && a.Reply.EndsWith("panel.", StringComparison.Ordinal),
"compact on from full: compact, and says so: " + a.Reply);
a = SenseLayout.Apply("compact on", compact, true);
Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense is already in the compact view", StringComparison.Ordinal), "compact on twice: already: " + a.Reply);
a = SenseLayout.Apply("compact on", collapsed, true);
Check(a.Ok && a.Next == collapsed && a.Reply.StartsWith("Sense is already in the collapsed view", StringComparison.Ordinal), "compact on while collapsed: stays collapsed (it is the small look)");
Check(SenseLayout.Apply("compact off", compact, true).Next == full && SenseLayout.Apply("compact off", collapsed, true).Next == full,
"compact off: the full panel, from compact or collapsed");
a = SenseLayout.Apply("compact off", compact, true);
Check(a.Reply.StartsWith("Sense: now the full view", StringComparison.Ordinal), "compact off says the full view: " + a.Reply);
Check(SenseLayout.Apply("collapse on", full, true).Next == collapsed, "collapse on from full: collapsed");
Check(SenseLayout.Apply("collapse on", compact, true).Next == collapsed, "collapse on from compact: collapsed");
Check(SenseLayout.Apply("collapse off", collapsed, true).Next == compact, "collapse off: the matches (compact)");
a = SenseLayout.Apply("collapse off", full, true);
Check(a.Ok && a.Next == full && a.Reply.StartsWith("Sense is already in the full view", StringComparison.Ordinal), "collapse off on the full panel: stays full");
Check(SenseLayout.Apply("collapsed on", full, true).Next == collapsed, "collapsed is collapse's other spelling");
Check(SenseLayout.Apply("view full", collapsed, true).Next == full, "view full");
Check(SenseLayout.Apply("VIEW Compact", full, true).Next == compact, "any case");
Check(SenseLayout.Apply("view collapsed", compact, true).Next == collapsed, "view collapsed");
foreach (string ask in new[] { "compact", "collapse", "view" })
{
a = SenseLayout.Apply(ask, compact, true);
Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense is in the compact view", StringComparison.Ordinal), $"'{ask}' alone: the look now ({a.Reply})");
}
a = SenseLayout.Apply("compact on", full, panelOpen: false);
Check(a.Reply.EndsWith("The panel is closed: /rc sense opens it.", StringComparison.Ordinal), "a closed panel: the reply says how to open it");
foreach (string bad in new[] { "compact maybe", "view huge", "frob", "collapse yes", "" })
{
a = SenseLayout.Apply(bad, compact, true);
Check(!a.Ok && a.Reply == SenseLayout.Usage, $"'{bad}': the usage");
}
Check(SenseLayout.Usage.StartsWith("Usage: /rc sense", StringComparison.Ordinal), "the usage line");
}
private static void CommandArguments()
{
foreach (string ok in new[] { "", "compact", "compact on", "compact off", "collapse on", "COLLAPSED off", "view", "view full", "view compact", "view collapsed" })
Check(SenseLayout.IsValidArgs(ok), $"'/rc sense {ok}' runs");
foreach (string bad in new[] { "now", "compact maybe", "compact on off", "view huge", "view full now", "frob on" })
Check(!SenseLayout.IsValidArgs(bad), $"'/rc sense {bad}' gets the usage");
Check(SenseLayout.IsLayoutCommand("compact on") && SenseLayout.IsLayoutCommand("view") && !SenseLayout.IsLayoutCommand("frob"), "look commands");
}
// ── sense.txt ──────────────────────────────────────────────────────
private static string[] Lines(string text) => text.Replace("\r\n", "\n").Split('\n');
private static void FileRoundTrip()
{
var terms = new List<SensePattern> { new("Drake", true), new("Mattekar*", false), new("?ire Ant", true) };
foreach (SenseLayoutMode mode in Enum.GetValues<SenseLayoutMode>())
{
string text = SenseFile.Format(terms, alertChat: true, alertBeep: false, mode);
SenseFileData back = SenseFile.Parse(Lines(text));
Check(back.Layout == mode, $"the look {mode} comes back");
Check(back.AlertChat && !back.AlertBeep, "the alerts come back");
Check(back.Terms.Count == 3 && back.Terms[0].Text == "Drake" && back.Terms[0].Enabled
&& back.Terms[1].Text == "Mattekar*" && !back.Terms[1].Enabled && back.Terms[1].IsGlob
&& back.Terms[2].Text == "?ire Ant", "the terms come back, in order, on and off");
}
string compact = SenseFile.Format(terms, false, true, SenseLayoutMode.Compact);
Check(compact.Contains("\nview=compact", StringComparison.Ordinal), "written as view=compact");
Check(SenseFile.Format(terms, false, false, SenseLayoutMode.Full).Contains("view=full", StringComparison.Ordinal), "and view=full");
Check(SenseFile.Format(terms, false, false, SenseLayoutMode.Collapsed).Contains("view=collapsed", StringComparison.Ordinal), "and view=collapsed");
}
private static void OlderAndBadFiles()
{
// A file from before the look: no view line.
SenseFileData old = SenseFile.Parse(new[]
{
"# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.",
"alertChat=0", "alertBeep=1", "term=1|Drake", "term=0|Mattekar",
});
Check(old.Layout == SenseLayoutMode.Full && old.AlertBeep && old.Terms.Count == 2, "an older file: the full panel, as before");
Check(SenseFile.Parse(new[] { "view=huge" }).Layout == SenseLayoutMode.Full, "an unknown look: full");
Check(SenseFile.Parse(new[] { "view= Compact " }).Layout == SenseLayoutMode.Compact, "the look by hand, any case and spaces");
Check(SenseFile.Parse(new[] { "view=compact", "view=collapsed" }).Layout == SenseLayoutMode.Collapsed, "the last view line wins");
Check(SenseFile.Parse(Array.Empty<string>()).Layout == SenseLayoutMode.Full, "no file: full");
SenseFileData junk = SenseFile.Parse(new[] { "", " ", "# view=compact", "nonsense", "=x", "unknown=1", "view" });
Check(junk.Layout == SenseLayoutMode.Full && junk.Terms.Count == 0 && !junk.AlertChat, "comments, blanks and junk are skipped");
}
private static void TermRules()
{
var lines = new List<string> { "term=drake", "term=1|DRAKE", "term=0|", "term=1| Golem ", "term=2|odd" };
SenseFileData d = SenseFile.Parse(lines);
Check(d.Terms.Count == 3, $"a duplicate (any case) and an empty term are dropped ({d.Terms.Count})");
Check(d.Terms[0].Text == "drake" && d.Terms[0].Enabled, "a bare term=name is on");
Check(d.Terms[1].Text == "Golem", "trimmed");
Check(d.Terms[2].Text == "2|odd" && d.Terms[2].Enabled, "only 0| and 1| are flags");
var many = new List<string>();
for (int i = 0; i < 45; i++) many.Add("term=1|name" + i);
Check(SenseFile.Parse(many).Terms.Count == SenseFile.MaxTerms, "at most 40 terms");
string longName = new('x', 100);
Check(SenseFile.Parse(new[] { "term=1|" + longName }).Terms[0].Text.Length == SenseFile.MaxTermLength, "a long term is cut to 64");
Check(SenseFile.Clean(" a\r\nb ") == "a b", "one line");
Check(SenseFile.IndexOf(new List<SensePattern> { new("Drake", true) }, "dRaKe") == 0, "found by any case");
}
private static void Matching()
{
Check(new SensePattern("drake", true).Matches("Dragon's Isle Drake"), "contains, any case");
Check(new SensePattern("Drake*", true).Matches("Drake Hatchling") && !new SensePattern("Drake*", true).Matches("Isle Drake"),
"with * the whole name must match");
Check(new SensePattern("?ire Ant", true).Matches("Fire Ant") && !new SensePattern("?ire Ant", true).Matches("Fire Ants"), "? is one letter");
Check(!new SensePattern("", true).Matches("Anything") && !new SensePattern("x", true).Matches(""), "empty never matches");
}
}

View file

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Sense panel's pure part (2026-10-31): src\RynthCore.Engine\UI\Data\
SenseModel.cs, compiled in. The compact view's layout decisions (which columns fit at a width,
how many rows fit and the "+N more" slot, which row the mouse is on, when the bare panel takes
the mouse and when clicks go to the game), the collapsed line, /rc sense's look commands
(compact on|off, collapse on|off, view ...: the look they lead to and their replies, and the
argument check), sense.txt read and written (terms, alerts and the look, a file from before
the look, bad values), and the term matching. No file I/O, no AC, no ImGui.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>SenseTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\SenseModel.cs" Link="Engine\SenseModel.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,88 @@
using System.Text.Json;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.UI
{
/// <summary>Stub of the engine's background writer: runs the write at once.</summary>
internal static class UiBackgroundWriter
{
public static void Enqueue(string label, Action work) => work();
}
}
namespace TrackerSettingsTests
{
// Offline tests for the Tracker's settings file. See the csproj. TrackerSettings loads once per
// process, so the order matters: an old-style file first, then saves.
internal static class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static int Main()
{
string root = Path.Combine(Path.GetTempPath(), "rynth-tracker-settings-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
string file = Path.Combine(root, "rynthtracker_settings.json");
Environment.SetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS", file);
try
{
// ToJson: what Save writes, both keys, parseable.
using (var doc = JsonDocument.Parse(TrackerSettings.ToJson(51, true)))
{
Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 51, "ToJson writes bgAlpha");
Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "ToJson writes textOnly true");
}
using (var doc = JsonDocument.Parse(TrackerSettings.ToJson(255, false)))
Check(!doc.RootElement.GetProperty("textOnly").GetBoolean(), "ToJson writes textOnly false");
// A file from before Text only (bgAlpha alone): its opacity kept, Text only off.
File.WriteAllText(file, "{\"bgAlpha\":100}");
Check(TrackerSettings.BgAlpha == 100, "an old file's opacity is read");
Check(!TrackerSettings.TextOnly, "an old file (no textOnly) leaves Text only off");
// Text only on: saved with the opacity.
TrackerSettings.SetTextOnly(true);
Check(TrackerSettings.TextOnly, "Text only is on at once");
using (var doc = JsonDocument.Parse(File.ReadAllText(file)))
{
Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "Text only on is saved");
Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 100, "saving Text only keeps the opacity");
}
// The opacity slider's save keeps Text only.
TrackerSettings.SetBgAlpha(40, save: true);
using (var doc = JsonDocument.Parse(File.ReadAllText(file)))
{
Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 40, "the opacity is saved");
Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "saving the opacity keeps Text only");
}
// Off again.
TrackerSettings.SetTextOnly(false);
Check(!TrackerSettings.TextOnly, "Text only is off at once");
using (var doc = JsonDocument.Parse(File.ReadAllText(file)))
Check(!doc.RootElement.GetProperty("textOnly").GetBoolean(), "Text only off is saved");
}
catch (Exception ex)
{
_fails++;
Console.WriteLine($" [FAIL] threw: {ex}");
}
finally
{
Environment.SetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS", null);
try { Directory.Delete(root, recursive: true); } catch { }
}
Console.WriteLine(_fails == 0
? $"PASS ({_asserts} assertions)"
: $"FAIL: {_fails} of {_asserts} assertions failed");
return _fails == 0 ? 0 : 1;
}
}
}

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Tracker panel's settings file (src\RynthCore.Engine\UI\TrackerSettings.cs,
compiled in with a synchronous UiBackgroundWriter stub): the defaults with no file, an old file
without "textOnly", and that background opacity and Text only both survive a save. Uses
RYNTHCORE_TRACKER_SETTINGS (a temp file); never touches %APPDATA%\RynthCore.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>TrackerSettingsTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\TrackerSettings.cs" Link="Engine\TrackerSettings.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,498 @@
using System.Diagnostics;
using RynthCore.Engine.ImGuiBackend;
namespace UiCostTests;
// Offline tests for the UI frame cost breakdown. See the csproj.
internal static class Program
{
private static int _fails, _asserts;
// Logic tests run on a microsecond clock: 1 tick = 1 us, so Ms(1.5) = 1500 ticks.
private const long Us = 1_000_000;
private static long Ms(double ms) => (long)Math.Round(ms * 1000);
private static long Sec(double s) => (long)Math.Round(s * Us);
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static void Eq<T>(T actual, T expected, string msg) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'");
private static int Main()
{
Run("FrameLineFormat", FrameLineFormat);
Run("ThresholdAndRateLimit", ThresholdAndRateLimit);
Run("ThresholdClamp", ThresholdClamp);
Run("RollingWindow", RollingWindow);
Run("HeartbeatTopThree", HeartbeatTopThree);
Run("DescribeNow", DescribeNow);
Run("ExclusiveTiming", ExclusiveTiming);
Run("OverflowSlot", OverflowSlot);
Run("TimingOff", TimingOff);
Run("DiscardFrame", DiscardFrame);
Run("Overhead", Overhead);
Run("DrawPlanRange", DrawPlanRange);
Run("DrawPlanLootEditorShape", DrawPlanLootEditorShape);
Run("SubmitCountersInLine", SubmitCountersInLine);
Run("SubmitCountersInHeartbeatAndDescribe", SubmitCountersInHeartbeatAndDescribe);
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks)");
return _fails == 0 && _asserts > 0 ? 0 : 1;
}
private static void Run(string name, Action body)
{
Console.WriteLine(name);
try { body(); }
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] threw {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); }
}
private static UiCostModel NewModel() => new(Us) { Enabled = true };
private static void FrameLineFormat()
{
var m = NewModel();
int radar = m.Register("Radar");
int hud = m.Register("Monster HUD", unit: "plates");
int chat = m.Register("Chat");
int tiny = m.Register("Tiny");
int nav = m.Register("Nav3D markers", outside: true);
m.Add(chat, Ms(4.0));
m.Add(radar, Ms(100.0));
m.Add(radar, Ms(20.3)); // two calls in one frame add up
m.Add(hud, Ms(41.0), 38);
m.Add(tiny, Ms(0.01));
m.Add(nav, Ms(1.2));
string? line = m.EndFrame(Ms(187.0), Sec(10), logSlow: true);
Check(line != null, "a 187 ms frame over 50 writes a line");
if (line == null) return;
Console.WriteLine(" " + line);
Check(line.StartsWith("[UiCost] frame 187.0 ms (over 50): Radar 120.3, Monster HUD 41.0 (38 plates), untimed 21.7, Chat 4.0", StringComparison.Ordinal),
"parts largest first, with counts and the untimed rest: " + line);
Check(line.Contains(", +1 more 0.0", StringComparison.Ordinal), "a part under 0.05 ms is summed as +1 more");
Check(line.EndsWith(" | 3D pass, not in ui=: Nav3D markers 1.2", StringComparison.Ordinal), "the 3D pass part listed apart, not in untimed");
Check(!line.Contains("Tiny", StringComparison.Ordinal), "the tiny part isn't named");
// The next frame starts clean.
m.Add(chat, Ms(60));
string? next = m.EndFrame(Ms(60), Sec(20), logSlow: true);
Check(next != null && !next.Contains("Radar", StringComparison.Ordinal) && next.Contains("Chat 60.0", StringComparison.Ordinal),
"a frame's parts don't carry into the next: " + next);
// More than LineTopItems parts: the rest are summed.
var many = NewModel();
for (int i = 0; i < 12; i++) many.Add(many.Register("P" + i), Ms(10 + i));
string? l2 = many.EndFrame(Ms(500), Sec(1), logSlow: true);
Check(l2 != null && l2.Contains("P11 21.0, P10 20.0", StringComparison.Ordinal), "largest first among many: " + l2);
// Shown: untimed (314) + P11..P5 = 8 parts; P4..P0 (14+13+12+11+10 = 60) summed.
Check(l2 != null && l2.Contains(", +5 more 60.0", StringComparison.Ordinal), "past the top 8 the rest are summed: " + l2);
}
private static void ThresholdAndRateLimit()
{
var m = NewModel();
int p = m.Register("Panel");
string? Frame(double ms, double atSec, bool log = true)
{
m.Add(p, Ms(ms * 0.9));
return m.EndFrame(Ms(ms), Sec(atSec), log);
}
Check(Frame(60, 0) != null, "the first slow frame is logged");
Check(Frame(70, 1) == null, "another 1 s later is not (rate limit)");
Check(Frame(500, 4.99) == null, "nor 4.99 s later");
Check(Frame(60, 5.0) != null, "5 s after the last line: logged again");
Check(Frame(49.9, 20) == null, "under the threshold: not logged");
Check(Frame(50, 21) != null, "exactly at the threshold: logged");
Check(Frame(60, 40, log: false) == null, "logging off: nothing");
Check(Frame(60, 41) != null, "logging back on, 20 s after the last line: logged");
Eq(m.LinesWritten, 4L, "lines written");
m.ThresholdMs = 100;
Check(Frame(99, 60) == null, "threshold raised to 100: a 99 ms frame isn't slow");
Check(Frame(100, 61) != null, "...a 100 ms frame is");
var t = m.WindowTotals(Sec(61));
Eq(t.Slow, 1L, "slow frames counted in the window at the current threshold");
}
private static void ThresholdClamp()
{
Eq(UiCostModel.ClampThresholdMs(1), UiCostModel.MinThresholdMs, "below the range");
Eq(UiCostModel.ClampThresholdMs(99999), UiCostModel.MaxThresholdMs, "above the range");
Eq(UiCostModel.ClampThresholdMs(75), 75, "in range");
var m = NewModel();
Eq(m.ThresholdMs, UiCostModel.DefaultThresholdMs, "default threshold");
Eq(UiCostModel.DefaultThresholdMs, 50, "the default is 50 ms");
m.ThresholdMs = 0;
Eq(m.ThresholdMs, UiCostModel.MinThresholdMs, "a 0 threshold is clamped");
}
private static void RollingWindow()
{
var m = NewModel();
int radar = m.Register("Radar");
// A frame every 100 ms for 10 s; at t = 2.0 s a 100 ms radar spike.
for (int i = 0; i < 100; i++)
{
double t = i * 0.1;
bool spike = i == 20;
m.Add(radar, Ms(spike ? 100 : 2));
m.EndFrame(Ms(spike ? 150 : 5), Sec(t), logSlow: false);
if (i == 30)
{
var early = m.SlotWindow(Sec(3.05), radar);
Check(Math.Abs(early.MaxMs - 100) < 0.001, $"at 3 s the window still has the spike (max {early.MaxMs})");
}
}
var w = m.WindowTotals(Sec(9.95));
Eq(w.Frames, 50L, "the window holds the last 5 one-second buckets (5.0-9.9 s)");
Check(Math.Abs(w.AvgMs - 5) < 0.001, $"avg ui 5 ms ({w.AvgMs})");
Check(Math.Abs(w.MaxMs - 5) < 0.001, $"the spike at 2 s has left the window ({w.MaxMs})");
var r = m.SlotWindow(Sec(9.95), radar);
Check(Math.Abs(r.AvgMs - 2) < 0.001 && Math.Abs(r.MaxMs - 2) < 0.001, $"radar avg/max 2/2 ({r.AvgMs}/{r.MaxMs})");
// Nothing for 10 s: the window is empty, and the first frame after the gap starts a new one.
Eq(m.WindowTotals(Sec(20)).Frames, 0L, "after a 10 s gap the window is empty");
m.Add(radar, Ms(7));
m.EndFrame(Ms(8), Sec(20), logSlow: false);
var after = m.WindowTotals(Sec(20.1));
Eq(after.Frames, 1L, "one frame after the gap");
Check(Math.Abs(after.MaxMs - 8) < 0.001, "...and only it");
Eq(m.FramesSeen, 101L, "every frame was folded in");
// A gap of 2 buckets: the buckets in between are empty, older ones still count.
var g = NewModel();
int s = g.Register("S");
g.Add(s, Ms(1)); g.EndFrame(Ms(1), Sec(0), false);
g.Add(s, Ms(3)); g.EndFrame(Ms(3), Sec(2.5), false);
var gw = g.WindowTotals(Sec(2.6));
Eq(gw.Frames, 2L, "frames 2.5 s apart are both in the window");
Check(Math.Abs(gw.AvgMs - 2) < 0.001, $"avg of 1 and 3 ({gw.AvgMs})");
}
private static void HeartbeatTopThree()
{
var m = NewModel();
int a = m.Register("Monster HUD (plates, combat text)", unit: "plates");
int b = m.Register("Radar");
int c = m.Register("Chat");
int d = m.Register("Bar");
for (int i = 0; i < 10; i++)
{
m.Add(c, Ms(1));
m.Add(a, Ms(i == 5 ? 41 : 5), 38);
m.Add(d, Ms(0.5));
m.Add(b, Ms(3));
m.EndFrame(Ms(i == 5 ? 46 : 10), Sec(i * 0.1), logSlow: false);
}
string f = m.HeartbeatField(Sec(1.0));
Console.WriteLine(" hb:" + f);
// a: avg (9*5+41)/10 = 8.6, max 41; b 3/3; c 1/1; untimed 0.5/0.5; d 0.5/0.5.
Eq(f, " uitop=Monster_HUD_(plates;_combat_text):8.6/41.0,Radar:3.0/3.0,Chat:1.0/1.0", "top 3 by average, avg/max, no spaces");
Check(f.LastIndexOf(' ') == 0, "only the leading space");
Eq(NewModel().HeartbeatField(Sec(1)), "", "no frames: no field");
}
private static void DescribeNow()
{
var m = NewModel();
int radar = m.Register("Radar");
int hud = m.Register("Monster HUD", unit: "plates");
int nav = m.Register("Nav3D markers", outside: true);
for (int i = 0; i < 20; i++)
{
bool slow = i == 7;
m.Add(radar, Ms(slow ? 120 : 1));
m.Add(hud, Ms(slow ? 41 : 2.1), slow ? 38 : 10);
m.Add(nav, Ms(0.5));
m.EndFrame(Ms(slow ? 187 : 4), Sec(i * 0.05), logSlow: true);
}
List<string> lines = m.Describe(Sec(1.0));
foreach (string l in lines) Console.WriteLine(" " + l);
Check(lines.Count == 4, $"summary, per-frame, slowest frame, 3D pass lines ({lines.Count})");
if (lines.Count < 4) return;
Check(lines[0].StartsWith("UI cost, last ", StringComparison.Ordinal) && lines[0].Contains("20 frames", StringComparison.Ordinal)
&& lines[0].Contains("max 187.0 ms", StringComparison.Ordinal) && lines[0].Contains("1 at 50 ms+", StringComparison.Ordinal), "summary: " + lines[0]);
Check(lines[1].StartsWith("Per frame, avg (max): Radar ", StringComparison.Ordinal), "radar first by average: " + lines[1]);
Check(lines[1].Contains("Monster HUD 4.0 (41.0, 38 plates)", StringComparison.Ordinal), "hud avg, max and the most plates: " + lines[1]);
Eq(lines[2], "Slowest frame 187.0 ms: Radar 120.0, Monster HUD 41.0 (38 plates), untimed 26.0", "the slowest frame part by part");
Check(lines[3].StartsWith("3D pass, not in ui=, avg (max): Nav3D markers 0.5 (0.5)", StringComparison.Ordinal), "3D pass: " + lines[3]);
var empty = NewModel();
List<string> none = empty.Describe(Sec(1));
Check(none.Count == 1 && none[0].StartsWith("UI cost: no UI frames", StringComparison.Ordinal), "no frames: one line saying so");
empty.Enabled = false;
Check(empty.Describe(Sec(1))[0].Contains("timing off", StringComparison.Ordinal), "says when timing is off");
}
private static void ExclusiveTiming()
{
long f = Stopwatch.Frequency;
var m = new UiCostModel(f) { Enabled = true };
int host = m.Register("Panel host upkeep");
int panel = m.Register("Inventory");
long start = Stopwatch.GetTimestamp() - f / 10; // the host part began 100 ms ago
long mark = m.Mark;
m.Add(panel, f * 60 / 1000); // a panel inside it took 60 ms
m.StopExclusive(host, start, mark);
m.EndFrame(f / 10, Stopwatch.GetTimestamp(), logSlow: false);
var h = m.SlotWindow(Stopwatch.GetTimestamp(), host);
var p = m.SlotWindow(Stopwatch.GetTimestamp(), panel);
Check(h.AvgMs >= 39.9 && h.AvgMs < 45, $"the host keeps only its own 40 ms ({h.AvgMs:0.00})");
Check(Math.Abs(p.AvgMs - 60) < 0.01, $"the panel keeps its 60 ms ({p.AvgMs:0.00})");
// Stop with a real Start.
int q = m.Register("Q");
long s = m.Start();
Check(s != 0, "Start gives a timestamp while timing is on");
Thread.Sleep(5);
m.Stop(q, s);
m.EndFrame(f / 100, Stopwatch.GetTimestamp(), logSlow: false);
Check(m.SlotWindow(Stopwatch.GetTimestamp(), q).MaxMs >= 4, "a 5 ms sleep is timed");
}
private static void OverflowSlot()
{
var m = NewModel();
int last = -1;
for (int i = 0; i < UiCostModel.MaxSlots + 40; i++) last = m.Register("N" + i);
Eq(last, UiCostModel.OverflowSlot, "past MaxSlots a name gets the overflow slot");
Eq(m.SlotCount, UiCostModel.MaxSlots, "slot count stops at MaxSlots");
m.Add(last, Ms(70));
string? line = m.EndFrame(Ms(80), Sec(1), true);
Check(line != null && line.Contains("(more names) 70.0", StringComparison.Ordinal), "the overflow slot is named: " + line);
m.Add(9999, Ms(5)); // out of range: ignored
m.Add(-1, Ms(5));
Eq(m.Mark, 0L, "an out-of-range slot adds nothing");
}
private static void TimingOff()
{
var m = new UiCostModel(Stopwatch.Frequency) { Enabled = false };
int p = m.Register("P");
long s = m.Start();
Eq(s, 0L, "Start is 0 while timing is off");
m.Stop(p, s);
m.StopExclusive(p, s, 0);
Eq(m.Mark, 0L, "Stop with 0 adds nothing");
}
private static void DiscardFrame()
{
var m = NewModel();
int nav = m.Register("Nav3D markers", outside: true);
int p = m.Register("P");
m.Add(nav, Ms(30));
m.Add(p, Ms(30));
m.DiscardFrame();
Eq(m.Mark, 0L, "discarded");
string? line = m.EndFrame(Ms(60), Sec(1), true);
Check(line != null && !line.Contains("Nav3D", StringComparison.Ordinal) && line.Contains("untimed 60.0", StringComparison.Ordinal),
"a discarded frame's parts don't reach the next frame: " + line);
}
// The per-frame cost of the breakdown: Parts Start/Stop pairs and an EndFrame (as UiCost does each
// frame), against the same frame with timing off (each Start a flag check, each Stop a 0 check).
private static void Overhead()
{
const int Parts = 40, Frames = 200_000;
var on = new UiCostModel(Stopwatch.Frequency) { Enabled = true };
var off = new UiCostModel(Stopwatch.Frequency) { Enabled = false };
int[] slotsOn = new int[Parts], slotsOff = new int[Parts];
for (int i = 0; i < Parts; i++) { slotsOn[i] = on.Register("Part " + i); slotsOff[i] = off.Register("Part " + i); }
static double Bench(UiCostModel m, int[] slots, bool endFrame, int frames)
{
long t0 = Stopwatch.GetTimestamp();
for (int f = 0; f < frames; f++)
{
for (int i = 0; i < slots.Length; i++)
{
long s = m.Start();
m.Stop(slots[i], s);
}
if (m.Enabled)
{
var st = new SubmitStats { Lists = 20, Draws = 400, TexSwitches = 3, VtxCopied = 30_000, VtxWholeList = 900_000 };
m.SetSubmit(st);
m.AddUploads(0, f % 1000 == 0 ? 1 : 0);
}
if (endFrame) m.EndFrame(Stopwatch.Frequency / 100, Stopwatch.GetTimestamp(), logSlow: false);
}
return (Stopwatch.GetTimestamp() - t0) * 1e9 / Stopwatch.Frequency / frames;
}
Bench(on, slotsOn, true, 20_000); // warm up (JIT)
Bench(off, slotsOff, false, 20_000);
long gc0 = GC.GetAllocatedBytesForCurrentThread();
double onNs = Bench(on, slotsOn, true, Frames);
long allocated = GC.GetAllocatedBytesForCurrentThread() - gc0;
double offNs = Bench(off, slotsOff, false, Frames);
Console.WriteLine($" {Parts} timed parts a frame: on {onNs / 1000.0:0.00} us/frame, off {offNs:0.0} ns/frame, " +
$"{allocated / (double)Frames:0.0} bytes allocated a frame (on); one Start/Stop pair {(onNs / Parts):0} ns.");
Check(onNs < 100_000, $"on: under 0.1 ms a frame ({onNs:0} ns)");
Check(offNs < 2_000, $"off: under 2 us a frame ({offNs:0} ns)");
Check(allocated / (double)Frames < 1.0, $"no allocation per frame ({allocated} bytes over {Frames} frames)");
}
// ── DrawSubmitPlan: which vertices one draw command hands to DrawIndexedPrimitiveUP ──
private static unsafe void DrawPlanRange()
{
ushort[] idx = { 104, 105, 106, 104, 106, 107 }; // one quad, vertices 104..107
fixed (ushort* p = idx)
{
DrawSubmitPlan.IndexRange(p, idx.Length, out int min, out int max);
Eq(min, 104, "smallest index");
Eq(max, 107, "largest index");
Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 500, vtxOffset: 0, out int first, out int num), "a quad inside the list is drawn");
Eq(first, 104, "first vertex = smallest index");
Eq(num, 4, "4 vertices handed over, not the list's 500");
ushort[] rebased = new ushort[idx.Length];
fixed (ushort* r = rebased) DrawSubmitPlan.Rebase(p, r, idx.Length, first);
Eq(string.Join(",", rebased), "0,1,2,0,2,3", "indices rebased to the first vertex");
// VtxOffset (lists past 64k vertices): the indices are relative to it.
Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 70_000, vtxOffset: 65_536, out first, out num) && first == 104 && num == 4,
"with a VtxOffset the range is relative to it");
Check(!DrawSubmitPlan.Plan(p, idx.Length, listVtx: 65_600, vtxOffset: 65_536, out _, out _),
"an index past the list's end (offset + 107 >= 65600) is refused");
Check(!DrawSubmitPlan.Plan(p, idx.Length, listVtx: 107, vtxOffset: 0, out _, out _), "index 107 in a 107-vertex list is refused");
Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 108, vtxOffset: 0, out _, out num) && num == 4, "...in a 108-vertex list it is drawn");
Check(!DrawSubmitPlan.Plan(p, 0, 500, 0, out _, out _), "no indices: nothing to draw");
Check(!DrawSubmitPlan.Plan(p, idx.Length, 500, 500, out _, out _), "a VtxOffset at the list's end is refused");
}
ushort[] zero = { 0, 1, 2 };
fixed (ushort* z = zero)
Check(DrawSubmitPlan.Plan(z, 3, 3, 0, out int f0, out int n0) && f0 == 0 && n0 == 3, "starting at vertex 0: no rebase needed (first 0)");
ushort[] one = { 9, 9, 9 };
fixed (ushort* o = one)
Check(DrawSubmitPlan.Plan(o, 3, 10, 0, out int f1, out int n1) && f1 == 9 && n1 == 1, "a degenerate command: one vertex");
}
// The Loot Editor's rule list as ImGui builds it: per visible row a command in the child's clip
// (row background, 5 icon buttons, the badge: ~450 vertices), then one per PushClipRect (name ~80,
// conditions ~240). Vertices are appended in order, each command's indices reach only its own.
private static unsafe void DrawPlanLootEditorShape()
{
const int Rows = 25;
int[] cmdVtx = { 448, 80, 240 }; // quads: multiples of 4
var idx = new List<ushort>();
var cmds = new List<(int off, int count)>();
int v = 0;
for (int r = 0; r < Rows; r++)
foreach (int cv in cmdVtx)
{
int off = idx.Count;
for (int q = 0; q < cv / 4; q++)
{
int b = v + q * 4;
idx.AddRange(new[] { (ushort)b, (ushort)(b + 1), (ushort)(b + 2), (ushort)b, (ushort)(b + 2), (ushort)(b + 3) });
}
cmds.Add((off, idx.Count - off));
v += cv;
}
int listVtx = v;
long copied = 0, wholeList = 0;
ushort[] arr = idx.ToArray();
fixed (ushort* p = arr)
foreach (var (off, count) in cmds)
{
Check(DrawSubmitPlan.Plan(p + off, count, listVtx, 0, out _, out int num), "every command is drawable");
copied += num;
wholeList += listVtx;
}
const int Stride = 28; // DX9Backend.CustomVertex: xyzrhw, colour, uv
Console.WriteLine($" {Rows} rows, {listVtx} vertices, {cmds.Count} commands: copied {copied} vertices ({copied * Stride / 1024.0:0} KB) " +
$"vs whole-list {wholeList} ({wholeList * Stride / 1048576.0:0.0} MB) a frame, {wholeList / (double)copied:0}x less");
Eq(copied, (long)listVtx, "each vertex is copied once a frame");
Eq(wholeList, (long)listVtx * cmds.Count, "the old policy copied the list once per command");
// The memcpy alone (a lower bound: the D3D9 runtime copies into its own ring buffer, which also
// stalls on the GPU when it wraps), printed, not checked.
byte[] src = new byte[listVtx * Stride], dst = new byte[listVtx * Stride];
long t0 = Stopwatch.GetTimestamp();
for (int c = 0; c < cmds.Count; c++) Buffer.BlockCopy(src, 0, dst, 0, src.Length);
double oldMs = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency;
t0 = Stopwatch.GetTimestamp();
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
double newMs = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency;
Console.WriteLine($" memcpy of that volume in system RAM: whole-list {oldMs:0.00} ms, per-command range {newMs:0.000} ms");
}
private static void SubmitCountersInLine()
{
var m = NewModel();
int sub = m.Register("ImGui submit", unit: "vtx");
int nav = m.Register("Nav3D markers", outside: true);
m.Add(sub, Ms(300), 29344);
m.Add(nav, Ms(1));
m.SetSubmit(new SubmitStats { Lists = 21, Draws = 412, TexSwitches = 3, VtxCopied = 31_100, VtxWholeList = 4_200_000, Skipped = 2 });
m.AddUploads(1, 2);
string? line = m.EndFrame(Ms(301), Sec(1), true);
Console.WriteLine(" " + line);
Check(line != null && line.Contains("ImGui submit 300.0 (29344 vtx), untimed 1.0 | submit: 21 lists, 412 draws, 3 tex switches, " +
"31.1k vtx copied (whole-list 4.2M), 2 skipped; uploads: 1 font, 2 tex | 3D pass, not in ui=: Nav3D markers 1.0",
StringComparison.Ordinal), "submit counters and uploads after the parts, before the 3D pass: " + line);
// The next frame starts clean: no submit recorded, no uploads -> no section.
m.Add(sub, Ms(60), 100);
string? next = m.EndFrame(Ms(60), Sec(10), true);
Check(next != null && !next.Contains("| submit", StringComparison.Ordinal) && !next.Contains("uploads", StringComparison.Ordinal),
"a frame's counters don't carry into the next: " + next);
// Uploads alone.
m.Add(sub, Ms(60));
m.AddUploads(1, 0);
string? up = m.EndFrame(Ms(60), Sec(20), true);
Check(up != null && up.Contains(" | uploads: 1 font, 0 tex", StringComparison.Ordinal), "uploads without a submit: " + up);
// Discarded with the frame.
m.SetSubmit(new SubmitStats { Lists = 1, Draws = 1 });
m.AddUploads(5, 5);
m.DiscardFrame();
m.Add(sub, Ms(60));
string? d = m.EndFrame(Ms(60), Sec(30), true);
Check(d != null && !d.Contains("| submit", StringComparison.Ordinal) && !d.Contains("uploads", StringComparison.Ordinal), "discarded counters are gone: " + d);
Eq(UiCostModel.Compact(950), "950", "compact under 1000");
Eq(UiCostModel.Compact(31_150), "31.2k", "compact thousands");
Eq(UiCostModel.Compact(4_200_000), "4.2M", "compact millions");
Eq(UiCostModel.Compact(31_000), "31k", "compact without a trailing .0");
}
private static void SubmitCountersInHeartbeatAndDescribe()
{
var m = NewModel();
int sub = m.Register("ImGui submit", unit: "vtx");
for (int i = 0; i < 10; i++)
{
m.Add(sub, Ms(i == 4 ? 300 : 20), 20_000);
m.SetSubmit(new SubmitStats { Lists = 18, Draws = i == 4 ? 412 : 120, TexSwitches = i == 4 ? 3 : 1, VtxCopied = i == 4 ? 31_000 : 13_000, VtxWholeList = i == 4 ? 4_200_000 : 400_000 });
if (i == 2) m.AddUploads(1, 0);
if (i == 6) m.AddUploads(0, 3);
m.EndFrame(Ms(i == 4 ? 301 : 21), Sec(i * 0.1), logSlow: false);
}
string f = m.HeartbeatField(Sec(1.0));
Console.WriteLine(" hb:" + f);
Check(f.EndsWith(" uisub=draws:412,texsw:3,vtx:31k/4.2M,up:1/3", StringComparison.Ordinal),
"the window's largest submit and its summed uploads: " + f);
Check(f.StartsWith(" uitop=ImGui_submit:", StringComparison.Ordinal), "uitop first: " + f);
List<string> lines = m.Describe(Sec(1.0));
foreach (string l in lines) Console.WriteLine(" " + l);
Check(lines.Exists(l => l == "ImGui submit, largest per frame: 18 lists, 412 draws, 3 tex switches, 31k vtx copied (whole-list 4.2M); uploads (window total): 1 font, 3 tex"),
"/rc uicost now names the submit's largest counters");
// Without a submit recorded the heartbeat field is as before.
var plain = NewModel();
int p = plain.Register("Radar");
plain.Add(p, Ms(5));
plain.EndFrame(Ms(5), Sec(0), false);
Eq(plain.HeartbeatField(Sec(0.5)), " uitop=Radar:5.0/5.0", "no submit: no uisub");
}
}

View file

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the UI frame cost breakdown (Settings > Diagnostics, /rc uicost):
src\RynthCore.Engine\ImGui\UiCostModel.cs is compiled in as is (no engine dependencies). The rolling
window (buckets roll, old seconds drop out, a long gap empties it), the parts ordered largest first
(the slow-frame line, the heartbeat's uitop= top 3, /rc uicost now), the counts, the untimed rest
and the 3D pass parts listed apart, the threshold and the once-per-5-s rate limit, exclusive timing
(a part around other timed parts keeps only its own time), the overflow slot, timing off, and a
benchmark of the per-frame cost (printed; checked against a generous bound). Also
src\RynthCore.Engine\ImGui\DrawSubmitPlan.cs: each draw command hands the renderer only the vertices
its indices reach (index range, rebasing, broken lists refused), a Loot-Editor-shaped list's copy
volume against the old whole-list-per-command policy, and the submit counters in the slow-frame line,
the heartbeat's uisub= and /rc uicost now. Reads and writes nothing.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>UiCostTests</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\UiCostModel.cs" Link="Engine\UiCostModel.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\DrawSubmitPlan.cs" Link="Engine\DrawSubmitPlan.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,97 @@
using RynthCore.Engine.Compatibility;
namespace VendorRateTests;
/// <summary>VendorTrade's profile rate check (VendorRatePolicy). See the csproj.</summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main()
{
// A free storage vendor: BuyPrice 0, SellPrice 0. This is the case that used to turn trading off.
Check(VendorRatePolicy.LooksSane(0f), "rate 0 (free storage vendor)");
Check(VendorRatePolicy.LooksSane(-0f), "rate -0 (compares equal to 0)");
// Ordinary vendors and promissory-note rates.
foreach (float r in new[] { 0.001f, 0.1f, 0.5f, 0.75f, 1f, 1.15f, 2.5f, 10f, 999.9f })
Check(VendorRatePolicy.LooksSane(r), $"rate {r}");
// Misreads stay rejected.
foreach (float r in new[] { -0.001f, -1f, float.NaN, float.PositiveInfinity, float.NegativeInfinity,
VendorRatePolicy.MaxRate, 1e6f, float.MaxValue, float.MinValue })
Check(!VendorRatePolicy.LooksSane(r), $"rate {r} rejected");
Pricing();
WiringPinned();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
return _failed == 0 ? 0 : 1;
}
private static void Eq(long got, long want, string what) => Check(got == want, $"{what}: got {got}, want {want}");
private const uint Note = VendorRatePolicy.ItemTypePromissoryNote;
private const uint Misc = 0x00000080;
// A 0 rate is free (the vault's GetSellCost/GetBuyCost return 0); any rate above 0 keeps ACE's 1 floor.
private static void Pricing()
{
Check(VendorRatePolicy.IsFreeVendor(0f, 0f), "buy=0 sell=0 is a free vendor");
Check(!VendorRatePolicy.IsFreeVendor(0f, 1.15f), "buy=0 sell=1.15 is not a free vendor");
Check(!VendorRatePolicy.IsFreeVendor(0.5f, 0f), "buy=0.5 sell=0 is not a free vendor");
Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 0), 0, "rate 0, value 0: cost");
Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 1), 0, "rate 0, value 1: cost");
Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 250_000), 0, "rate 0, value 250000: cost");
Eq(VendorRatePolicy.PlayerPaysForStack(0f, Note, 250_000), 0, "rate 0, a note: cost");
Eq(VendorRatePolicy.VendorPaysForStack(0f, Misc, 1), 0, "rate 0, value 1: payout");
Eq(VendorRatePolicy.VendorPaysForStack(0f, Misc, 250_000), 0, "rate 0, value 250000: payout");
Eq(VendorRatePolicy.VendorPaysForStack(0f, Note, 250_000), 0, "rate 0, a note: payout");
// The floor stays for every rate above 0 (stock ACE).
Eq(VendorRatePolicy.PlayerPaysForStack(0.001f, Misc, 1), 1, "rate 0.001, value 1: cost floors at 1");
Eq(VendorRatePolicy.VendorPaysForStack(0.001f, Misc, 1), 1, "rate 0.001, value 1: payout floors at 1");
Eq(VendorRatePolicy.PlayerPaysForStack(0.5f, Misc, 0), 1, "rate 0.5, value 0: cost floors at 1");
Eq(VendorRatePolicy.PlayerPaysForStack(1.15f, Misc, 100), 115, "rate 1.15, value 100: cost");
Eq(VendorRatePolicy.VendorPaysForStack(0.75f, Misc, 100), 75, "rate 0.75, value 100: payout");
Eq(VendorRatePolicy.PlayerPaysForStack(2f, Note, 100), 115, "a note costs 1.15x whatever the rate");
Eq(VendorRatePolicy.VendorPaysForStack(0.5f, Note, 100), 100, "a note pays 1.0x whatever the rate");
}
// VendorTrade.cs must route through VendorRatePolicy, or the checks above test code the engine doesn't run.
private static void WiringPinned()
{
string? src = FindUp(Path.Combine("src", "RynthCore.Engine", "Compatibility", "VendorTrade.cs"));
Check(src != null, "found src\\RynthCore.Engine\\Compatibility\\VendorTrade.cs walking up from " + AppContext.BaseDirectory);
if (src == null) return;
string text = File.ReadAllText(src);
foreach (string needle in new[]
{
"snap.ProfileRead = RateLooksSane(snap.BuyRate) && RateLooksSane(snap.SellRate);",
"RateLooksSane(float rate) => VendorRatePolicy.LooksSane(rate);",
"VendorRatePolicy.PlayerPaysForStack(sellRate, itemType, stackValue);",
"VendorRatePolicy.VendorPaysForStack(buyRate, itemType, value);",
"VendorRatePolicy.IsFreeVendor(snap.BuyRate, snap.SellRate)",
})
Check(text.Contains(needle, StringComparison.Ordinal), "VendorTrade.cs contains: " + needle);
}
private static string? FindUp(string relative)
{
for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent)
{
string p = Path.Combine(d.FullName, relative);
if (File.Exists(p)) return p;
}
return null;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) { Console.WriteLine("ok " + what); return; }
_failed++;
Console.WriteLine("FAIL " + what);
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for VendorTrade's profile rate check (2026-10-30, a free storage vendor on a
custom server, buy=0 sell=0, had trading turned off): src\RynthCore.Engine\Compatibility\VendorRatePolicy.cs,
compiled in. 0 and ordinary rates pass; negative, NaN, infinite and huge rates fail. A 0 rate
prices at 0 (cost and payout), any rate above 0 keeps ACE's 1-per-stack floor. Reads
src\RynthCore.Engine\Compatibility\VendorTrade.cs (found by walking up) to pin that it calls
VendorRatePolicy. No AC. Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>VendorRateTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\VendorRatePolicy.cs" Link="Engine\VendorRatePolicy.cs" />
</ItemGroup>
</Project>