Snapshot for release 2026.10.6.1 (internal 1cbe514)

This commit is contained in:
Tom Bohar 2026-10-06 08:47:11 -04:00
commit abf9146a5b
93 changed files with 10168 additions and 597 deletions

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for RynthChat's rule match modes and standard filters (2026-10-05; idea from
Silentkelpie, rynth PR #1): src/RynthCore.Engine/UI/Data/ChatRuleMatching.cs (how a pattern
is read: Regex, Contains, Starts with, Ends with), ChatFilterPresets.cs (the ready-made Hide
rules) and ChatSettingsDto.cs (rynthchat_settings.json and Export / Import, with the real
source-generated serializer), compiled in. A Regex rule must compile and match exactly as
before, and a settings file without "mode" must load and save unchanged. Nothing native: no
AC, no engine state. Reads the live %APPDATA%\RynthCore\rynthchat_settings.json if there is
one (never writes it).
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>ChatFilterTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRuleMatching.cs" Link="Engine\ChatRuleMatching.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatFilterPresets.cs" Link="Engine\ChatFilterPresets.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatSettingsDto.cs" Link="Engine\ChatSettingsDto.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,320 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using RynthCore.Engine.UI.Data;
namespace ChatFilterTests;
/// <summary>
/// RynthChat rule match modes and standard filters without AC: a Regex rule compiles and matches
/// exactly as before; Contains / Starts with / Ends with match plain text; "mode" loads and saves,
/// and a file without it is a file of Regex rules, written back unchanged; every standard filter
/// catches its example lines and spares player speech.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
// Real lines from the RynthCore logs ([BuffChat] type=... text=...), plus player speech.
private static readonly string[] Lines =
{
"You evaded Tusker Guard!",
"Tusker Guard grazes your foot for 4 points of bludgeoning damage!",
"Critical hit! Olthoi Swarm Nymph nicks your head for 21 points of piercing damage!",
"You say, \"Malar Zhavik\"",
"The spell consumed the following components: Prismatic Taper",
"Your spell fizzled.",
"You cast Focus Self I on yourself, but it is surpassed by Incantation of Focus Other",
"You don't have all the components for this spell.",
"You're too busy!",
"AutoRun ON",
"In portal Space",
"[General] Aja says, \"lol\"",
"Bob tells you, \"you evade like a pro (really)\"",
"Bob says, \"$5 for the Black Opal?\"",
"",
};
private static int Main()
{
RegexModeUnchanged();
LiveSettingsRulesUnchanged();
Contains();
StartsWith();
EndsWith();
EmptyAndBadPatterns();
ModeJson();
SettingsRoundTrip();
WhenParsing();
PresetsCatchAndSpare();
PresetsWellFormed();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL CHAT FILTER TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
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}");
}
/// <summary>What a rule compiled to before match modes (ChatFilterRule.Recompile, 2026-09-29).</summary>
private static Regex? Before(string pattern, out string? error)
{
error = null;
if (pattern.Length == 0) return null;
try { return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(15)); }
catch (ArgumentException ex) { error = ex.Message; return null; }
}
private static Regex? Now(ChatMatchMode mode, string pattern) => ChatRuleMatching.Compile(mode, pattern, 15, out _);
private static void SameAsBefore(string pattern, string why)
{
Regex? before = Before(pattern, out string? errBefore);
Regex? now = ChatRuleMatching.Compile(ChatMatchMode.Regex, pattern, 15, out string? errNow);
Check((before == null) == (now == null), $"{why}: compiles the same ('{pattern}')");
Check(errBefore == errNow, $"{why}: same error ('{pattern}')");
if (before == null || now == null) return;
Check(before.ToString() == now.ToString() && before.Options == now.Options, $"{why}: same regex and options ('{pattern}')");
foreach (string line in Lines)
{
Match a = before.Match(line), b = now.Match(line);
Check(a.Success == b.Success && a.Index == b.Index && a.Length == b.Length, $"{why}: same match on '{line}' ('{pattern}')");
}
}
// ── Regex: as before ─────────────────────────────────────────────────
private static void RegexModeUnchanged()
{
Case("regex rules compile and match exactly as before");
foreach (string p in new[]
{
"You evade", "^You evaded ", @"for \d+ points? of", "^Bob tells you, \"", "Autorun On", "In portal Space",
@"^\[General\]", "(?i)fizzled", "busy!$", ".", "a|b", "[unclosed", "(", @"\", " spaced ",
})
SameAsBefore(p, "regex");
Check(ChatRuleMatching.ToRegex(ChatMatchMode.Regex, "^You evaded ") == "^You evaded ", "a regex pattern is used as typed");
}
/// <summary>Every rule in the live settings file (if any) still compiles to what it did.</summary>
private static void LiveSettingsRulesUnchanged()
{
Case("the rules in this PC's rynthchat_settings.json are unchanged (read only)");
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_settings.json");
if (!File.Exists(path)) { Console.WriteLine(" (no live settings file; skipped)"); return; }
string json = File.ReadAllText(path);
RynthChatSettingsDto? dto = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto);
Check(dto != null, "the live file reads");
int n = 0;
foreach (RynthChatFilterDto f in dto?.Filters ?? Array.Empty<RynthChatFilterDto>())
{
if (f.Mode != null) continue; // a plain-text rule saved by a newer build
Check(ChatRuleMatching.Parse(f.Mode) == ChatMatchMode.Regex, "a rule without mode is Regex");
SameAsBefore(f.Pattern ?? "", "live rule");
n++;
}
Console.WriteLine($" ({n} live rule(s) checked)");
}
// ── Plain text ───────────────────────────────────────────────────────
private static void Contains()
{
Case("Contains: plain text anywhere, any case, nothing special");
Regex rx = Now(ChatMatchMode.Contains, "evaded TUSKER")!;
Check(rx.IsMatch("You evaded Tusker Guard!"), "anywhere, any case");
Check(!rx.IsMatch("You evaded Olthoi Slayer!"), "not other text");
Regex special = Now(ChatMatchMode.Contains, "(really)")!;
Check(special.IsMatch("Bob tells you, \"you evade like a pro (really)\""), "( ) are characters");
Check(!special.IsMatch("really"), "...not a group");
Regex money = Now(ChatMatchMode.Contains, "$5 for the")!;
Check(money.IsMatch("Bob says, \"$5 for the Black Opal?\""), "$ is a character");
Regex dot = Now(ChatMatchMode.Contains, "fizzled.")!;
Check(dot.IsMatch("Your spell fizzled."), "a dot matches a dot");
Check(!dot.IsMatch("Your spell fizzledX"), "...not any character");
Regex quote = Now(ChatMatchMode.Contains, "You say, \"")!;
Check(quote.IsMatch("You say, \"Malar Zhavik\""), "a quote");
Regex star = Now(ChatMatchMode.Contains, "a*b")!;
Check(star.IsMatch("x a*b y") && !star.IsMatch("aaab"), "* is a character");
Regex spaced = Now(ChatMatchMode.Contains, " evaded ")!;
Check(spaced.IsMatch("You evaded Tusker Guard!") && !spaced.IsMatch("evaded"), "spaces in Contains count");
Match m = rx.Match("You evaded Tusker Guard!");
Check(m.Index == 4 && m.Length == "evaded TUSKER".Length, "the match is the text (Colour match colours just it)");
}
private static void StartsWith()
{
Case("Starts with");
Regex rx = Now(ChatMatchMode.StartsWith, "you say, \"")!;
Check(rx.IsMatch("You say, \"Malar Zhavik\""), "the start, any case");
Check(!rx.IsMatch("Bob says, \"You say, \\\"x\\\"\""), "not later in the line");
Regex lead = Now(ChatMatchMode.StartsWith, " [General]")!;
Check(lead.IsMatch("[General] Aja says, \"lol\""), "leading spaces in the pattern don't count");
Check(!lead.IsMatch("Bob says, \"[General]\""), "brackets are characters, at the start only");
}
private static void EndsWith()
{
Case("Ends with");
Regex rx = Now(ChatMatchMode.EndsWith, "evaded your attack. ")!;
Check(rx.IsMatch("Drudge Slinker evaded your attack."), "the end, trailing pattern spaces ignored");
Check(rx.IsMatch("Drudge Slinker evaded your attack. "), "trailing line spaces ignored");
Check(!rx.IsMatch("Drudge Slinker evaded your attack. Again"), "not earlier in the line");
Check(!rx.IsMatch("Drudge Slinker evaded your attackX"), "the dot is a dot");
}
private static void EmptyAndBadPatterns()
{
Case("empty and bad patterns");
foreach (ChatMatchMode mode in Enum.GetValues<ChatMatchMode>())
{
Check(ChatRuleMatching.Compile(mode, "", 15, out string? e) == null && e == null, $"{mode}: empty matches nothing, no error");
Check(ChatRuleMatching.Compile(mode, null, 15, out _) == null, $"{mode}: null matches nothing");
}
foreach (ChatMatchMode mode in new[] { ChatMatchMode.Contains, ChatMatchMode.StartsWith, ChatMatchMode.EndsWith })
{
Check(ChatRuleMatching.Compile(mode, " ", 15, out _) == null, $"{mode}: spaces only match nothing");
Check(ChatRuleMatching.Compile(mode, "[unclosed (", 15, out string? e) != null && e == null, $"{mode}: regex syntax is just text");
}
Check(ChatRuleMatching.Compile(ChatMatchMode.Regex, "[unclosed", 15, out string? err) == null && err != null, "Regex: a bad regex reports its error");
Check(ChatRuleMatching.Compile(ChatMatchMode.Regex, " ", 15, out _) != null, "Regex: spaces are a pattern (as before)");
}
// ── Saving and loading ───────────────────────────────────────────────
private static void ModeJson()
{
Case("mode in JSON");
Check(ChatRuleMatching.ToJson(ChatMatchMode.Regex) == null, "Regex writes no mode");
foreach (ChatMatchMode mode in Enum.GetValues<ChatMatchMode>())
Check(ChatRuleMatching.Parse(ChatRuleMatching.ToJson(mode)) == mode, $"{mode} round-trips");
Check(ChatRuleMatching.Parse(null) == ChatMatchMode.Regex, "absent: Regex");
Check(ChatRuleMatching.Parse("") == ChatMatchMode.Regex, "empty: Regex");
Check(ChatRuleMatching.Parse("CONTAINS") == ChatMatchMode.Contains, "any case");
Check(ChatRuleMatching.Parse("StartsWith") == ChatMatchMode.StartsWith, "StartsWith (enum name)");
Check(ChatRuleMatching.Parse("EndsWith") == ChatMatchMode.EndsWith, "EndsWith (enum name)");
Check(ChatRuleMatching.Parse("fuzzy") == ChatMatchMode.Regex, "unknown: Regex");
Check(ChatRuleMatching.Labels.Length == Enum.GetValues<ChatMatchMode>().Length, "a label per mode");
}
private const string OldFile = """
{"version":2,"fontSize":10,"backgroundAlpha":242,"autoScroll":true,"suppressChat":false,"logEnabled":false,
"ctrlGatedClickThrough":false,"showTimestamps":true,"mentionHighlight":true,"mentionSound":false,
"customTabs":["Junk"],
"filters":[{"pattern":"In portal Space","tab":"Junk","enabled":true,"action":"move"},
{"pattern":"^You evaded ","tab":"","enabled":false,"action":"hide","when":"type:21"},
{"pattern":"fizzled","tab":"","enabled":true,"action":"color","colorMode":"match","color":"#FFD27A"}]}
""";
private static void SettingsRoundTrip()
{
Case("settings: an old file loads as Regex rules and saves unchanged; plain-text rules round-trip");
var opts = RynthChatJsonContext.Default.RynthChatSettingsDto;
RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!;
Check(old.Filters!.Length == 3, "three rules");
Check(old.Filters.All(f => f.Mode == null && ChatRuleMatching.Parse(f.Mode) == ChatMatchMode.Regex), "every old rule is Regex");
string saved = JsonSerializer.Serialize(old, opts);
Check(!saved.Contains("\"mode\"", StringComparison.Ordinal), "saving old rules writes no mode key");
string savedAgain = JsonSerializer.Serialize(JsonSerializer.Deserialize(saved, opts)!, opts);
Check(saved == savedAgain, "load + save is stable");
// A plain-text rule, as ChatModel.ToDto writes it, and back.
old.Filters[0].Mode = ChatRuleMatching.ToJson(ChatMatchMode.Contains);
old.Filters[1].Mode = ChatRuleMatching.ToJson(ChatMatchMode.StartsWith);
string withModes = JsonSerializer.Serialize(old, opts);
Check(withModes.Contains("\"mode\":\"contains\"", StringComparison.Ordinal), "Contains saved as mode=contains");
RynthChatSettingsDto back = JsonSerializer.Deserialize(withModes, opts)!;
Check(ChatRuleMatching.Parse(back.Filters![0].Mode) == ChatMatchMode.Contains, "Contains loads back");
Check(ChatRuleMatching.Parse(back.Filters[1].Mode) == ChatMatchMode.StartsWith, "StartsWith loads back");
Check(ChatRuleMatching.Parse(back.Filters[2].Mode) == ChatMatchMode.Regex, "the untouched rule is still Regex");
Check(back.Filters[1].When == "type:21" && back.Filters[1].Action == "hide" && !back.Filters[1].Enabled, "other fields kept");
// Export / Import uses the rule-set DTO: same field.
var set = new RynthChatRuleSetDto { Format = RynthChatRuleSetDto.FormatName, Rules = back.Filters };
string exported = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto);
RynthChatRuleSetDto imported = JsonSerializer.Deserialize(exported, RynthChatJsonContext.Default.RynthChatRuleSetDto)!;
Check(ChatRuleMatching.Parse(imported.Rules![0].Mode) == ChatMatchMode.Contains, "export / import keeps the mode");
RynthChatFilterDto[]? bare = JsonSerializer.Deserialize("[{\"pattern\":\"x\"}]", RynthChatJsonContext.Default.RynthChatFilterDtoArray);
Check(bare != null && ChatRuleMatching.Parse(bare[0].Mode) == ChatMatchMode.Regex, "a bare old rule array imports as Regex");
}
private static void WhenParsing()
{
Case("When: the same reading as before");
Check(ChatRuleMatching.ParseWhen("") == (null, -1), "empty: any");
Check(ChatRuleMatching.ParseWhen(null) == (null, -1), "null: any");
Check(ChatRuleMatching.ParseWhen(" chan:Combat ") == ("Combat", -1), "a channel");
Check(ChatRuleMatching.ParseWhen("CHAN:Combat") == ("Combat", -1), "chan: any case");
Check(ChatRuleMatching.ParseWhen("type:21") == (null, 21), "a type");
Check(ChatRuleMatching.ParseWhen("type:x") == (null, -1), "a bad type: any");
Check(ChatRuleMatching.ParseWhen("type:-1") == (null, -1), "a negative type: any");
Check(ChatRuleMatching.ParseWhen("chan:") == (null, -1), "chan: with nothing: any");
Check(ChatRuleMatching.WhenMatches("combat", -1, "Combat", 3), "channel any case");
Check(!ChatRuleMatching.WhenMatches("Combat", -1, "Chat", 21), "other channel");
Check(ChatRuleMatching.WhenMatches(null, 21, "Combat", 21) && !ChatRuleMatching.WhenMatches(null, 21, "Combat", 22), "type");
Check(ChatRuleMatching.WhenMatches(null, -1, "Chat", 2), "any");
}
// ── Standard filters ─────────────────────────────────────────────────
private static void PresetsCatchAndSpare()
{
Case("standard filters catch their lines and spare the others");
foreach (ChatFilterPreset p in ChatFilterPresets.All)
{
Check(p.Catches.Length > 0, $"{p.Id}: has example lines");
foreach (var (text, chan, type) in p.Catches)
Check(p.Matches(text, chan, type), $"{p.Id}: catches '{text}' ({chan}, type {type})");
foreach (var (text, chan, type) in p.Spares)
Check(!p.Matches(text, chan, type), $"{p.Id}: spares '{text}' ({chan}, type {type})");
// The same rule built the way ChatFilterRule.Recompile builds it.
Regex? rx = ChatRuleMatching.Compile(p.Mode, p.Pattern, 15, out string? err);
Check(rx != null && err == null, $"{p.Id}: compiles as a rule");
}
// Player speech: no filter that is held to a type or channel may take a say, a tell or an emote's text.
string[] speech = { "Bob says, \"You evaded Tusker Guard!\"", "Bob tells you, \"Your spell fizzled.\"", "You say, \"You're too busy!\"" };
foreach (ChatFilterPreset p in ChatFilterPresets.All)
{
if (p.When.Length == 0) continue; // "" presets are checked by their own Spares
foreach (string s in speech)
{
Check(!p.Matches(s, "Chat", 2), $"{p.Id}: never a Local say ('{s}')");
Check(!p.Matches(s, "Chat", 3), $"{p.Id}: never a tell ('{s}')");
}
}
}
private static void PresetsWellFormed()
{
Case("standard filters are well formed");
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ChatFilterPreset p in ChatFilterPresets.All)
{
Check(ids.Add(p.Id), $"{p.Id}: unique id");
Check(p.Group.Length > 0 && p.Label.Length > 0 && p.Description.Length > 0, $"{p.Id}: named and described");
Check(p.Pattern.Trim().Length > 0, $"{p.Id}: has a pattern");
var (chan, type) = ChatRuleMatching.ParseWhen(p.When);
Check(p.When.Length == 0 || chan != null || type >= 0, $"{p.Id}: When '{p.When}' is one the rules read");
Check(p.SameAs(p.Mode, p.Pattern, p.When), $"{p.Id}: SameAs itself");
Check(!p.SameAs(p.Mode == ChatMatchMode.Regex ? ChatMatchMode.Contains : ChatMatchMode.Regex, p.Pattern, p.When), $"{p.Id}: another mode is another rule");
Check(!p.SameAs(p.Mode, p.Pattern + "x", p.When), $"{p.Id}: another pattern is another rule");
Check(ReferenceEquals(ChatFilterPresets.Get(p.Id), p), $"{p.Id}: found by id");
}
Check(ChatFilterPresets.Get("no.such") == null, "an unknown id is null");
Check(ChatFilterPresets.All.Length >= 10, "a useful set");
}
}

View file

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for saving engine.json (2026-10-05; idea from Silentkelpie, rynth PR #1):
src\RynthCore.Engine\Plugins\EngineSettings.cs and EngineSettingsFile.cs, compiled in, with a
stub RynthLog. A save keeps every key the engine doesn't own (the launcher's) exactly as it
was, writes the engine's own keys as before, swaps the file in atomically (no temp file left),
and leaves an unreadable engine.json alone instead of overwriting it. The real EngineSettings
runs in a child process of this test (its settings path is read once per process), pointed at
a temp file with RYNTHCORE_ENGINE_SETTINGS. 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>EngineSettingsTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettings.cs" Link="Engine\EngineSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,353 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine
{
/// <summary>Stub of the engine's log: the lines go to stdout, where the parent test reads them.</summary>
internal static class RynthLog
{
internal static void Plugin(string msg) => Console.WriteLine("[PLG] " + msg);
internal static void Info(string msg) => Console.WriteLine("[INF] " + msg);
internal static void Warn(string msg) => Console.WriteLine("[WRN] " + msg);
}
}
namespace EngineSettingsTests
{
// Offline tests for saving engine.json. 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}"); }
}
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 string _root = "";
private static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "--child")
return Child(args.Skip(1).ToArray());
_root = Path.Combine(Path.GetTempPath(), "rynth-engine-settings-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
try
{
Run(nameof(MergeKeepsForeignKeys), MergeKeepsForeignKeys);
Run(nameof(MergeEmptyOrMissingFile), MergeEmptyOrMissingFile);
Run(nameof(MergeRefusesUnreadableFile), MergeRefusesUnreadableFile);
Run(nameof(WriteAtomicCreatesAndReplaces), WriteAtomicCreatesAndReplaces);
Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings);
Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys);
Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys);
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)");
return _fails == 0 && _asserts > 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fails;
try { test(); }
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); }
Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}");
}
// ── The real EngineSettings, in a child process ─────────────────────────
/// <summary>Runs in the child: one EngineSettings call against RYNTHCORE_ENGINE_SETTINGS.</summary>
private static int Child(string[] args)
{
try
{
switch (args[0])
{
case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break;
case "add-plugin": EngineSettings.AddPluginPath(args[1]); break;
case "imgui-off": EngineSettings.EnableImGuiBackend = false; break;
case "dump":
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip"));
Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode);
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
break;
default: throw new ArgumentException(args[0]);
}
Console.WriteLine("CHILD-OK");
return 0;
}
catch (Exception ex)
{
Console.WriteLine($"CHILD-THREW {ex.GetType().Name}: {ex.Message}");
return 2;
}
}
private static (int Exit, string Out) RunChild(string settingsPath, params string[] args)
{
var psi = new ProcessStartInfo(Environment.ProcessPath!)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("--child");
foreach (string a in args) psi.ArgumentList.Add(a);
psi.Environment["RYNTHCORE_ENGINE_SETTINGS"] = settingsPath;
using Process p = Process.Start(psi)!;
string output = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
p.WaitForExit();
return (p.ExitCode, output);
}
private static string NewDir(string name)
{
string dir = Path.Combine(_root, name);
Directory.CreateDirectory(dir);
return dir;
}
private static JsonElement ReadJson(string path)
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
return doc.RootElement.Clone();
}
private static string Raw(JsonElement el) => el.GetRawText().Replace(" ", "").Replace("\r", "").Replace("\n", "");
private static void NoTempFilesLeft(string dir) =>
Eq(string.Join(",", Directory.GetFiles(dir).Select(Path.GetFileName).Where(n => n != "engine.json")), "", "only engine.json in the folder (no temp file left)");
// A launcher-written engine.json: the engine's keys plus the launcher's (and an unknown tool's).
private const string LauncherFile = """
{
"PluginPaths": [ "C:\\Games\\RynthSuite\\Plugins\\RynthCore.Plugin.RynthAi.dll" ],
"EnableImGuiShell": false,
"EnableImGuiBackend": true,
"EnableDcompOverlay": true,
"DecalBridge": "On",
"DecalInGameImGui": true,
"LoggingLevel": "Debug",
"LauncherWindow": { "X": 10, "Y": -4, "Docked": [ "Plugins", { "Tab": 2 } ], "Note": null },
"SomeNumber": 1.50,
"Unicode": "Dereth \u00e9 \u2014"
}
""";
private static void SaveKeepsLauncherKeys()
{
string dir = NewDir("keeps");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
JsonElement before = ReadJson(path);
var (exit, output) = RunChild(path, "hook-off", "StartTooltip");
Eq(exit, 0, "child exit code (" + output.Trim() + ")");
JsonElement after = ReadJson(path);
foreach (string key in new[] { "EnableDcompOverlay", "LoggingLevel", "LauncherWindow", "SomeNumber", "Unicode" })
{
Check(after.TryGetProperty(key, out JsonElement v), $"launcher key {key} kept");
if (after.TryGetProperty(key, out v))
Check(JsonElement.DeepEquals(v, before.GetProperty(key)), $"launcher key {key} value unchanged: {Raw(v)}");
}
Eq(after.GetProperty("SomeNumber").GetRawText(), "1.50", "a number keeps its exact text");
Eq(after.GetProperty("Unicode").GetString(), "Dereth \u00e9 \u2014", "non-ASCII text intact");
// The engine's own keys: written from memory as before.
Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "DisabledUiHooks written");
Eq(Raw(after.GetProperty("PluginPaths")), Raw(before.GetProperty("PluginPaths")), "PluginPaths kept");
Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept (read, written back)");
Eq(after.GetProperty("DecalBridge").GetString(), "On", "DecalBridge On kept");
Check(!after.TryGetProperty("DecalInGameImGui", out _), "DecalInGameImGui at its default is left out, as before");
foreach (string key in new[] { "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableHangMinidump", "PreventIdleLogoff" })
Check(after.TryGetProperty(key, out _), $"owned key {key} written as before");
// No key twice.
var names = after.EnumerateObject().Select(p => p.Name).ToList();
Eq(names.Count, names.Distinct(StringComparer.Ordinal).Count(), "no duplicate keys");
NoTempFilesLeft(dir);
// A second save (another owned key) still keeps them.
(exit, output) = RunChild(path, "imgui-off");
Eq(exit, 0, "second child exit code (" + output.Trim() + ")");
after = ReadJson(path);
Eq(after.GetProperty("EnableImGuiBackend").GetBoolean(), false, "EnableImGuiBackend saved");
Check(after.TryGetProperty("EnableDcompOverlay", out _) && after.TryGetProperty("LauncherWindow", out _), "launcher keys survive a second save");
Eq(after.GetProperty("DisabledUiHooks").GetArrayLength(), 1, "first save's DisabledUiHooks kept");
}
private static void SaveRoundTripsOwnedKeys()
{
string dir = NewDir("roundtrip");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", "\"ServerMessageStream\": false, \"LoggingLevel\""));
string plugin = Path.Combine(dir, "RynthCore.Plugin.RynthNav.dll");
Eq(RunChild(path, "add-plugin", plugin).Exit, 0, "add-plugin");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "hook-off");
var (exit, output) = RunChild(path, "dump");
Eq(exit, 0, "dump");
Check(output.Contains("PluginPaths=C:\\Games\\RynthSuite\\Plugins\\RynthCore.Plugin.RynthAi.dll|" + plugin), "plugin paths read back in order: " + output);
Check(output.Contains("StartTooltip=False"), "the hook is off after a reload");
Check(output.Contains("DecalBridge=On"), "DecalBridge read back");
Check(output.Contains("ServerMessageStream=False"), "ServerMessageStream false read back");
Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there");
}
private static void SaveWithoutFileWritesOwnedKeys()
{
string dir = NewDir("nofile");
string path = Path.Combine(dir, "engine.json");
var (exit, output) = RunChild(path, "hook-off", "CheckTooltip");
Eq(exit, 0, "child exit code (" + output.Trim() + ")");
Check(File.Exists(path), "engine.json created");
JsonElement after = ReadJson(path);
Eq(after.GetProperty("DisabledUiHooks")[0].GetString(), "CheckTooltip", "the change saved");
Check(after.EnumerateObject().All(p => EngineSettings.OwnedKeys.Contains(p.Name)), "only engine keys in a new file");
NoTempFilesLeft(dir);
}
private static void SaveLeavesMalformedFileAlone()
{
foreach ((string name, string content) in new[]
{
("truncated", "{ \"PluginPaths\": [ \"C:\\\\Games\\\\a.dll\" ], \"EnableDcompOverlay\": tr"),
("not-json", "this is not json"),
("array-root", "[ 1, 2, 3 ]"),
})
{
string dir = NewDir("bad-" + name);
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, content);
byte[] before = File.ReadAllBytes(path);
var (exit, output) = RunChild(path, "hook-off", "StartTooltip");
Eq(exit, 0, $"{name}: no crash ({output.Trim()})");
Check(output.Contains("[WRN] EngineSettings: not saving"), $"{name}: says why it didn't save");
Check(File.ReadAllBytes(path).SequenceEqual(before), $"{name}: the file is left exactly as it was");
NoTempFilesLeft(dir);
}
// An empty file (an old non-atomic save cut short) holds nothing to lose: it is rewritten.
string emptyDir = NewDir("bad-empty");
string emptyPath = Path.Combine(emptyDir, "engine.json");
File.WriteAllText(emptyPath, "");
Eq(RunChild(emptyPath, "hook-off", "StartTooltip").Exit, 0, "empty: no crash");
Eq(ReadJson(emptyPath).GetProperty("DisabledUiHooks")[0].GetString(), "StartTooltip", "empty: rewritten with the change");
}
// ── EngineSettingsFile, direct ──────────────────────────────────────────
private static byte[] Owned(string json) => Encoding.UTF8.GetBytes(json);
private static readonly HashSet<string> Keys = new(StringComparer.Ordinal) { "A", "B", "Optional" };
private static void MergeKeepsForeignKeys()
{
string existing = """{ "A": 1, "Foreign": { "x": [1, {"y": null}] }, "Optional": true, "B": "old", "Other": "kept", "Foreign": 99 }""";
byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 2, "B": "new" }"""), Keys, out string? err);
Check(merged != null && err == null, "merged");
JsonElement r = JsonDocument.Parse(merged!).RootElement;
Eq(string.Join(",", r.EnumerateObject().Select(p => p.Name)), "A,B,Foreign,Other", "ours first in our order, then the others in file order, each once");
Eq(r.GetProperty("A").GetInt32(), 2, "owned A updated");
Eq(r.GetProperty("B").GetString(), "new", "owned B updated");
Eq(Raw(r.GetProperty("Foreign")), """{"x":[1,{"y":null}]}""", "nested foreign object kept whole (first of a duplicate key)");
Check(!r.TryGetProperty("Optional", out _), "an owned key not written this time is left out");
// A key we write but forgot to list as owned is still written once (ours wins).
byte[]? m2 = EngineSettingsFile.Merge("""{ "New": "file" }""", Owned("""{ "New": "ours" }"""), Keys, out _);
JsonElement r2 = JsonDocument.Parse(m2!).RootElement;
Eq(r2.EnumerateObject().Count(), 1, "unlisted key written once");
Eq(r2.GetProperty("New").GetString(), "ours", "ours wins");
// Keys are case-sensitive, like the engine's reads: "a" is not "A".
byte[]? m3 = EngineSettingsFile.Merge("""{ "a": 5 }""", Owned("""{ "A": 1 }"""), Keys, out _);
Eq(JsonDocument.Parse(m3!).RootElement.GetProperty("a").GetInt32(), 5, "a differently-cased key is someone else's");
}
private static void MergeEmptyOrMissingFile()
{
foreach (string? existing in new[] { null, "", " \r\n " })
{
byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 1 }"""), Keys, out string? err);
Check(merged != null && err == null, $"'{existing}': merged");
Eq(Raw(JsonDocument.Parse(merged!).RootElement), """{"A":1}""", $"'{existing}': only ours");
}
}
private static void MergeRefusesUnreadableFile()
{
foreach (string bad in new[] { "{ \"A\": ", "nope", "[1]", "\"text\"", "null", "{ \"A\": 1 } trailing" })
{
byte[]? merged = EngineSettingsFile.Merge(bad, Owned("""{ "A": 1 }"""), Keys, out string? err);
Check(merged == null && !string.IsNullOrEmpty(err), $"'{bad}': refused with a reason");
}
}
private static void WriteAtomicCreatesAndReplaces()
{
string dir = NewDir("atomic");
string path = Path.Combine(dir, "engine.json");
EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":1}"));
Eq(File.ReadAllText(path), "{\"v\":1}", "created");
EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":2}"));
Eq(File.ReadAllText(path), "{\"v\":2}", "replaced");
NoTempFilesLeft(dir);
// A file another process holds open without delete sharing: the swap fails after its
// retries, the old content stays whole, and the temp file is cleaned up.
using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
bool threw = false;
try { EngineSettingsFile.WriteAtomic(path, Encoding.UTF8.GetBytes("{\"v\":3}")); }
catch (IOException) { threw = true; }
catch (UnauthorizedAccessException) { threw = true; }
Check(threw, "a locked file makes the save fail (the caller logs it)");
}
Eq(File.ReadAllText(path), "{\"v\":2}", "locked: old content intact");
NoTempFilesLeft(dir);
}
// Every key EngineSettings.cs reads or writes must be in OwnedKeys (and the other way round):
// a new setting left off the list would be kept from the old file instead of saved.
private static void OwnedKeysMatchEngineSettings()
{
string source = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "Plugins", "EngineSettings.cs")));
var used = new HashSet<string>(StringComparer.Ordinal);
foreach (Match m in Regex.Matches(source, @"TryGetProperty\(""(\w+)"""))
used.Add(m.Groups[1].Value);
foreach (Match m in Regex.Matches(source, @"\bw\.Write\w*\(""(\w+)"""))
used.Add(m.Groups[1].Value);
Check(used.Count >= 16, $"found the keys in EngineSettings.cs ({used.Count})");
foreach (string key in used)
Check(EngineSettings.OwnedKeys.Contains(key), $"EngineSettings.OwnedKeys lists \"{key}\"");
foreach (string key in EngineSettings.OwnedKeys)
Check(used.Contains(key), $"OwnedKeys \"{key}\" is read or written by EngineSettings.cs");
}
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;
}
throw new FileNotFoundException(relative);
}
}
}

View file

@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for the flight recorder (src\RynthCore.Engine\Net\Flight*.cs, compiled in; pure
code, no engine state):
- the ring (order, wrap, truncation, concurrent writers against a reader);
- what is kept from client and server datagrams (filters, the player's id learned from
game events, objects the character used, position rate limit, retransmit dedupe,
resend-request markers);
- engine-call tagging ([eng] / [cli]) and folding of repeated calls;
- the stall detectors (use refusal, unanswered uses, "too busy") and the dump rate limit;
- decoding every recorded message type from hand-built bytes (WireBuilder.cs from
NetMessageTests), truncated and garbage input, and the dump file format;
- cost: no allocation and time per datagram on the hot path.
Extra arguments are .rnc captures from "/rc netmsg capture" (server datagrams): replayed through
the recorder and dumped to the console.
Nothing native: no AC, no engine.
Run: dotnet run -c Release [(double dash) capture.rnc ...] (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>FlightRecorderTests</RootNamespace>
<ServerGarbageCollection>false</ServerGarbageCollection>
<TieredPGO>true</TieredPGO>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Net\AcPacketWire.cs" Link="Engine\AcPacketWire.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightRing.cs" Link="Engine\FlightRing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightCapture.cs" Link="Engine\FlightCapture.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightFormat.cs" Link="Engine\FlightFormat.cs" />
<Compile Include="..\NetMessageTests\WireBuilder.cs" Link="WireBuilder.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,853 @@
using System.Buffers.Binary;
using System.Diagnostics;
using NetMessageTests;
using RynthCore.Engine.Net;
namespace FlightRecorderTests;
internal static unsafe class Program
{
private static int _checks, _failed;
private static string _case = "";
// Fake clock: one tick = one millisecond.
private static long _t = 1_000_000;
private static long Clock() => _t;
private const uint Player = 0x50000ABC;
private const uint Corpse = 0x80068ACE;
private const uint Other = 0x80012345;
private static int Main(string[] args)
{
RingBasics();
RingWrapAndTruncation();
RingConcurrent();
PlayerLearnedAndFilters();
UsedObjectsKept();
PositionRateLimit();
RetransmitDedupe();
ResendRequestMarker();
EngineTagging();
EngineRepeatFolding();
DetectUseRefusal();
DetectUseRefusalDelayedAnswers();
NoTriggerWhenCorpsesOpen();
NoTriggerForDrinksAndKits();
DetectUnanswered();
DetectTooBusy();
DumpPolicy();
DecodeOutbound();
DecodeMoveToState();
DecodeInboundEvents();
DecodeMotion();
DecodePositionAndObjects();
DecodeMarkers();
DecodeTruncatedAndGarbage();
DumpFormat();
foreach (string path in args)
{
if (path == "--sample") SampleDump();
else Replay(path);
}
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL FLIGHT RECORDER TESTS PASSED." : $"{_failed} FAILED.");
Performance();
return _failed == 0 ? 0 : 1;
}
// ── helpers ─────────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine($"- {name}");
}
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 void Has(string text, string part, string what) =>
Check(text.Contains(part, StringComparison.Ordinal), $"{what}: expected \"{part}\" in \"{text}\"");
private static void Lacks(string text, string part, string what) =>
Check(!text.Contains(part, StringComparison.Ordinal), $"{what}: did not expect \"{part}\" in \"{text}\"");
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
private static FlightCapture NewCapture(int capacity = 1024) => new(capacity, Clock, 1000);
private static uint _fragSeq = 1000;
/// <summary>One datagram carrying <paramref name="message"/> in one fragment.</summary>
private static byte[] One(byte[] message, uint extraFlags = 0, uint? seq = null)
=> Datagram.Build(extraFlags, 0, null, new Frag(seq ?? _fragSeq++, 1, 0, message));
private static void Feed(FlightCapture c, bool outbound, byte[] datagram)
{
fixed (byte* p = datagram)
c.OnDatagram(outbound, p, datagram.Length);
}
private static void In(FlightCapture c, byte[] message, uint extraFlags = 0, uint? seq = null) => Feed(c, false, One(message, extraFlags, seq));
private static void Out(FlightCapture c, byte[] message, uint extraFlags = 0, uint? seq = null) => Feed(c, true, One(message, extraFlags, seq));
private static uint _actionSeq = 1;
private static byte[] Action(uint type, Body body) => new Body().U32(0xF7B1).U32(_actionSeq++).U32(type).Bytes(body.ToArray()).ToArray();
private static byte[] Event(uint type, Body body) => body.GameEvent(type, Player, 42);
private static FlightRecord[] Recs(FlightCapture c) => c.Ring.Snapshot();
private static string[] Lines(FlightCapture c) => Recs(c).Select(r => FlightFormat.Arrow(r.Entry.Dir) + " " + FlightFormat.Describe(r)).ToArray();
private static string Last(FlightCapture c) { var r = Recs(c); return r.Length == 0 ? "" : FlightFormat.Arrow(r[^1].Entry.Dir) + " " + FlightFormat.Describe(r[^1]); }
private static int Count(FlightCapture c, FlightDir dir) => Recs(c).Count(r => r.Entry.Dir == dir);
private static void LoginAs(FlightCapture c) => In(c, Event(0x01C7, new Body().U32(0))); // any game event names the player
// Message builders (server side as the server writes them, client side as the client does).
private static byte[] UseDone(uint err) => Event(0x01C7, new Body().U32(err));
private static byte[] ViewContents(uint container, params uint[] items)
{
var b = new Body().U32(container).U32((uint)items.Length);
foreach (uint i in items) b.U32(i).U32(0);
return Event(0x0196, b);
}
private static byte[] WeenieError(uint code) => Event(0x028A, new Body().U32(code));
private static byte[] Use(uint obj) => Action(0x0036, new Body().U32(obj));
private static byte[] UseWithTarget(uint src, uint dst) => Action(0x0035, new Body().U32(src).U32(dst));
/// <summary>UpdateMotion for <paramref name="obj"/>: header, then a state with the given commands.</summary>
private static byte[] MotionState(uint obj, ushort style, ushort forward = 0, (ushort Cmd, float Speed)[]? cmds = null, bool autonomous = false)
{
cmds ??= Array.Empty<(ushort, float)>();
uint flags = 0x1 | (forward != 0 ? 0x2u : 0);
var b = new Body().U32(0xF74C).U32(obj).U16(3).U16(7).U16(9).Bytes(autonomous ? (byte)1 : (byte)0, 0) // aligned to 16
.Bytes(0, 0).U16(style) // movement type 0 (state), flags, style
.U32(flags | ((uint)cmds.Length << 7)).U16(style);
if (forward != 0) b.U16(forward);
foreach (var (cmd, speed) in cmds) b.U16(cmd).U16(0x8005).F32(speed);
while (b.Length % 4 != 0) b.Bytes(0);
return b.ToArray();
}
private static byte[] MotionMoveToObject(uint obj, uint target)
=> new Body().U32(0xF74C).U32(obj).U16(3).U16(8).U16(10).Bytes(0, 0)
.Bytes(6, 0).U16(0x3C)
.U32(target).U32(0xA9B40017).F32(10).F32(20).F32(0)
.U32(0x1EE0F).F32(0.6f).F32(0).F32(15).F32(1).F32(15).F32(0).F32(1.5f).ToArray();
private static byte[] MotionTurnToObject(uint obj, uint target)
=> new Body().U32(0xF74C).U32(obj).U16(3).U16(9).U16(11).Bytes(0, 0)
.Bytes(8, 0).U16(0x3D)
.U32(target).F32(90).U32(0x2).F32(1).F32(90).ToArray();
private static byte[] UpdatePosition(uint obj, uint cell, ushort posSeq, ushort tele = 1, ushort force = 1)
=> new Body().U32(0xF748).U32(obj).U32(0x04 | 0x10 | 0x20).U32(cell).F32(1).F32(2).F32(3).F32(1).F32(0)
.U16(5).U16(posSeq).U16(tele).U16(force).ToArray();
private static byte[] AutoPos(uint cell, ushort inst = 5, ushort srv = 6, ushort tele = 1, ushort force = 1)
=> Action(0xF753, new Body().U32(cell).F32(84.5f).F32(12.25f).F32(0).F32(1).F32(0).F32(0).F32(0)
.U16(inst).U16(srv).U16(tele).U16(force).Bytes(1, 0, 0, 0));
// ── ring ────────────────────────────────────────────────────────────────
private static void RingBasics()
{
Case("ring: order, kinds, names");
var ring = new FlightRing(16);
byte[] m = { 1, 2, 3, 4, 5 };
fixed (byte* p = m) ring.WriteMessage(10, FlightDir.In, FlightFlags.None, p, m.Length, m.Length, 7, 0);
ring.WriteMark(11, FlightMark.EngineCall, "UseObject", 0x80000001, 0, 0, default);
ring.WriteMark(12, FlightMark.Note, null, 0, 0, 0, "hello");
var recs = ring.Snapshot();
Eq(recs.Length, 3, "three entries");
Eq(recs[0].Entry.Dir, FlightDir.In, "first is the message");
Eq(recs[0].Entry.Len, (ushort)5, "message length kept");
Eq(recs[0].Entry.A, 7u, "fragment sequence kept");
Eq(recs[1].Name, "UseObject", "marker name");
Eq(recs[2].Entry.Stamp, 12L, "stamp");
Has(FlightFormat.Describe(recs[2]), "note: hello", "note text");
Eq(ring.Total, 3, "total");
}
private static void RingWrapAndTruncation()
{
Case("ring: wrap keeps the newest Capacity, long messages are cut");
var ring = new FlightRing(16);
for (uint i = 1; i <= 40; i++) ring.WriteMark(i, FlightMark.Note, null, i, 0, 0, "x");
var recs = ring.Snapshot();
Eq(recs.Length, 16, "capacity entries");
Eq(recs[0].Entry.A, 25u, "oldest kept is #25");
Eq(recs[^1].Entry.A, 40u, "newest is #40");
Check(recs.Zip(recs.Skip(1)).All(p => p.First.Entry.Serial < p.Second.Entry.Serial), "oldest first");
byte[] big = new byte[300];
for (int i = 0; i < big.Length; i++) big[i] = (byte)i;
fixed (byte* p = big) ring.WriteMessage(99, FlightDir.Out, FlightFlags.None, p, big.Length, big.Length, 1, 0);
var last = ring.Snapshot()[^1].Entry;
Eq((int)last.Len, FlightEntry.DataCap, "kept DataCap bytes");
Eq(last.FullLen, (ushort)300, "full length remembered");
Check((last.Flags & FlightFlags.Truncated) != 0, "flagged truncated");
string longText = new string('a', 500);
ring.WriteMark(100, FlightMark.Note, null, 0, 0, 0, longText);
Has(FlightFormat.Describe(ring.Snapshot()[^1]), "...", "long note cut with ...");
}
private static void RingConcurrent()
{
Case("ring: 4 writers and a reader, every copied entry is whole");
var ring = new FlightRing(256);
int stop = 0;
long torn = 0, seen = 0;
var writers = Enumerable.Range(0, 4).Select(w => new Thread(() =>
{
byte[] buf = new byte[64];
uint n = 0;
while (Volatile.Read(ref stop) == 0)
{
n++;
uint v = (uint)(w << 24) | n;
for (int i = 0; i < buf.Length; i += 4) BinaryPrimitives.WriteUInt32LittleEndian(buf.AsSpan(i), v);
fixed (byte* p = buf) ring.WriteMessage(v, FlightDir.In, FlightFlags.None, p, buf.Length, buf.Length, v, v);
}
})).ToList();
writers.ForEach(t => t.Start());
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 400)
{
foreach (var r in ring.Snapshot())
{
seen++;
FlightEntry e = r.Entry;
uint v = e.A;
bool ok = e.B == v && e.Stamp == v;
for (int i = 0; i < e.Len && ok; i += 4)
ok = BinaryPrimitives.ReadUInt32LittleEndian(new ReadOnlySpan<byte>(e.Data + i, 4)) == v;
if (!ok) torn++;
}
}
Volatile.Write(ref stop, 1);
writers.ForEach(t => t.Join());
Check(seen > 1000, $"read many entries ({seen})");
Eq(torn, 0L, "torn entries");
}
// ── what is kept ────────────────────────────────────────────────────────
private static void PlayerLearnedAndFilters()
{
Case("capture: the player id comes from game events; other objects' motion is not kept");
var c = NewCapture();
In(c, MotionState(Player, 0x3D)); // before the id is known: dropped
Eq(Count(c, FlightDir.In), 0, "nothing kept before the player is known");
LoginAs(c);
Eq(c.PlayerId, Player, "player id learned");
In(c, MotionState(Player, 0x3D));
In(c, MotionState(Other, 0x3C)); // a monster
In(c, Event(0x0013, new Body().U32(0))); // PlayerDescription: not wanted
In(c, new Body().Str("hi").Str("Bob").U32(Other).U32(2).Message(0x02BB)); // local chat: never kept
In(c, WeenieError(0x001D));
string[] lines = Lines(c);
Eq(lines.Length, 3, "UseDone (login), player motion, WeenieError");
Check(lines.Any(l => l.Contains("UpdateMotion 0x50000ABC")), "player motion kept");
Check(!lines.Any(l => l.Contains("0x80012345")), "monster motion not kept");
Check(!lines.Any(l => l.Contains("Bob")), "chat not kept");
}
private static void UsedObjectsKept()
{
Case("capture: messages about an object the character just used are kept, for 20 s");
var c = NewCapture();
LoginAs(c);
Out(c, Use(Corpse));
In(c, new Body().U32(Corpse).U16(1).Message(0xF747)); // delete
In(c, new Body().U32(Other).U16(1).Message(0xF747)); // someone else's
In(c, MotionState(Corpse, 0x3D)); // a door opening, say
string all = string.Join("\n", Lines(c));
Has(all, $"ObjectDelete 0x{Corpse:X8}", "used object's delete kept");
Lacks(all, $"ObjectDelete 0x{Other:X8}", "other delete not kept");
Has(all, $"UpdateMotion 0x{Corpse:X8}", "used object's motion kept");
_t += 21_000;
int before = Recs(c).Length;
In(c, new Body().U32(Corpse).U16(2).Message(0xF747));
Eq(Recs(c).Length, before, "forgotten after 20 s");
}
private static void PositionRateLimit()
{
Case("capture: AutonomousPosition / the player's UpdatePosition are rate-limited, changes always kept");
var c = NewCapture();
LoginAs(c);
int start = Recs(c).Length;
for (int i = 0; i < 10; i++) { Out(c, AutoPos(0xA9B40017)); _t += 100; }
Eq(Recs(c).Length - start, 1, "one kept in a second");
_t += 2000;
Out(c, AutoPos(0xA9B40017));
var last = Recs(c)[^1];
Eq(last.Entry.B, 9u, "the next kept one counts the 9 skipped");
Has(FlightFormat.Describe(last), "(+9 like it not kept)", "described");
Out(c, AutoPos(0xA9B40018));
Has(Last(c), "@0xA9B40018", "cell change kept at once");
Out(c, AutoPos(0xA9B40018, force: 2));
Has(Last(c), "f2", "force-position change kept at once");
int n = Recs(c).Length;
for (ushort i = 0; i < 5; i++) In(c, UpdatePosition(Player, 0xA9B40018, (ushort)(10 + i)));
Eq(Recs(c).Length - n, 1, "server positions for the player: one kept");
In(c, UpdatePosition(Player, 0xA9B40018, 20, tele: 2));
Has(Last(c), "t2", "teleport sequence change kept");
In(c, UpdatePosition(Other, 0xA9B40018, 21));
Lacks(Last(c), "0x80012345", "other objects' positions not kept");
}
private static void RetransmitDedupe()
{
Case("capture: a retransmitted copy of a message already seen is not kept twice");
var c = NewCapture();
LoginAs(c);
byte[] msg = UseDone(0);
In(c, msg, seq: 777);
In(c, msg, Datagram.Retransmission, seq: 777);
In(c, msg, Datagram.Retransmission, seq: 778); // first copy lost: kept, flagged
var recs = Recs(c);
Eq(recs.Count(r => r.Entry.Dir == FlightDir.In), 3, "login + one + the unseen retransmit");
Has(FlightFormat.Describe(recs[^1]), "[retransmitted]", "flagged");
}
private static void ResendRequestMarker()
{
Case("capture: a resend request in a packet header becomes a marker (rate-limited)");
var c = NewCapture();
byte[] nak = new Body().U32(1).U32(0x1000).U32(0).U16(1).U16(0).U16(12).U16(0).U32(2).U32(555).U32(556).ToArray();
Feed(c, false, nak);
Feed(c, false, nak);
var marks = Recs(c).Where(r => r.Entry.Dir == FlightDir.Mark).ToArray();
Eq(marks.Length, 1, "one marker within 500 ms");
Has(FlightFormat.Describe(marks[0]), "server asks for 2 lost packet(s) again (first seq 555)", "described");
_t += 600;
Feed(c, true, nak);
Has(Last(c), "client asks", "client side named");
var s = new FlightSummary();
c.TakeCounters(ref s);
Eq(s.InResendRequests, (ushort)2, "both server requests counted");
Eq(s.OutResendRequests, (ushort)1, "client request counted");
Eq(s.InPackets, (ushort)2, "packets counted");
}
private static void EngineTagging()
{
Case("capture: an action right after the engine's call is [eng], otherwise [cli]");
var c = NewCapture();
LoginAs(c);
c.EngineCall("UseObject", Corpse, 0);
_t += 20;
Out(c, Use(Corpse));
Has(Last(c), "[eng] Use 0x80068ACE", "engine use");
Out(c, Use(Corpse));
Has(Last(c), "[cli] Use", "a second use without a call is the client's");
c.EngineCall("UseObject", Corpse, 0);
_t += 2000;
Out(c, Use(Corpse));
Has(Last(c), "[cli]", "too late to match");
c.EngineCall("CastSpell", Other, 1234);
Out(c, Action(0x004A, new Body().U32(Other).U32(1234)));
Has(Last(c), "[eng] CastTargetedSpell spell 1234 on 0x80012345", "cast matched by spell");
c.EngineCall("ChangeCombatMode", 1, 0);
Out(c, Action(0x0053, new Body().U32(8)));
Has(Last(c), "[cli] ChangeCombatMode Magic", "different mode does not match");
c.EngineCall("SetAutoRun", 1, 0);
Out(c, Action(0xF61C, new Body().U32(0)));
Has(Last(c), "[eng] MoveToState", "movement matched by time");
c.EngineCall("GiveObjectTo", Corpse, Other);
Out(c, Action(0x00CD, new Body().U32(Other).U32(Corpse).U32(1)));
Has(Last(c), "[eng] GiveObjectRequest 0x80068ACE x1 to 0x80012345", "give matched on the object");
string engineLines = string.Join("\n", Lines(c).Where(l => l.StartsWith("**")));
Has(engineLines, "engine UseObject(0x80068ACE, 0)", "engine call markers written");
}
private static void EngineRepeatFolding()
{
Case("capture: identical engine calls within 1 s fold into one line plus a 'repeated' line");
var c = NewCapture();
for (int i = 0; i < 30; i++) { c.EngineCall("SetMotion", 0x45000005, 0); _t += 33; }
Eq(Recs(c).Length, 1, "one line while repeating");
c.EngineCall("StopCompletely", 0, 0);
string[] lines = Lines(c);
Eq(lines.Length, 3, "first, repeated, next");
Has(lines[1], "repeated 29 more time(s)", "count of folded calls");
Check(Recs(c)[1].Entry.Stamp < Recs(c)[2].Entry.Stamp, "repeat line at the last repeat's time");
c.EngineCall("StopCompletely", 0, 0);
c.FlushEngineRepeats();
Has(Last(c), "StopCompletely(0, 0) repeated 1 more time(s)", "flush before a dump");
}
// ── detectors ───────────────────────────────────────────────────────────
private static void DetectUseRefusal()
{
Case("detector: 4 uses answered UseDone(0) with nothing opened -> use-refusal trigger");
var c = NewCapture();
LoginAs(c);
uint[] corpses = { 0x80000001, 0x80000002, 0x80000003, 0x80000004 };
foreach (uint id in corpses)
{
Out(c, Use(id));
_t += 60;
In(c, UseDone(0));
_t += 1600;
c.Tick();
}
string? t = c.TakeTrigger();
Check(t != null && t.StartsWith("use-refusal: 4 uses"), $"trigger ({t})");
Check(t != null && t.Contains("0x80000004"), "names the objects");
Eq(c.TakeTrigger(), null, "taken once");
}
private static void DetectUseRefusalDelayedAnswers()
{
Case("detector: the stall shape (each answer arrives after the next use) still triggers");
var c = NewCapture();
LoginAs(c);
for (int i = 0; i < 6; i++)
{
Out(c, Use(Corpse));
_t += 65;
if (i > 0) In(c, UseDone(0)); // answers the previous use
_t += 1500;
c.Tick();
}
_t += 2000;
c.Tick();
Check(c.TakeTrigger()?.StartsWith("use-refusal") == true, "trigger");
}
private static void NoTriggerWhenCorpsesOpen()
{
Case("detector: opens that work never trigger; one open resets the streak");
var c = NewCapture();
LoginAs(c);
for (int i = 0; i < 10; i++)
{
uint id = 0x80001000u + (uint)i;
Out(c, Use(id));
_t += 200;
In(c, MotionTurnToObject(Player, id));
In(c, UseDone(0));
In(c, ViewContents(id, 0x81000001));
_t += 2000;
c.Tick();
}
Eq(c.TakeTrigger(), null, "no trigger");
for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 60; In(c, UseDone(0)); _t += 1600; c.Tick(); }
In(c, ViewContents(Other));
for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 60; In(c, UseDone(0)); _t += 1600; c.Tick(); }
Eq(c.TakeTrigger(), null, "3 + open + 3 does not trigger");
Eq(c.RefusedStreak, 3, "streak restarted after the open");
}
private static void NoTriggerForDrinksAndKits()
{
Case("detector: potions (player animation), kits (use-with-target) and errors don't count");
var c = NewCapture();
LoginAs(c);
for (int i = 0; i < 6; i++)
{
Out(c, Use(Other));
_t += 50;
In(c, MotionState(Player, 0x3D, cmds: new[] { ((ushort)0x1B, 1f) })); // Drink
In(c, UseDone(0));
_t += 2000;
c.Tick();
}
for (int i = 0; i < 6; i++)
{
Out(c, UseWithTarget(0x80000777, Player));
_t += 2400;
In(c, UseDone(0));
_t += 2000;
c.Tick();
}
for (int i = 0; i < 6; i++)
{
Out(c, Use(Corpse));
_t += 50;
In(c, UseDone(0x0037)); // ObjectGone: an answer with an error
_t += 2000;
c.Tick();
}
Eq(c.TakeTrigger(), null, "no trigger");
}
private static void DetectUnanswered()
{
Case("detector: 3 uses with no UseDone at all -> use-unanswered trigger");
var c = NewCapture();
LoginAs(c);
for (int i = 0; i < 3; i++) { Out(c, Use(Corpse)); _t += 5100; c.Tick(); }
Check(c.TakeTrigger()?.StartsWith("use-unanswered") == true, "trigger");
}
private static void DetectTooBusy()
{
Case("detector: 3 'too busy' within 20 s -> too-busy trigger (WeenieError or system text)");
var c = NewCapture();
LoginAs(c);
In(c, WeenieError(0x001D)); _t += 15_000;
In(c, WeenieError(0x001D)); _t += 15_000;
In(c, WeenieError(0x001D));
Eq(c.TakeTrigger(), null, "spread over 30 s: none");
_t += 1000;
In(c, new Body().Str("You're too busy!").U32(0x1A).Message(0xF7E0));
Check(c.TakeTrigger()?.StartsWith("too-busy") == true, "three within 20 s");
In(c, new Body().Str("You cast Heal Self on yourself").U32(0x1A).Message(0xF7E0));
Eq(c.TakeTrigger(), null, "other system text is not 'too busy'");
}
private static void DumpPolicy()
{
Case("dump policy: one automatic dump per 10 minutes");
var p = new FlightDumpPolicy(600_000);
Check(p.TryAccept(1000, out _), "first");
Check(!p.TryAccept(2000, out long wait), "second within the cooldown");
Eq(wait, 599_000L, "wait reported");
Check(!p.TryAccept(600_999, out _), "just before");
Check(p.TryAccept(601_000, out _), "after the cooldown");
Eq(p.Refused, 2, "refusals counted");
}
// ── decoding ────────────────────────────────────────────────────────────
private static string DescribeOut(byte[] message, FlightFlags flags = FlightFlags.None)
{
var ring = new FlightRing(16);
fixed (byte* p = message) ring.WriteMessage(0, FlightDir.Out, flags, p, message.Length, message.Length, 1, 0);
return FlightFormat.Describe(ring.Snapshot()[0]);
}
private static string DescribeIn(byte[] message)
{
var ring = new FlightRing(16);
fixed (byte* p = message) ring.WriteMessage(0, FlightDir.In, FlightFlags.None, p, message.Length, message.Length, 1, 0);
return FlightFormat.Describe(ring.Snapshot()[0]);
}
private static void DecodeOutbound()
{
Case("decode: client actions");
_actionSeq = 400;
Has(DescribeOut(Use(Corpse)), "Use 0x80068ACE #400", "use");
Has(DescribeOut(UseWithTarget(0x80000777, Player)), "UseWithTarget 0x80000777 on 0x50000ABC", "use with target");
Has(DescribeOut(Action(0x0048, new Body().U32(157))), "CastUntargetedSpell spell 157", "untargeted cast");
Has(DescribeOut(Action(0x004A, new Body().U32(Other).U32(2000))), "CastTargetedSpell spell 2000 on 0x80012345", "targeted cast");
Has(DescribeOut(Action(0x0053, new Body().U32(2))), "ChangeCombatMode Melee", "combat mode");
Has(DescribeOut(Action(0x0008, new Body().U32(Other).U32(2).F32(0.5f))), "MeleeAttack 0x80012345 height 2 power 0.5", "melee");
Has(DescribeOut(Action(0x0019, new Body().U32(Other).U32(Player).I32(0))), "PutItemInContainer 0x80012345 into 0x50000ABC slot 0", "put item");
Has(DescribeOut(Action(0x001B, new Body().U32(Other))), "DropItem 0x80012345", "drop");
Has(DescribeOut(Action(0x0195, new Body().U32(Corpse))), "NoLongerViewingContents 0x80068ACE", "no longer viewing");
Has(DescribeOut(Action(0x01B7, new Body())), "CancelAttack", "cancel attack");
Has(DescribeOut(Action(0xF61B, new Body().F32(0.8f).F32(0).F32(1).F32(5).U16(1).U16(2).U16(3).U16(4))), "Jump extent 0.8 velocity (0,1,5) seq i1/s2/t3/f4", "jump");
Has(DescribeOut(AutoPos(0xA9B40017)), "AutonomousPosition @0xA9B40017 (84.5,12.25,0) yaw 0 seq i5/s6/t1/f1 contact=1", "autonomous position");
string talk = DescribeOut(Action(0x0015, new Body().Str("my secret words")));
Has(talk, "Talk (", "talk named");
Lacks(talk, "secret", "talk text not written");
Has(DescribeOut(Action(0x9999, new Body().U32(1).U32(2))), "action 0x9999 args 0x1 0x2", "unknown action raw");
Has(DescribeOut(new Body().U32(0x1234).Message(0xF7C8)), "CharacterEnterWorldRequest", "non-action message");
Has(DescribeOut(Use(Corpse), FlightFlags.Engine), "[eng] Use", "engine tag");
}
private static void DecodeMoveToState()
{
Case("decode: MoveToState raw motion state, commands, position, sequences");
// hold key, style, forward command + hold + speed, turn command + speed, one command.
uint flags = 0x001 | 0x002 | 0x004 | 0x008 | 0x010 | 0x100 | 0x400;
var b = new Body().U32(flags | (1u << 11))
.U32(2).U32(0x80000049).U32(0x44000007).U32(2).F32(1.25f).U32(0x6500000D).F32(1.5f)
.U16(0x31).U16(0x8007).F32(1)
.U32(0xA9B40017).F32(84.5f).F32(12.25f).F32(0).F32(0.7071f).F32(0).F32(0).F32(0.7071f)
.U16(11).U16(12).U16(13).U16(14).Bytes(1, 0, 0, 0);
string s = DescribeOut(Action(0xF61C, b));
Has(s, "MoveToState hold=Run style=Magic fwd=RunForward(Run)@1.25 turn=TurnRight@1.5", "fields");
Has(s, "cmds=[MagicHeal@1#7a]", "command with autonomous sequence");
Has(s, "@0xA9B40017 (84.5,12.25,0) yaw 90", "position");
Has(s, "seq i11/s12/t13/f14 contact=1", "sequences");
Lacks(s, "...", "not cut");
Has(DescribeOut(Action(0xF61C, new Body().U32(0).U32(0xA9B40017).F32(1).F32(2).F32(3).F32(1).F32(0).F32(0).F32(0).U16(1).U16(1).U16(1).U16(1).Bytes(1, 0, 0, 0))),
"(no motion: stand still)", "empty state");
}
private static void DecodeInboundEvents()
{
Case("decode: server game events");
Has(DescribeIn(UseDone(0)), "UseDone err 0x0000 none #42", "use done");
Has(DescribeIn(UseDone(0x0037)), "UseDone err 0x0037 ObjectGone", "use done error");
Has(DescribeIn(ViewContents(Corpse, 1, 2, 3)), "ViewContents 0x80068ACE items 3: 0x00000001 0x00000002 0x00000003", "view contents");
Has(DescribeIn(Event(0x0052, new Body().U32(Corpse))), "CloseGroundContainer 0x80068ACE", "close ground container");
Has(DescribeIn(WeenieError(0x001D)), "WeenieError 0x001D YoureTooBusy", "too busy");
Has(DescribeIn(WeenieError(0x0402)), "YourSpellFizzled", "fizzle");
Has(DescribeIn(Event(0x028B, new Body().U32(0x0036).Str("Interrupted!"))), "WeenieErrorWithString 0x0036 ActionCancelled \"Interrupted!\"", "error with string");
Has(DescribeIn(Event(0x00A0, new Body().U32(Other).U32(0x0020))), "InventoryServerSaveFailed 0x80012345 err 0x0020", "save failed");
Has(DescribeIn(Event(0x0022, new Body().U32(Other).U32(Player).I32(3).U32(0))), "InventoryPutObjInContainer 0x80012345 in 0x50000ABC slot 3", "put in container");
Has(DescribeIn(Event(0x01A7, new Body().U32(0))), "AttackDone err 0x0000", "attack done");
Has(DescribeIn(Event(0x01B8, new Body())), "CombatCommenceAttack", "commence attack");
Has(DescribeIn(Event(0x01B1, new Body().Str("Drudge Ravener").U32(1).Bytes(BitConverter.GetBytes(0.4)).U32(37).U32(1).U32(0).U32(0))),
"AttackerNotification hit 'Drudge Ravener' for 37 (crit), 40% left", "attacker notification");
var ench = new Body().U16(2053).U16(1).U16(5).U16(0).U32(400).Bytes(BitConverter.GetBytes(0.0)).Bytes(BitConverter.GetBytes(1800.0)).U32(Player);
Has(DescribeIn(Event(0x02C2, ench)), "MagicUpdateEnchantment spell 2053 layer 1 duration 1800 s caster 0x50000ABC", "enchantment");
Has(DescribeIn(Event(0x02C3, new Body().U16(2053).U16(1))), "MagicRemoveEnchantment spell 2053 layer 1", "remove enchantment");
Has(DescribeIn(Event(0x02EB, new Body().Str("You can't do that"))), "TransientString \"You can't do that\"", "transient string");
Has(DescribeIn(new Body().Str("You're too busy!").U32(0x1A).Message(0xF7E0)), "ServerMessage \"You're too busy!\" (chat type 26)", "system text");
}
private static void DecodeMotion()
{
Case("decode: UpdateMotion state, move-to-object, turn-to-object");
string s = DescribeIn(MotionState(Player, 0x49, forward: 0x03, cmds: new[] { ((ushort)0x31, 1f) }));
Has(s, "UpdateMotion 0x50000ABC server State style=Magic fwd=Ready cmds=[MagicHeal@1#5a] seq i3/m7/c9", "state");
Lacks(s, "...", "whole");
Has(DescribeIn(MotionState(Player, 0x3D, autonomous: true)), "autonomous State style=NonCombat", "autonomous flag");
string mt = DescribeIn(MotionMoveToObject(Player, Corpse));
Has(mt, "MoveToObject style=HandCombat target 0x80068ACE origin @0xA9B40017 (10,20,0) params 0x1EE0F dist 0.6", "move to object");
Has(mt, "runrate 1.5 seq i3/m8/c10", "run rate and sequences");
Has(DescribeIn(MotionTurnToObject(Player, Corpse)), "TurnToObject style=NonCombat target 0x80068ACE heading 90 params 0x2 speed 1", "turn to object");
}
private static void DecodePositionAndObjects()
{
Case("decode: positions, teleport, object messages");
Has(DescribeIn(UpdatePosition(Player, 0xA9B40017, 33, 4, 5)), "UpdatePosition 0x50000ABC @0xA9B40017 (1,2,3) yaw 0 grounded seq i5/p33/t4/f5", "update position");
Has(DescribeIn(new Body().U16(7).U16(0).Message(0xF751)), "PlayerTeleport seq t7", "teleport");
Has(DescribeIn(new Body().U32(Corpse).U16(2).U16(0).Message(0xF747)), "ObjectDelete 0x80068ACE i2", "delete");
Has(DescribeIn(new Body().U32(Player).F32(0).F32(0).F32(5).F32(0).F32(0).F32(0).U16(1).U16(2).Message(0xF74E)), "VectorUpdate 0x50000ABC velocity (0,0,5)", "vector");
Has(DescribeIn(new Body().U32(Player).U32(0x57).F32(1).Message(0xF755)), "PlayEffect 0x50000ABC script 0x57", "effect");
Has(DescribeIn(new Body().Bytes(1).U32(Other).U32(9).U32(90).Message(0x0197)), "SetStackSize 0x80012345 size 9", "stack size");
}
private static void DecodeMarkers()
{
Case("decode: markers and the per-second summary");
var c = NewCapture();
c.Mark(FlightMark.BusyIncrement, 1, 1);
c.Mark(FlightMark.BusyForceClear, 2, 0, text: "with the motion flush");
c.Mark(FlightMark.BusyWatchdog, 1, 0, 4100, "real m_cBusy stuck");
c.Mark(FlightMark.GateCleared, 3, Corpse, text: "manual (/rc unlockactions)");
c.Mark(FlightMark.GateCleared, 0, 0, text: "watchdog");
c.Mark(FlightMark.EngineInit, 3);
c.Mark(FlightMark.Trigger, text: "plugin: loot wedge");
var s = new FlightSummary { RealBusy = 1, ShadowBusy = 0, PendingType = 3, PendingObject = Corpse, Attacking = 0, Gesture = 1, InPackets = 12, InMessages = 30, InKept = 4, OutPackets = 8, OutMessages = 9, OutKept = 2, SendErrors = 1 };
c.WriteSummary(s);
string all = string.Join("\n", Lines(c));
Has(all, "** m_cBusy +1 -> real 1 (engine count 1)", "increment");
Has(all, "m_cBusy force-cleared (was real 2, engine count 0) - with the motion flush", "force clear");
Has(all, "busy watchdog (real m_cBusy stuck): real 1, engine count 0, stuck 4100 ms", "watchdog");
Has(all, "action gate cleared: pending item request type 3 on 0x80068ACE (manual (/rc unlockactions))", "request gate");
Has(all, "action gate cleared: attacking flag (watchdog)", "attack gate");
Has(all, "engine generation 3 started (hot reload", "hot reload");
Has(all, "AUTO DUMP TRIGGER: plugin: loot wedge", "trigger");
Has(all, "-- 1s: in 12 pk/30 msg (4 kept), out 8 pk/9 msg (2 kept)", "summary counters");
Has(all, "SEND ERRORS 1", "send errors");
Has(all, "m_cBusy 1 (engine 0) | item request type 3 on 0x80068ACE | attacking 0 | gesture 1", "summary state");
var u = new FlightSummary { RealBusy = FlightSummary.Unknown, PendingType = 0xFFFFFFFF, Attacking = 255, Gesture = 255 };
c.WriteSummary(u);
Has(Last(c), "m_cBusy ? (engine 0) | item request ? | attacking ? | gesture ?", "unknowns");
}
private static void DecodeTruncatedAndGarbage()
{
Case("decode: cut-off messages end with '...', garbage never throws");
// A MoveToState with 12 commands is longer than DataCap.
var b = new Body().U32(0x002 | (12u << 11)).U32(0x80000049);
for (int i = 0; i < 12; i++) b.U16(0x31).U16((ushort)i).F32(1);
b.U32(0xA9B40017).F32(1).F32(2).F32(3).F32(1).F32(0).F32(0).F32(0).U16(1).U16(1).U16(1).U16(1).Bytes(1, 0, 0, 0);
string s = DescribeOut(Action(0xF61C, b));
Has(s, "...", "cut off");
Lacks(s, "undecodable", "no exception");
var rnd = new Random(7);
int bad = 0;
for (int i = 0; i < 20000; i++)
{
int len = rnd.Next(0, 130);
byte[] m = new byte[len];
rnd.NextBytes(m);
if (len >= 4 && rnd.Next(2) == 0)
{
uint[] ops = { 0xF7B0, 0xF7B1, 0xF74C, 0xF748, 0xF7E0, 0xF751, 0xF755, 0x0197 };
BinaryPrimitives.WriteUInt32LittleEndian(m, ops[rnd.Next(ops.Length)]);
}
string d1 = rnd.Next(2) == 0 ? DescribeIn(m) : DescribeOut(m);
if (d1.Contains("undecodable")) bad++;
}
Eq(bad, 0, "random messages decoded without an exception");
var c = NewCapture();
int crashes = 0;
for (int i = 0; i < 20000; i++)
{
byte[] d = new byte[rnd.Next(0, 200)];
rnd.NextBytes(d);
if (d.Length >= 20 && rnd.Next(2) == 0)
{
BinaryPrimitives.WriteUInt32LittleEndian(d.AsSpan(4), 0x4);
BinaryPrimitives.WriteUInt16LittleEndian(d.AsSpan(16), (ushort)(d.Length - 20));
}
try { Feed(c, rnd.Next(2) == 0, d); } catch { crashes++; }
}
Eq(crashes, 0, "random datagrams never throw");
}
private static void DumpFormat()
{
Case("dump: header, legend, one line per entry, time relative to the request");
var c = NewCapture();
LoginAs(c);
c.EngineCall("UseObject", Corpse, 0);
_t += 5;
Out(c, Use(Corpse));
_t += 60;
In(c, UseDone(0));
long zero = _t;
_t += 250;
c.Mark(FlightMark.Note, text: "after");
var sw = new StringWriter();
var recs = c.Ring.Snapshot();
FlightFormat.WriteDump(sw, recs, zero, new DateTime(2026, 10, 6, 12, 0, 0), 1000, new[] { "Reason: test" });
string[] lines = sw.ToString().Split(Environment.NewLine);
Eq(lines[0], "RynthCore flight recorder dump", "title");
Eq(lines[1], "Reason: test", "header line");
Has(lines[2], $"Entries: {recs.Length}", "entry count");
Check(lines.Any(l => l.StartsWith("How to read")), "legend");
string[] body = lines.Where(l => l.Contains(" ms ")).ToArray();
Eq(body.Length, recs.Length, "one line per entry");
Has(body.First(l => l.Contains("[eng] Use")), " -60 ms 11:59:59.940 -> [eng] Use 0x80068ACE", "outbound line");
Has(body.First(l => l.Contains("UseDone") && l.Contains("12:00:00.000")), " 0 ms 12:00:00.000 <- UseDone err 0x0000 none", "inbound line at time 0");
Has(body.First(l => l.Contains("note")), " +250 ms 12:00:00.250 ** note: after", "marker after the request");
}
// ── sample ──────────────────────────────────────────────────────────────
/// <summary>"--sample": a made-up corpse-use stall, dumped to the console (what a dump looks like).</summary>
private static void SampleDump()
{
Console.WriteLine();
Console.WriteLine("Sample dump (synthetic stall):");
var c = NewCapture(4096);
LoginAs(c);
var s = new FlightSummary { RealBusy = 0, PendingType = 0, Attacking = 0, Gesture = 0, InPackets = 14, InMessages = 22, InKept = 3, OutPackets = 9, OutMessages = 7, OutKept = 2 };
c.WriteSummary(s);
// A normal open: use, server turns the character, UseDone, contents.
c.EngineCall("UseObject", 0x80068ACD, 0); _t += 3;
Out(c, Use(0x80068ACD)); c.Mark(FlightMark.BusyIncrement, 1, 1); _t += 120;
In(c, MotionTurnToObject(Player, 0x80068ACD)); _t += 180;
In(c, UseDone(0)); In(c, ViewContents(0x80068ACD, 0x81000001, 0x81000002)); _t += 400;
Out(c, Action(0x0195, new Body().U32(0x80068ACD))); _t += 900;
// The onset: use in melee stance, a peace-mode swap 3 ms later.
c.EngineCall("UseObject", Corpse, 0); _t += 2;
Out(c, Use(Corpse)); _t += 3;
c.EngineCall("ChangeCombatMode", 1, 0); _t += 1;
Out(c, Action(0x0053, new Body().U32(1))); _t += 40;
In(c, MotionState(Player, 0x3D)); _t += 1500;
for (int i = 0; i < 4; i++)
{
c.EngineCall("UseObject", Corpse, 0); _t += 2;
Out(c, Use(Corpse)); _t += 65;
In(c, UseDone(0)); _t += 1600;
c.Tick();
c.WriteSummary(s);
}
string? why = c.TakeTrigger();
if (why != null) c.Mark(FlightMark.Trigger, text: "engine: " + why);
long zero = _t;
_t += 3000;
var recs = c.Ring.Snapshot();
var w = new StringWriter();
FlightFormat.WriteDump(w, recs, zero, new DateTime(2026, 10, 6, 6, 18, 50), 1000, new[] { "Reason: auto: " + (why ?? "?") });
Console.WriteLine(w.ToString());
}
// ── captures ────────────────────────────────────────────────────────────
private static void Replay(string path)
{
Case($"replay {Path.GetFileName(path)} (server datagrams through the recorder)");
byte[] all = File.ReadAllBytes(path);
if (all.Length < 4 || all[0] != 'R' || all[1] != 'N' || all[2] != 'C' || all[3] != '1')
{
Check(false, "not an RNC1 capture");
return;
}
var c = new FlightCapture(16384, Clock, 1000);
int pos = 4, datagrams = 0;
long firstStamp = -1;
while (pos + 6 <= all.Length)
{
uint stamp = BinaryPrimitives.ReadUInt32LittleEndian(all.AsSpan(pos));
int len = BinaryPrimitives.ReadUInt16LittleEndian(all.AsSpan(pos + 4));
pos += 6;
if (pos + len > all.Length) break;
if (firstStamp < 0) firstStamp = stamp;
_t = 1_000_000 + (stamp - firstStamp);
fixed (byte* p = &all[pos]) c.OnDatagram(false, p, len);
pos += len;
datagrams++;
}
var recs = c.Ring.Snapshot();
Console.WriteLine($" {datagrams} datagrams, {recs.Length} entries kept, player 0x{c.PlayerId:X8}");
int undecodable = 0;
foreach (var r in recs.TakeLast(60))
Console.WriteLine(" " + FlightFormat.Line(r, recs[^1].Entry.Stamp, DateTime.Now, 1000));
foreach (var r in recs) if (FlightFormat.Describe(r).Contains("undecodable")) undecodable++;
Eq(undecodable, 0, "every kept entry decodes");
}
// ── cost ────────────────────────────────────────────────────────────────
private static void Performance()
{
Console.WriteLine();
Console.WriteLine("Cost (hot path, real Stopwatch clock):");
var c = new FlightCapture(16384, Stopwatch.GetTimestamp, Stopwatch.Frequency);
LoginAs(c);
byte[] autoPos = One(AutoPos(0xA9B40017));
byte[] monsterPos = One(UpdatePosition(Other, 0xA9B40017, 1));
byte[] playerMotion = One(MotionState(Player, 0x3D));
byte[] create = One(new byte[400]);
BinaryPrimitives.WriteUInt32LittleEndian(create.AsSpan(36), 0xF745); // CreateObject: not kept
void Run(string what, byte[] d, bool outbound, int n)
{
fixed (byte* p = d)
{
for (int i = 0; i < 2000; i++) c.OnDatagram(outbound, p, d.Length); // warm up
long before = GC.GetAllocatedBytesForCurrentThread();
long t0 = Stopwatch.GetTimestamp();
for (int i = 0; i < n; i++) c.OnDatagram(outbound, p, d.Length);
long ticks = Stopwatch.GetTimestamp() - t0;
long alloc = GC.GetAllocatedBytesForCurrentThread() - before;
double ns = ticks * 1e9 / Stopwatch.Frequency / n;
Console.WriteLine($" {what,-44} {ns,7:0} ns/datagram, {alloc} bytes allocated over {n}");
_case = "cost";
Eq(alloc, 0L, $"{what}: no allocation");
}
}
Run("AutonomousPosition (rate-limited away)", autoPos, true, 200_000);
Run("monster UpdatePosition (filtered out)", monsterPos, false, 200_000);
Run("CreateObject-size message (not kept)", create, false, 200_000);
Run("player UpdateMotion (kept: 120-byte copy)", playerMotion, false, 200_000);
Console.WriteLine($" ring memory: {c.Ring.Bytes / 1024} KB for {c.Ring.Capacity} entries ({sizeof(FlightEntry)} bytes each)");
Console.WriteLine(_failed == 0 ? "COST CHECKS PASSED." : $"{_failed} FAILED (incl. cost).");
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the install-folder resolver (src\Shared\RynthInstallPaths.cs, compiled in):
environment beats HKCU beats HKLM beats the default; empty, relative or broken values are skipped;
with nothing set the answer is exactly C:\Games\RynthCore / C:\Games\RynthSuite; paths with spaces.
The environment and registry are a fake; the only real-registry call is a READ of a value that
does not exist. Nothing is ever written.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>InstallPathsTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,167 @@
using RynthCore.Install;
namespace InstallPathsTests;
/// <summary>
/// RynthInstallPaths: where RynthCore and RynthSuite live. Order is environment, HKCU, HKLM,
/// then today's C:\Games folders. Idea from Silentkelpie (rynth PR #1); re-implemented here.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
NothingSetGivesTodaysFolders();
Order();
UnusableValuesAreSkipped();
Tidying();
SpacesInPaths();
ThrowingSourceFallsThrough();
RealRegistryMissingValueIsNull();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"[FAIL] {_case}: {what}");
}
private static void Eq(string? actual, string? expected, string what)
=> Check(string.Equals(actual, expected, StringComparison.Ordinal), $"{what}: expected '{expected}', got '{actual}'");
/// <summary>An in-memory environment and registry; records what was asked.</summary>
private sealed class Fake : IInstallSettingSource
{
public readonly Dictionary<string, string?> Env = new();
public readonly Dictionary<string, string?> User = new();
public readonly Dictionary<string, string?> Machine = new();
public readonly List<string> Asked = new();
public bool Throw;
public string? EnvironmentVariable(string name) { Asked.Add("env:" + name); if (Throw) throw new InvalidOperationException(); return Env.GetValueOrDefault(name); }
public string? CurrentUser(string valueName) { Asked.Add("hkcu:" + valueName); if (Throw) throw new UnauthorizedAccessException(); return User.GetValueOrDefault(valueName); }
public string? LocalMachine(string valueName) { Asked.Add("hklm:" + valueName); if (Throw) throw new IOException(); return Machine.GetValueOrDefault(valueName); }
}
private static string Core(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.CoreEnvironmentVariable,
RynthInstallPaths.CoreValueName, RynthInstallPaths.DefaultCoreDir, f);
private static string Suite(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.SuiteEnvironmentVariable,
RynthInstallPaths.SuiteValueName, RynthInstallPaths.DefaultSuiteDir, f);
private static void NothingSetGivesTodaysFolders()
{
_case = "nothing set";
var f = new Fake();
Eq(Core(f), @"C:\Games\RynthCore", "core default is today's folder");
Eq(Suite(f), @"C:\Games\RynthSuite", "suite default is today's folder");
Eq(Path.Combine(Core(f), "Logs"), @"C:\Games\RynthCore\Logs", "logs under the default");
Eq(Path.Combine(Suite(f), "RynthAi"), @"C:\Games\RynthSuite\RynthAi", "RynthAi under the default");
Check(f.Asked.Contains("env:RYNTHCORE_DIR") && f.Asked.Contains("hkcu:CoreDir") && f.Asked.Contains("hklm:CoreDir"),
"all three sources asked for the core folder");
Check(f.Asked.Contains("env:RYNTHSUITE_DIR") && f.Asked.Contains("hkcu:SuiteDir") && f.Asked.Contains("hklm:SuiteDir"),
"all three sources asked for the suite folder");
Eq(RynthInstallPaths.RegistryKey, @"Software\Rynth", "registry key");
}
private static void Order()
{
_case = "order";
var f = new Fake();
f.Machine["CoreDir"] = @"D:\Machine\RynthCore";
Eq(Core(f), @"D:\Machine\RynthCore", "HKLM beats the default");
f.User["CoreDir"] = @"E:\User\RynthCore";
Eq(Core(f), @"E:\User\RynthCore", "HKCU beats HKLM");
f.Env["RYNTHCORE_DIR"] = @"F:\Dev\RynthCore";
Eq(Core(f), @"F:\Dev\RynthCore", "environment beats HKCU");
f.Asked.Clear();
Core(f);
Check(f.Asked.Count == 1 && f.Asked[0] == "env:RYNTHCORE_DIR", "a usable environment value stops the search");
// The two folders are independent.
var g = new Fake();
g.User["SuiteDir"] = @"E:\Suite";
Eq(Core(g), @"C:\Games\RynthCore", "a suite setting leaves the core folder alone");
Eq(Suite(g), @"E:\Suite", "suite from HKCU");
g.Env["RYNTHCORE_DIR"] = @"F:\Core";
Eq(Suite(g), @"E:\Suite", "a core variable leaves the suite folder alone");
}
private static void UnusableValuesAreSkipped()
{
_case = "unusable values";
foreach (string? bad in new[] { null, "", " ", "\"\"", @"Games\RynthCore", @"..\RynthCore", "RynthCore", "C:", @"C:Games", "D:\\bad|name", "\0" })
{
var f = new Fake();
f.Env["RYNTHCORE_DIR"] = bad;
f.User["CoreDir"] = bad;
f.Machine["CoreDir"] = @"D:\Machine";
Eq(Core(f), @"D:\Machine", $"'{bad}' in env and HKCU falls through to HKLM");
var g = new Fake();
g.Machine["CoreDir"] = bad;
Eq(Core(g), @"C:\Games\RynthCore", $"'{bad}' in HKLM falls back to the default");
}
}
private static void Tidying()
{
_case = "tidying";
Eq(RynthInstallPaths.Normalize(@"D:\Rynth\"), @"D:\Rynth", "trailing separator dropped");
Eq(RynthInstallPaths.Normalize(@"D:\Rynth\\"), @"D:\Rynth", "doubled trailing separator dropped");
Eq(RynthInstallPaths.Normalize("D:/Rynth/Core/"), @"D:\Rynth\Core", "forward slashes");
Eq(RynthInstallPaths.Normalize(" \"D:\\Rynth\" "), @"D:\Rynth", "whitespace and quotes trimmed");
Eq(RynthInstallPaths.Normalize(@"D:\Rynth\.\Core\..\Suite"), @"D:\Rynth\Suite", "dot segments resolved");
Eq(RynthInstallPaths.Normalize(@"D:\"), @"D:\", "a drive root stays a root");
Eq(RynthInstallPaths.Normalize(@"\\nas\games\RynthCore\"), @"\\nas\games\RynthCore", "UNC path");
}
private static void SpacesInPaths()
{
_case = "spaces";
var f = new Fake();
f.User["SuiteDir"] = @"C:\Program Files (x86)\Rynth Suite\";
Eq(Suite(f), @"C:\Program Files (x86)\Rynth Suite", "HKCU value with spaces");
Eq(Path.Combine(Suite(f), "RynthAi", "MetaFiles"), @"C:\Program Files (x86)\Rynth Suite\RynthAi\MetaFiles", "joined path keeps the spaces");
var g = new Fake();
g.Env["RYNTHCORE_DIR"] = "\"D:\\My Games\\Rynth Core\"";
Eq(Core(g), @"D:\My Games\Rynth Core", "quoted environment value with spaces");
var h = new Fake();
h.Machine["CoreDir"] = @" E:\Tom's Games\RynthCore ";
Eq(Core(h), @"E:\Tom's Games\RynthCore", "HKLM value with spaces and an apostrophe, padded");
}
private static void ThrowingSourceFallsThrough()
{
_case = "throwing source";
var f = new Fake { Throw = true };
Eq(Core(f), @"C:\Games\RynthCore", "every source throws -> default, no exception");
Check(f.Asked.Count == 3, "all three sources were still tried");
}
private static void RealRegistryMissingValueIsNull()
{
_case = "real registry (read only)";
string missing = "NoSuchValue-" + Guid.NewGuid().ToString("N");
Check(SystemInstallSettings.Instance.CurrentUser(missing) == null, "HKCU read of a missing value is null");
Check(SystemInstallSettings.Instance.LocalMachine(missing) == null, "HKLM read of a missing value is null");
Check(SystemInstallSettings.Instance.EnvironmentVariable(missing) == null, "missing environment variable is null");
// Whatever this machine has set, the live answers are absolute folders.
Check(Path.IsPathFullyQualified(RynthInstallPaths.CoreDir), "CoreDir is absolute: " + RynthInstallPaths.CoreDir);
Check(Path.IsPathFullyQualified(RynthInstallPaths.SuiteDir), "SuiteDir is absolute: " + RynthInstallPaths.SuiteDir);
Eq(RynthInstallPaths.CoreLogsDir, Path.Combine(RynthInstallPaths.CoreDir, "Logs"), "CoreLogsDir");
Eq(RynthInstallPaths.RynthAiDir, Path.Combine(RynthInstallPaths.SuiteDir, "RynthAi"), "RynthAiDir");
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Item Count and Mini Remote panels' pure logic (2026-10-05):
src\RynthCore.Engine\UI\Data\ItemHudModel.cs, compiled in. The carried count (stacks
summed, any case, worn too), which carried item a remote slot uses (same object, else the
largest stack with its name), the per-character edits, and the item_huds.txt round-trip
(sections per character, slots, unknown lines kept, bad values). No file I/O, 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>ItemHudTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ItemHudModel.cs" Link="Engine\ItemHudModel.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,203 @@
using RynthCore.Engine.UI.Data;
namespace ItemHudTests;
/// <summary>The Item Count / Mini Remote model: counting, slot lookup, edits and item_huds.txt.</summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
CountSumsStacks();
ResolveSlots();
CountListEdits();
SlotEdits();
FileRoundTrip();
PerCharacterSections();
UnknownLinesKept();
BadFileValues();
EditsAreImmutable();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)");
return _failed == 0 ? 0 : 1;
}
private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); }
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"FAIL {_case}: {what}");
}
private static readonly HudItem[] Pack =
{
new(0x80000001, "Mana Scarab", 25),
new(0x80000002, "Mana Scarab", 100),
new(0x80000003, "mana scarab", 3), // any case
new(0x80000004, "Prismatic Taper", 0), // a single item can report 0
new(0x80000005, "Healing Kit", 1),
new(0x80000006, "Greater Mana Scarab", 7),// a different item
new(0x80000007, "Deadly Arrow", 250), // worn (wielded ammo)
};
private static void CountSumsStacks()
{
Case("CountSumsStacks");
Check(ItemHudMath.Count(Pack, "Mana Scarab") == 128, "every Mana Scarab stack summed, any case");
Check(ItemHudMath.Count(Pack, "Prismatic Taper") == 1, "an item without a stack size counts 1");
Check(ItemHudMath.Count(Pack, "Deadly Arrow") == 250, "worn ammo counts");
Check(ItemHudMath.Count(Pack, "Lockpick") == 0, "none carried is 0");
Check(ItemHudMath.Count(Pack, "Scarab") == 0, "the name must match, not just contain");
Check(ItemHudMath.Count(Array.Empty<HudItem>(), "Mana Scarab") == 0, "no items");
}
private static void ResolveSlots()
{
Case("ResolveSlots");
Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x80000001, "Mana Scarab")) == 0x80000001, "the same object while carried");
Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x8000FFFF, "Mana Scarab")) == 0x80000002, "gone (merged/used up): the largest stack with its name");
Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x8000FFFF, "Lockpick")) == 0, "nothing with that name: 0");
Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0, "healing kit")) == 0x80000005, "no id: by name, any case");
Check(ItemHudMath.Resolve(Pack, new RemoteSlot(0x80000005, "")) == 0x80000005, "no name: by id");
Check(ItemHudMath.TryFind(Pack, 0x80000004, out HudItem t) && t.Name == "Prismatic Taper", "TryFind by id");
Check(!ItemHudMath.TryFind(Pack, 0x12345678, out _), "TryFind misses");
}
private static void CountListEdits()
{
Case("CountListEdits");
var c = ItemHudCharacter.Empty;
c = c.WithCount(" Mana Scarab ", out string m1);
Check(c.Counts.SequenceEqual(new[] { "Mana Scarab" }) && m1.StartsWith("Counting", StringComparison.Ordinal), "added, trimmed");
var same = c.WithCount("MANA SCARAB", out string m2);
Check(ReferenceEquals(same, c) && m2.Contains("already"), "a duplicate in another case is refused");
Check(ReferenceEquals(c.WithCount(" ", out string m3), c) && m3.Length > 0, "an empty name is refused");
c = c.WithCount("Healing Kit", out _).WithCount("Lock|pick", out _);
Check(c.Counts.Length == 3 && c.Counts[2] == "Lock pick", "a bar can't break the file format");
c = c.WithoutCount(c.IndexOfCount("healing kit"));
Check(c.Counts.SequenceEqual(new[] { "Mana Scarab", "Lock pick" }), "removed by name, any case");
Check(ReferenceEquals(c.WithoutCount(9), c), "a bad index changes nothing");
var full = ItemHudCharacter.Empty;
for (int i = 0; i < ItemHudCharacter.MaxCounts + 3; i++) full = full.WithCount("Item " + i, out _);
Check(full.Counts.Length == ItemHudCharacter.MaxCounts, "capped");
string longName = new('x', 200);
Check(ItemHudCharacter.Empty.WithCount(longName, out _).Counts[0].Length == ItemHudCharacter.MaxNameLength, "long names cut");
}
private static void SlotEdits()
{
Case("SlotEdits");
var c = ItemHudCharacter.Empty;
Check(c.Slots.Length == ItemHudCharacter.DefaultSlots && c.Slots.All(s => s == null), "8 empty slots by default");
c = c.WithSlot(2, new RemoteSlot(0x80000005, "Healing Kit"));
Check(c.Slots[2] == new RemoteSlot(0x80000005, "Healing Kit"), "slot set");
Check(ReferenceEquals(c.WithSlot(99, new RemoteSlot(1, "x")), c), "out of range: no change");
c = c.WithSlotCount(12);
Check(c.Slots.Length == 12 && c.Slots[2]?.Name == "Healing Kit", "more slots keep the filled ones");
c = c.WithSlotCount(1);
Check(c.Slots.Length == ItemHudCharacter.MinSlots && c.Slots[2]?.Name == "Healing Kit", "at least 4 slots");
c = c.WithSlotCount(1000);
Check(c.Slots.Length == ItemHudCharacter.MaxSlots, "at most 24");
c = c.WithSlot(2, null);
Check(c.Slots[2] == null, "cleared");
}
private static ItemHudFile.Contents RoundTrip(ItemHudFile.Contents c) =>
ItemHudFile.Parse(ItemHudFile.Write(c).Split('\n'));
private static void FileRoundTrip()
{
Case("FileRoundTrip");
var c = new ItemHudFile.Contents();
var d = ItemHudCharacter.Empty.WithCount("Mana Scarab", out _).WithCount("Deadly Arrow", out _)
.WithSlotCount(12).WithSlot(0, new RemoteSlot(0x80123456, "Healing Kit")).WithSlot(11, new RemoteSlot(0x8012ABCD, "Stamina Elixir"));
c.Set("Aelrynth/Drakkon", d);
string text = ItemHudFile.Write(c);
Check(text.StartsWith(ItemHudFile.Header, StringComparison.Ordinal), "header first");
Check(text.Contains("[Aelrynth/Drakkon]\n") && text.Contains("count=Mana Scarab\n") && text.Contains("slots=12\n")
&& text.Contains("slot=0|0x80123456|Healing Kit\n") && text.Contains("slot=11|0x8012ABCD|Stamina Elixir\n"), "readable lines");
var back = RoundTrip(c).For("aelrynth/drakkon");
Check(back.Counts.SequenceEqual(d.Counts), "counts back, in order (key any case)");
Check(back.Slots.Length == 12 && back.Slots[0] == d.Slots[0] && back.Slots[11] == d.Slots[11] && back.Slots[5] == null, "slots back");
Check(ItemHudFile.Write(RoundTrip(c)) == text, "a second save is identical");
}
private static void PerCharacterSections()
{
Case("PerCharacterSections");
var c = new ItemHudFile.Contents();
c.Set("Aelrynth/One", ItemHudCharacter.Empty.WithCount("Mana Scarab", out _));
c.Set("Aelrynth/Two", ItemHudCharacter.Empty.WithCount("Healing Kit", out _));
c.Set("Other/One", ItemHudCharacter.Empty.WithSlot(1, new RemoteSlot(5, "Pyreal")));
var back = RoundTrip(c);
Check(back.For("Aelrynth/One").Counts.SequenceEqual(new[] { "Mana Scarab" }), "first character");
Check(back.For("Aelrynth/Two").Counts.SequenceEqual(new[] { "Healing Kit" }), "second character apart");
Check(back.For("Other/One").Counts.Length == 0 && back.For("Other/One").Slots[1]?.Name == "Pyreal", "same name on another server apart");
Check(ReferenceEquals(back.For("Nobody/Here"), ItemHudCharacter.Empty), "an unknown character: empty");
Check(back.Order.SequenceEqual(new[] { "Aelrynth/One", "Aelrynth/Two", "Other/One" }), "file order kept");
}
private static void UnknownLinesKept()
{
Case("UnknownLinesKept");
string[] file =
{
"# a comment",
"future=1",
"[A/B]",
"count=Mana Scarab",
"iconSize=24",
"slot=0|0x00000005|Pyreal",
};
var c = ItemHudFile.Parse(file);
Check(c.Preamble.SequenceEqual(new[] { "future=1" }), "a line before any section kept");
Check(c.For("A/B").Other.SequenceEqual(new[] { "iconSize=24" }), "an unknown line in a section kept");
string text = ItemHudFile.Write(c);
Check(text.Contains("future=1\n") && text.Contains("iconSize=24\n"), "and written back");
Check(!text.Contains("# a comment"), "comments are ours to write");
}
private static void BadFileValues()
{
Case("BadFileValues");
string[] file =
{
"[A/B]",
"count=",
"count=Mana Scarab",
"count=MANA SCARAB",
"slots=banana",
"slots=2",
"slot=x|0x5|Pyreal",
"slot=3|zzz|Pyreal",
"slot=30|0x5|Pyreal",
"slot=1|0x0|",
"slot=2|17|Decimal Id",
};
var d = ItemHudFile.Parse(file).For("A/B");
Check(d.Counts.SequenceEqual(new[] { "Mana Scarab" }), "empty and duplicate counts dropped");
Check(d.Slots.Length == ItemHudCharacter.MinSlots, "slots clamped to the minimum");
Check(d.Slots[1] == null, "a slot with no id and no name stays empty");
Check(d.Slots[2] == new RemoteSlot(17, "Decimal Id"), "a decimal id reads");
Check(d.Other.Count(o => o.StartsWith("slot=", StringComparison.Ordinal)) == 3, "unreadable slot lines kept as they were");
Check(ItemHudFile.Parse(Array.Empty<string>()).Order.Count == 0, "an empty file");
}
private static void EditsAreImmutable()
{
Case("EditsAreImmutable");
var a = ItemHudCharacter.Empty.WithCount("Mana Scarab", out _).WithSlot(0, new RemoteSlot(1, "Pyreal"));
string[] counts = a.Counts;
var slots = a.Slots;
var b = a.WithCount("Healing Kit", out _).WithSlot(0, null).WithSlotCount(12);
Check(counts.Length == 1 && a.Counts.Length == 1, "the old lists are unchanged");
Check(slots[0]?.Name == "Pyreal" && a.Slots.Length == ItemHudCharacter.DefaultSlots, "the old slots are unchanged");
Check(b.Counts.Length == 2 && b.Slots[0] == null && b.Slots.Length == 12, "the new ones have the edits");
Check(ItemHudCharacter.Empty.Counts.Length == 0 && ItemHudCharacter.Empty.Slots.All(s => s == null), "Empty stays empty");
}
}

View file

@ -28,4 +28,8 @@
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Meta editor's rules (2026-10-05 clean-up), compiled in from
src/RynthCore.Engine/UI/Data: MetaEditing.cs (new state names, the autosave debounce, the
one .bak per session, placeholder rule, Add condition / action, finding a rule again by
content), MetaLocation.cs ("Set current" text for landblock / landcell, against a copy of
RynthAi's MetaManager reading; RynthSuite's RynthAiHostTests check the real one) and
MetaRuleDto.cs. Nothing native: no AC, no ImGui, no files.
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>MetaEditTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaEditing.cs" Link="Engine\MetaEditing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRuleDto.cs" Link="Engine\MetaRuleDto.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,328 @@
using System.Globalization;
using RynthCore.Engine.UI.Data;
namespace MetaEditTests;
/// <summary>
/// The Meta editor's rules without AC or ImGui: what a new state may be called, when an edit is
/// saved, which file is backed up once per session, the "Set current" landblock / landcell text,
/// and the rule edits behind "+ New state..." and "+ Add".
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
StateNames();
AutosaveDebounce();
BackupOncePerSession();
LocationText();
Placeholder();
AddCondition();
AddAction();
TakesData();
NoKillsMinutes();
SameContentAndLocate();
Console.WriteLine();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks");
return _failed == 0 ? 0 : 1;
}
// ── New state names ──────────────────────────────────────────────────
private static void StateNames()
{
Case("new state names");
string[] states = { "Default", "Combat", "Loot Run" };
Eq(MetaStateName.Problem(" Buff ", states, out string n), null, "a new name is fine");
Eq(n, "Buff", "trimmed");
True(MetaStateName.Problem("", states, out _) != null, "empty refused");
True(MetaStateName.Problem(" ", states, out _) != null, "blank refused");
True(MetaStateName.Problem(null, states, out _) != null, "null refused");
True(MetaStateName.Problem("Combat", states, out _) != null, "duplicate refused");
True(MetaStateName.Problem(" combat ", states, out _)?.Contains("Combat") == true, "duplicate ignoring case, names the existing one");
True(MetaStateName.Problem("loot run", states, out _) != null, "duplicate with a space, any case");
True(MetaStateName.Problem("A{b}", states, out _) != null, "braces refused (.af writes STATE: {name})");
True(MetaStateName.Problem("a\tb", states, out _) != null, "tab refused");
True(MetaStateName.Problem(new string('x', MetaStateName.MaxLength + 1), states, out _) != null, "too long refused");
Eq(MetaStateName.Problem(new string('x', MetaStateName.MaxLength), states, out _), null, "longest allowed");
Eq(MetaStateName.Problem("Default 2", states, out _), null, "a name containing an existing one is fine");
Eq(MetaStateName.Problem("Ärger", Array.Empty<string>(), out _), null, "non-ASCII fine");
}
// ── Autosave ─────────────────────────────────────────────────────────
private static void AutosaveDebounce()
{
Case("autosave debounce");
var a = new MetaAutosave();
False(a.Dirty, "clean at start");
False(a.Due(10_000, typing: false), "nothing to save");
False(a.Take(), "nothing to take");
a.Changed(1000);
True(a.Dirty, "dirty after a change");
False(a.Due(1000 + 749, typing: false), "not before 750 ms");
True(a.Due(1000 + 750, typing: false), "due at 750 ms");
a.Changed(1500); // another change restarts the clock
False(a.Due(1000 + 800, typing: false), "a later change restarts the clock");
True(a.Due(1500 + 750, typing: false), "due 750 ms after the last change");
False(a.Due(1500 + 5000, typing: true), "never while a box is being typed in");
True(a.Due(1500 + 5000, typing: false), "due as soon as the box is left");
True(a.Take(), "take the pending edit");
False(a.Dirty, "clean after taking");
False(a.Due(99_999, typing: false), "nothing due after a save");
a.Changed(2000);
True(a.Take(), "a flush (Back / close / meta switch) takes it before the debounce");
False(a.Take(), "only once");
a.Changed(3000);
a.Clear();
False(a.Dirty, "Clear drops it (deleted rule / discarded draft)");
// Typing burst: one save, not one per key.
var b = new MetaAutosave();
int saves = 0;
for (int t = 0; t <= 3000; t += 16)
{
bool typing = t < 2000;
if (typing && t % 160 == 0) b.Changed(t); // a key every 160 ms for 2 s
if (b.Due(t, typing) && b.Take()) saves++;
}
Eq(saves, 1, "a 2 s typing burst saves once, after the box is left");
}
// ── Backup ───────────────────────────────────────────────────────────
private static void BackupOncePerSession()
{
Case("one backup per session");
var p = new MetaBackupPlan();
string farm = Path.Combine("C:\\Games", "RynthSuite", "RynthAi", "MetaFiles", "farm.af");
Eq(p.Before(farm), (farm, farm + ".bak"), "first save backs the file up");
Eq(p.Before(farm), null, "not again this session");
Eq(p.Before(farm.ToUpperInvariant()), null, "same file in another case");
string other = Path.ChangeExtension(farm, null) + "2.af";
Eq(p.Before(other), (other, other + ".bak"), "another meta: its own backup");
Eq(p.Before(farm), null, "switching back: still once per file");
p.NewSession();
Eq(p.Before(farm), (farm, farm + ".bak"), "a new session backs up again (overwrites the .bak)");
Eq(p.Before(""), null, "a meta without a file: nothing");
Eq(p.Before(null), null, "null path: nothing");
string met = Path.ChangeExtension(farm, ".met");
string metAf = Path.ChangeExtension(farm, ".af");
var q = new MetaBackupPlan();
Eq(q.Before(met), (metAf, metAf + ".bak"), "a .met meta saves as the .af beside it: that is what is backed up");
Eq(MetaBackupPlan.WrittenFile(farm), farm, ".af written as is");
}
// ── Set current ──────────────────────────────────────────────────────
private static void LocationText()
{
Case("set current (landblock / landcell)");
Eq(MetaLocation.LandblockText(0xA9B4001C), "A9B40000", "landblock: 8 digits, low word zero");
Eq(MetaLocation.LandcellText(0xA9B4001C), "A9B4001C", "landcell: the whole cell");
Eq(MetaLocation.LandcellText(0x00070143), "00070143", "leading zeros kept");
Eq(MetaLocation.Text(16, 0x8B370105), "8B370000", "Landblock == is condition 16");
Eq(MetaLocation.Text(17, 0x8B370105), "8B370105", "Landcell == is condition 17");
Eq(MetaLocation.Text(15, 0x8B370105), null, "other conditions: none");
True(MetaLocation.TakesPosition(16) && MetaLocation.TakesPosition(17) && !MetaLocation.TakesPosition(18), "TakesPosition");
// A copy of RynthAi's MetaManager reading (Landblock_EQ / Landcell_EQ); RynthAiHostTests
// run the real one against MetaLocation.
foreach (uint cell in new uint[] { 0xA9B4001C, 0x00070143, 0x0000FFFF, 0x00010001, 0xFFFF0100, 0x12340031 })
{
True(BlockMatches(MetaLocation.LandblockText(cell), cell), $"landblock text matches its own cell {cell:X8}");
True(CellMatches(MetaLocation.LandcellText(cell), cell), $"landcell text matches its own cell {cell:X8}");
False(BlockMatches(MetaLocation.LandblockText(cell), cell ^ 0x00010000), $"not the next landblock {cell:X8}");
False(CellMatches(MetaLocation.LandcellText(cell), cell ^ 1), $"not the next cell {cell:X8}");
}
}
private static bool BlockMatches(string data, uint cellId)
{
uint landblock = cellId >> 16;
if (uint.TryParse(data, NumberStyles.HexNumber, null, out uint hex))
{
if (hex > 0xFFFF) hex >>= 16;
return landblock == hex;
}
return false;
}
private static bool CellMatches(string data, uint cellId) =>
uint.TryParse(data, NumberStyles.HexNumber, null, out uint hex) && cellId == hex;
// ── Rule edits ───────────────────────────────────────────────────────
private static void Placeholder()
{
Case("a new state's first rule");
MetaRuleDto r = MetaRuleEdit.Placeholder("Buff");
Eq(r.State, "Buff", "in the new state");
Eq(r.Condition, 0, "Never");
Eq(r.Action, 0, "None");
True(r.Enabled, "enabled (it can't fire anyway)");
True(MetaRuleEdit.IsPlaceholder(r), "is the placeholder");
r.ActionData = "x";
False(MetaRuleEdit.IsPlaceholder(r), "with data it isn't");
False(MetaRuleEdit.IsPlaceholder(new MetaRuleDto { Condition = 1 }), "Always isn't");
}
private static void AddCondition()
{
Case("+ Add condition");
var r = new MetaRuleDto { State = "S", Condition = 16, ConditionData = "A9B40000" };
True(MetaRuleEdit.CanAddCondition(r), "can add to a single condition");
MetaRuleEdit.AddCondition(r);
Eq(r.Condition, MetaRuleEdit.All, "a single condition becomes an All");
Eq(r.ConditionData, "", "the All has no data");
Eq(r.Children.Count, 2, "old + new");
Eq(r.Children[0].Condition, 16, "the old condition first");
Eq(r.Children[0].ConditionData, "A9B40000", "with its data");
Eq(r.Children[1].Condition, MetaRuleEdit.Never, "the new one is Never until picked");
Eq(r.Children[1].State, "S", "same state");
MetaRuleEdit.AddCondition(r);
Eq(r.Children.Count, 3, "an All gets one more");
var any = new MetaRuleDto { Condition = MetaRuleEdit.Any };
MetaRuleEdit.AddCondition(any);
Eq(any.Children.Count, 1, "an empty Any gets its first");
var not = new MetaRuleDto { Condition = MetaRuleEdit.Not };
True(MetaRuleEdit.CanAddCondition(not), "an empty Not can take one");
MetaRuleEdit.AddCondition(not);
Eq(not.Children.Count, 1, "Not got its operand");
False(MetaRuleEdit.CanAddCondition(not), "a full Not can't");
MetaRuleEdit.AddCondition(not);
Eq(not.Children.Count, 1, "adding to a full Not does nothing");
Eq(not.Condition, MetaRuleEdit.Not, "still a Not");
}
private static void AddAction()
{
Case("+ Add action");
var r = new MetaRuleDto { Action = 1, ActionData = "/say hi" };
MetaRuleEdit.AddAction(r);
Eq(r.Action, MetaRuleEdit.DoAll, "a single action becomes a DoAll");
Eq(r.ActionData, "", "the DoAll has no data");
Eq(r.ActionChildren.Count, 2, "old + new");
Eq(r.ActionChildren[0].ActionData, "/say hi", "old first, data kept");
Eq(r.ActionChildren[1].Action, MetaRuleEdit.NoAction, "the new one is None until picked");
MetaRuleEdit.AddAction(r);
Eq(r.ActionChildren.Count, 3, "a DoAll gets one more");
}
private static void TakesData()
{
Case("which conditions / actions have a value");
foreach (int c in new[] { 0, 1, 7, 8, 9, 14, 18, 19, 28, 2, 3, 20 })
False(MetaRuleEdit.ConditionTakesData(c), $"condition {c} has no value");
foreach (int c in new[] { 4, 5, 6, 10, 11, 12, 13, 15, 16, 17, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35 })
True(MetaRuleEdit.ConditionTakesData(c), $"condition {c} has a value");
foreach (int a in new[] { 0, 4, 6, 10, 15 })
False(MetaRuleEdit.ActionTakesData(a), $"action {a} has no value");
foreach (int a in new[] { 1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14 })
True(MetaRuleEdit.ActionTakesData(a), $"action {a} has a value");
Case("a new rule is added once filled in");
False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1 }), "Always -> Chat with no command: not yet");
True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1, ActionData = "/say hi" }), "Always -> /say hi");
False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 1, Action = 1, ActionData = " " }), "blank command: not yet");
False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 16, Action = 6 }), "Landblock with no value: not yet");
True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 16, ConditionData = "A9B40000", Action = 6 }), "Landblock -> Return");
True(MetaRuleEdit.ReadyToAdd(MetaRuleEdit.Placeholder("S")), "Never -> None");
var all = new MetaRuleDto { Condition = MetaRuleEdit.All, Action = 6 };
False(MetaRuleEdit.ReadyToAdd(all), "an empty All: not yet");
all.Children.Add(new MetaRuleDto { Condition = 4 });
False(MetaRuleEdit.ReadyToAdd(all), "an All with an empty Chat Message: not yet");
all.Children[0].ConditionData = "hello";
True(MetaRuleEdit.ReadyToAdd(all), "All(Chat Message: hello) -> Return");
var doAll = new MetaRuleDto { Condition = 1, Action = MetaRuleEdit.DoAll };
False(MetaRuleEdit.ReadyToAdd(doAll), "an empty DoAll: not yet");
doAll.ActionChildren.Add(new MetaRuleDto { Action = 2 });
False(MetaRuleEdit.ReadyToAdd(doAll), "DoAll(Set Meta State with no state): not yet");
doAll.ActionChildren[0].ActionData = "Buff";
True(MetaRuleEdit.ReadyToAdd(doAll), "DoAll(Set Meta State Buff)");
}
// ── No Kills Within Minutes (2026-10-06) ─────────────────────────────
private static void NoKillsMinutes()
{
Case("No Kills Within Minutes: the minutes box");
Eq(MetaRuleEdit.NoKillsWithinMinutes, 35, "RynthAi's enum value (appended after Vitae % >=)");
True(MetaRuleEdit.ConditionTakesData(MetaRuleEdit.NoKillsWithinMinutes), "takes a value");
False(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 35, Action = 6 }), "no minutes yet: not added");
True(MetaRuleEdit.ReadyToAdd(new MetaRuleDto { Condition = 35, ConditionData = "5", Action = 6 }), "5 minutes -> Return");
foreach (string ok in new[] { "5", "0", "2.5", " 10 ", "0,5", "1e1" })
True(MetaRuleEdit.MinutesOk(ok), $"'{ok}' is minutes");
foreach (string bad in new[] { "", "abc", "-1", "5m", "NaN", "Infinity" })
False(MetaRuleEdit.MinutesOk(bad), $"'{bad}' is not");
False(MetaRuleEdit.NoKillsTooltip("5").Contains("isn't a number"), "a number: the plain explanation");
True(MetaRuleEdit.NoKillsTooltip("five").Contains("never holds"), "not a number: says it never holds");
False(MetaRuleEdit.NoKillsTooltip("").Contains("isn't a number"), "empty: the plain explanation");
}
private static void SameContentAndLocate()
{
Case("finding the edited rule again");
MetaRuleDto R(string state, int cond, string data) => new() { State = state, Condition = cond, ConditionData = data, Action = 1, ActionData = "/x" };
var a = R("S", 4, "a");
var b = R("S", 4, "b");
var c = R("T", 4, "a");
True(MetaRuleEdit.SameContent(a, a.Clone()), "a clone is the same");
var fired = a.Clone();
fired.LastFiredMs = 5;
True(MetaRuleEdit.SameContent(a, fired), "LastFiredMs doesn't count");
False(MetaRuleEdit.SameContent(a, b), "data differs");
False(MetaRuleEdit.SameContent(a, c), "state differs");
var child1 = a.Clone(); child1.Children.Add(R("S", 1, ""));
var child2 = a.Clone(); child2.Children.Add(R("S", 0, ""));
False(MetaRuleEdit.SameContent(child1, child2), "children compared");
False(MetaRuleEdit.SameContent(a, child1), "child count compared");
var list = new List<MetaRuleDto> { b, a, c };
Eq(MetaRuleEdit.Locate(list, a, 1), 1, "still at its index");
Eq(MetaRuleEdit.Locate(list, a, 0), 1, "moved: found by content");
Eq(MetaRuleEdit.Locate(list, R("S", 4, "zzz"), 2), 2, "not in the snapshot yet: the hint");
Eq(MetaRuleEdit.Locate(list, a, 7), 1, "a hint past the end: found");
var dupes = new List<MetaRuleDto> { a.Clone(), b, a.Clone(), c, a.Clone() };
Eq(MetaRuleEdit.Locate(dupes, a, 3), 2, "duplicates: the nearest to the hint");
}
// ── Checks ───────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine("== " + name);
}
private static void True(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
private static void False(bool ok, string what) => True(!ok, what);
private static void Eq<T>(T actual, T expected, string what)
{
_checks++;
if (EqualityComparer<T>.Default.Equals(actual, expected)) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}: expected <{expected}>, got <{actual}>");
}
}

View file

@ -23,4 +23,8 @@
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the popped-out panel window destroy backup
(src\RynthCore.Engine\UI\PanelDestroyFallback.cs, compiled in): when LayeredWindow.Dispose can't post
the self-destroy to a panel, it destroys the window only on its owner thread and only if it is still
one of our panel windows; otherwise it leaves it hidden. Never a cross-thread DestroyWindow.
No windows are created. 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>PanelWindowTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelDestroyFallback.cs" Link="Engine\PanelDestroyFallback.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,48 @@
using RynthCore.Engine.UI;
namespace PanelWindowTests;
/// <summary>
/// The backup path of LayeredWindow.Dispose (PanelDestroyPlan.Choose). Win32 only lets the creating
/// thread destroy a window. Idea from Silentkelpie (rynth PR #1); re-implemented here.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main()
{
const uint game = 0x1A2C, avalonia = 0x2B40;
Check(PanelDestroyPlan.Choose(0, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone,
"window gone (no owner thread) -> nothing");
Check(PanelDestroyPlan.Choose(0, game, ourPanel: true) == PanelDestroyFallback.AlreadyGone,
"window gone even if the class looked like ours -> nothing");
Check(PanelDestroyPlan.Choose(game, game, ourPanel: true) == PanelDestroyFallback.DestroyHere,
"game thread owns it, game thread disposing -> destroy here");
Check(PanelDestroyPlan.Choose(avalonia, avalonia, ourPanel: true) == PanelDestroyFallback.DestroyHere,
"Avalonia UI thread owns it, Avalonia UI thread disposing -> destroy here");
Check(PanelDestroyPlan.Choose(avalonia, game, ourPanel: true) == PanelDestroyFallback.LeaveHidden,
"panel made on the Avalonia UI thread, disposed from the game thread -> leave hidden, no cross-thread destroy");
Check(PanelDestroyPlan.Choose(game, avalonia, ourPanel: true) == PanelDestroyFallback.LeaveHidden,
"panel made on the game thread, disposed from the Avalonia UI thread (redock) -> leave hidden");
Check(PanelDestroyPlan.Choose(game, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone,
"handle reused by a window that isn't a panel -> never destroy it");
Check(PanelDestroyPlan.Choose(avalonia, game, ourPanel: false) == PanelDestroyFallback.AlreadyGone,
"handle reused on another thread -> never touch it");
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"[FAIL] {what}");
}
}

View file

@ -9,7 +9,10 @@
this test's own DLL with UpdateResource, as the build does);
- the SDK's API version can't drift: RynthCoreHost.CurrentApiVersion, the SDK's table size
(RynthCoreApiNative vs the engine's RynthCoreAPI, compiled in) and the build targets'
RynthCoreSdkApiVersion all match PluginContractVersion.Current.
RynthCoreSdkApiVersion all match PluginContractVersion.Current;
- PluginPaths de-duplication (src\RynthCore.Engine\Plugins\PluginPathDedupe.cs, compiled in):
the same DLL listed twice (any case or slashes) loads once; the same file name from two
folders keeps the first and warns.
Extra arguments are plugin DLLs to read and check (e.g. a RynthSuite publish folder's).
Never loads a plugin, never touches %APPDATA% or C:\Games.
Run: dotnet run -c Release [plugin.dll ...] (arguments after a double dash) (exit 0 = pass, 1 = fail)
@ -35,6 +38,7 @@
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContract.cs" Link="Engine\PluginContract.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Engine\PluginContractVersion.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginManifestGate.cs" Link="Engine\PluginManifestGate.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginPathDedupe.cs" Link="Engine\PluginPathDedupe.cs" />
</ItemGroup>
</Project>

View file

@ -53,6 +53,11 @@ internal static class Program
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice);
Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes);
Run(nameof(DedupeSameNameTwoFolders), DedupeSameNameTwoFolders);
Run(nameof(DedupeAgainstAlreadyLoaded), DedupeAgainstAlreadyLoaded);
Run(nameof(DedupeKeepsOrderAndText), DedupeKeepsOrderAndText);
foreach (string dll in args)
Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll));
}
@ -489,6 +494,86 @@ internal static class Program
"the SDK assembly carries no manifest attribute");
}
// ── PluginPaths de-duplication (PluginPathDedupe; Silentkelpie, rynth PR #1) ──
private const string SuiteDir = @"C:\Games\RynthSuite\Plugins";
private const string OtherDir = @"D:\Old\RynthSuite";
private static void DedupeSamePathTwice()
{
string ai = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll");
string chat = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthChat.dll");
var r = PluginPathDedupe.Dedupe(new[] { ai, chat, ai });
Eq(string.Join("|", r.Load), ai + "|" + chat, "loads each once, in order");
Eq(r.Skipped.Count, 1, "one skipped");
Check(r.Skipped[0].SameFile && r.Skipped[0].Path == ai && r.Skipped[0].KeptPath == ai, "repeat flagged as the same file");
Check(r.Skipped[0].Message.Contains("listed twice") && !r.Skipped[0].Message.Contains("conflict"), "repeat is not called a conflict: " + r.Skipped[0].Message);
}
private static void DedupeCaseAndSlashes()
{
string ai = SuiteDir + @"\RynthCore.Plugin.RynthAi.dll";
string[] spellings =
{
ai.ToUpperInvariant(),
ai.Replace('\\', '/'),
@"C:\Games\RynthSuite\Plugins\..\Plugins\.\rynthcore.plugin.rynthai.DLL",
" " + ai + " ",
};
foreach (string other in spellings)
{
var r = PluginPathDedupe.Dedupe(new[] { ai, other });
Eq(r.Load.Count, 1, $"'{other}' loads once");
Check(r.Skipped.Count == 1 && r.Skipped[0].SameFile, $"'{other}' is the same file, not a conflict");
}
Eq(PluginPathDedupe.Normalize("C:/Games/RynthSuite/Plugins/"), @"C:\Games\RynthSuite\Plugins", "normalize: slashes and trailing separator");
}
private static void DedupeSameNameTwoFolders()
{
string first = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll");
string second = Path.Combine(OtherDir, "rynthcore.plugin.rynthai.dll");
string nav = Path.Combine(OtherDir, "RynthCore.Plugin.RynthNav.dll");
var r = PluginPathDedupe.Dedupe(new[] { first, nav, second });
Eq(string.Join("|", r.Load), first + "|" + nav, "the first listed wins; other plugins in that folder still load");
Eq(r.Skipped.Count, 1, "one skipped");
PluginPathDedupe.Skipped s = r.Skipped[0];
Check(!s.SameFile && !s.KeptAlreadyLoaded, "flagged as a conflict between two copies");
Eq(s.KeptPath, first, "kept path");
Check(s.Message.StartsWith("plugin conflict") && s.Message.Contains(first) && s.Message.Contains(second) && s.Message.Contains("listed first"),
"warning names both copies and which won: " + s.Message);
// Reversed order: the other one wins. First listed is the rule, not a folder preference.
var rev = PluginPathDedupe.Dedupe(new[] { second, first });
Eq(rev.Load.Single(), second, "reversed: the first listed wins");
}
private static void DedupeAgainstAlreadyLoaded()
{
string loaded = Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll");
string copy = Path.Combine(OtherDir, "RynthCore.Plugin.RynthAi.dll");
var r = PluginPathDedupe.Dedupe(new[] { loaded.ToLowerInvariant(), copy }, new[] { loaded });
Eq(r.Load.Count, 0, "nothing new to load");
Eq(r.Skipped.Count, 2, "both skipped");
Check(r.Skipped[0].SameFile && r.Skipped[0].KeptAlreadyLoaded && r.Skipped[0].Message.Contains("already loaded"), "same file as a loaded plugin");
Check(!r.Skipped[1].SameFile && r.Skipped[1].KeptAlreadyLoaded && r.Skipped[1].Message.Contains("already loaded"), "a second copy of a loaded plugin is a conflict");
}
private static void DedupeKeepsOrderAndText()
{
string[] paths =
{
Path.Combine(SuiteDir, "RynthCore.Plugin.RynthChat.dll"),
"",
Path.Combine(SuiteDir, "RynthCore.Plugin.RynthAi.dll"),
Path.Combine(SuiteDir, "RynthCore.Plugin.RynthNav.dll"),
};
var r = PluginPathDedupe.Dedupe(paths);
Eq(string.Join("|", r.Load), paths[0] + "|" + paths[2] + "|" + paths[3], "no duplicates: everything loads, as listed, text unchanged");
Eq(r.Skipped.Count, 0, "nothing skipped");
Eq(PluginPathDedupe.Dedupe(Array.Empty<string>()).Load.Count, 0, "empty list");
}
private static string FindUp(string relative)
{
for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent)

View file

@ -34,4 +34,8 @@
<Compile Include="..\..\src\RynthCore.StatusAgent\StatusFileCache.cs" Link="Agent\StatusFileCache.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -23,4 +23,8 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\UsageStats.cs" Link="App\UsageStats.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,204 @@
using RynthCore.Engine.D3D9;
namespace VideoPatchTests;
/// <summary>The video patch's modes, focus logic, frame cap and settings file (VideoPatchPolicy).</summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
OffNeverSkips();
WorldSkipsSceneOnly();
UnfocusedFollowsFocus();
AllSkipsUiOnlyWithImGui();
OutsideTheWorldNothingSkips();
FrameCap();
CommandWords();
ComboMatchesEnum();
CharacterKeys();
FileRoundTrip();
AllIsNeverSaved();
OffRemovesTheLine();
DefaultLineAndUnknownLines();
BadFileValues();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)");
return _failed == 0 ? 0 : 1;
}
private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); }
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"FAIL {_case}: {what}");
}
private static VideoPatchDecision D(VideoPatchMode m, bool inWorld = true, bool focused = true, bool imgui = true) =>
VideoPatchPolicy.Decide(m, inWorld, focused, imgui);
private static void OffNeverSkips()
{
Case("OffNeverSkips");
foreach (bool w in new[] { true, false })
foreach (bool f in new[] { true, false })
foreach (bool i in new[] { true, false })
Check(!D(VideoPatchMode.Off, w, f, i).Any, $"off skipped something (world={w} focused={f} imgui={i})");
}
private static void WorldSkipsSceneOnly()
{
Case("WorldSkipsSceneOnly");
foreach (bool f in new[] { true, false })
{
var d = D(VideoPatchMode.World, focused: f);
Check(d.SkipWorld, "world mode must skip the 3D scene");
Check(!d.SkipAcUi, "world mode must keep AC's UI");
}
}
private static void UnfocusedFollowsFocus()
{
Case("UnfocusedFollowsFocus");
Check(!D(VideoPatchMode.Unfocused, focused: true).Any, "focused client must draw everything");
var bg = D(VideoPatchMode.Unfocused, focused: false);
Check(bg.SkipWorld && !bg.SkipAcUi, "background client: world skipped, UI kept");
// Switching back is per frame: the decision has no memory.
Check(!D(VideoPatchMode.Unfocused, focused: true).Any, "focus back must draw again at once");
}
private static void AllSkipsUiOnlyWithImGui()
{
Case("AllSkipsUiOnlyWithImGui");
var all = D(VideoPatchMode.All);
Check(all.SkipWorld && all.SkipAcUi, "all with ImGui: scene and AC UI skipped");
var noImgui = D(VideoPatchMode.All, imgui: false);
Check(noImgui.SkipWorld && !noImgui.SkipAcUi, "all without the ImGui layer falls back to world (AC's chat stays)");
Check(D(VideoPatchMode.All, focused: true).SkipAcUi, "all ignores focus");
}
private static void OutsideTheWorldNothingSkips()
{
Case("OutsideTheWorldNothingSkips");
foreach (VideoPatchMode m in Enum.GetValues<VideoPatchMode>())
foreach (bool f in new[] { true, false })
Check(!D(m, inWorld: false, focused: f).Any, $"{m} skipped outside the world (login/character select must draw)");
}
private static void FrameCap()
{
Case("FrameCap");
var skip = new VideoPatchDecision(true, false);
Check(VideoPatchPolicy.FrameCap(skip, 15) == 15, "default cap");
Check(VideoPatchPolicy.FrameCap(skip, 0) == 0, "0 = no cap");
Check(VideoPatchPolicy.FrameCap(skip, 2) == VideoPatchPolicy.MinFrameCapFps, "cap clamps up to the minimum");
Check(VideoPatchPolicy.FrameCap(skip, 500) == VideoPatchPolicy.MaxFrameCapFps, "cap clamps down to the maximum");
Check(VideoPatchPolicy.FrameCap(VideoPatchDecision.None, 15) == 0, "no cap while drawing");
Check(VideoPatchPolicy.FrameCap(D(VideoPatchMode.Unfocused, focused: true), 15) == 0, "no cap for a focused 'unfocused' client");
Check(VideoPatchPolicy.FrameCap(D(VideoPatchMode.Unfocused, focused: false), 15) == 15, "cap for a background 'unfocused' client");
Check(VideoPatchPolicy.ClampCap(-3) == 0, "negative = no cap");
}
private static void CommandWords()
{
Case("CommandWords");
(string word, VideoPatchMode mode)[] words =
{
("off", VideoPatchMode.Off), ("OFF", VideoPatchMode.Off), ("on", VideoPatchMode.World),
("world", VideoPatchMode.World), ("unfocused", VideoPatchMode.Unfocused), ("focus", VideoPatchMode.Unfocused),
("all", VideoPatchMode.All), (" all ", VideoPatchMode.All),
};
foreach ((string word, VideoPatchMode mode) in words)
Check(VideoPatchPolicy.TryParse(word, out VideoPatchMode m) && m == mode, $"'{word}' -> {mode}");
Check(!VideoPatchPolicy.TryParse("status", out _), "'status' is not a mode");
Check(!VideoPatchPolicy.TryParse(null, out _), "null is not a mode");
foreach (VideoPatchMode m in Enum.GetValues<VideoPatchMode>())
Check(VideoPatchPolicy.TryParse(VideoPatchPolicy.Name(m), out VideoPatchMode back) && back == m, $"Name({m}) round-trips");
}
private static void ComboMatchesEnum()
{
Case("ComboMatchesEnum");
Check(VideoPatchPolicy.ComboItems.Length == Enum.GetValues<VideoPatchMode>().Length, "one combo item per mode");
Check(VideoPatchPolicy.ComboItems[(int)VideoPatchMode.Off] == "Off", "index 0 is Off");
Check(VideoPatchPolicy.ComboItems[(int)VideoPatchMode.All].Contains("session"), "All says it is session only");
}
private static void CharacterKeys()
{
Case("CharacterKeys");
Check(VideoPatchPolicy.CharacterKey("Aelrynth", "Some Guy") == "Aelrynth/Some Guy", "server/character");
Check(VideoPatchPolicy.CharacterKey("", "Some Guy") == "Some Guy", "no server");
Check(VideoPatchPolicy.CharacterKey("Aelrynth", "") == VideoPatchPolicy.DefaultCharacterKey, "no character = Default");
Check(VideoPatchPolicy.CharacterKey(null, null) == VideoPatchPolicy.DefaultCharacterKey, "nulls = Default");
Check(!VideoPatchPolicy.CharacterKey("A=B", "C").Contains('='), "no '=' in a key");
}
private static VideoPatchPolicy.FileModel RoundTripModel(VideoPatchPolicy.FileModel m) =>
VideoPatchPolicy.Parse(VideoPatchPolicy.Serialize(m));
private static void FileRoundTrip()
{
Case("FileRoundTrip");
var m = VideoPatchPolicy.Parse(null);
Check(m.FrameCapFps == VideoPatchPolicy.DefaultFrameCapFps, "missing file = default cap");
Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.Off, "missing file = off");
m.FrameCapFps = 10;
m.Set("Aelrynth/A", VideoPatchMode.World);
m.Set("Aelrynth/B", VideoPatchMode.Unfocused);
var back = RoundTripModel(m);
Check(back.FrameCapFps == 10, "cap round-trips");
Check(back.ModeFor("Aelrynth/A") == VideoPatchMode.World, "A round-trips");
Check(back.ModeFor("aelrynth/b") == VideoPatchMode.Unfocused, "B round-trips (case-insensitive)");
Check(back.ModeFor("Aelrynth/C") == VideoPatchMode.Off, "unknown character = off");
var twice = RoundTripModel(back);
Check(string.Join("\n", VideoPatchPolicy.Serialize(twice)) == string.Join("\n", VideoPatchPolicy.Serialize(back)), "serialize is stable");
Check(VideoPatchPolicy.Serialize(twice).Count(l => l.StartsWith("# RynthCore video patch")) == 1, "one header line");
}
private static void AllIsNeverSaved()
{
Case("AllIsNeverSaved");
var m = VideoPatchPolicy.Parse(null);
m.Set("X/Y", VideoPatchMode.World);
Check(!m.Set("X/Y", VideoPatchMode.All), "Set(all) refuses");
Check(m.ModeFor("X/Y") == VideoPatchMode.World, "Set(all) keeps the saved mode");
var hand = VideoPatchPolicy.Parse(new[] { "X/Z=all" });
Check(hand.ModeFor("X/Z") == VideoPatchMode.Off, "a hand-written 'all' loads as off (a start never hides AC's UI)");
}
private static void OffRemovesTheLine()
{
Case("OffRemovesTheLine");
var m = VideoPatchPolicy.Parse(null);
m.Set("X/Y", VideoPatchMode.World);
m.Set("X/Y", VideoPatchMode.Off);
Check(!VideoPatchPolicy.Serialize(m).Any(l => l.StartsWith("X/Y")), "off leaves no line");
}
private static void DefaultLineAndUnknownLines()
{
Case("DefaultLineAndUnknownLines");
var m = VideoPatchPolicy.Parse(new[] { "Default=unfocused", "SomethingNew=42", "# a note", "Aelrynth/A=world" });
Check(m.ModeFor("Aelrynth/Q") == VideoPatchMode.Unfocused, "Default applies to characters without a line");
Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.World, "own line wins over Default");
var lines = VideoPatchPolicy.Serialize(m);
Check(lines.Contains("SomethingNew=42"), "unknown key kept");
Check(lines.Contains("# a note"), "comment kept");
}
private static void BadFileValues()
{
Case("BadFileValues");
var m = VideoPatchPolicy.Parse(new[] { "FrameCapFps=abc", "Aelrynth/A=sideways", "=world", "" });
Check(m.FrameCapFps == VideoPatchPolicy.DefaultFrameCapFps, "bad cap keeps the default");
Check(m.ModeFor("Aelrynth/A") == VideoPatchMode.Off, "bad mode = off");
Check(VideoPatchPolicy.Parse(new[] { "FrameCapFps=1" }).FrameCapFps == VideoPatchPolicy.MinFrameCapFps, "cap 1 clamps to the minimum");
Check(VideoPatchPolicy.Parse(new[] { "FrameCapFps=0" }).FrameCapFps == 0, "cap 0 = none");
}
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the video patch's pure logic (2026-10-05):
src\RynthCore.Engine\D3D9\VideoPatchPolicy.cs, compiled in. What each mode skips (in and
out of the world, focused and not, with and without the ImGui layer), the frame cap,
the command words, and the video_patch.txt round-trip (per-character keys, "all" never
saved, unknown lines kept). No file I/O, 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>VideoPatchTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\D3D9\VideoPatchPolicy.cs" Link="Engine\VideoPatchPolicy.cs" />
</ItemGroup>
</Project>

View file

@ -312,7 +312,7 @@ def _compat_dir():
def parse_engine_patterns():
srcs = {}
# Compatibility/ holds nearly every hook; D3D9/AcUiPassHook.cs (RenderUI::RenderObjects)
# is the one function hook that lives with the render code.
# and D3D9/VideoPatch.cs (SmartBox::RenderNormalMode) live with the render code.
engine_dir = os.path.dirname(_compat_dir())
for f in glob.glob(os.path.join(_compat_dir(), "*.cs")) + glob.glob(os.path.join(engine_dir, "D3D9", "*.cs")):
with open(f, "r", encoding="utf-8") as fh: