Snapshot for release 2026.10.15.1 (internal 4b7e805)

This commit is contained in:
Tom Bohar 2026-10-15 09:27:14 -04:00
commit 8bb1c3aa23
71 changed files with 5546 additions and 837 deletions

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the toolbar's rows (src\RynthCore.Engine\UI\BarLayout.cs, compiled in):
icons per row = ceil(icons / rows) capped at the limit, the clamps (rows 1-6, limit 0 or
2-30), the grip menu's icons-per-row steps (no limit above 30), the Settings picker index
maps, and the barlayout= row of panel_state.txt (a missing or bad row gives 1 row, no limit).
No files, no ImGui. Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>BarLayoutTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\BarLayout.cs" Link="Engine\BarLayout.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,114 @@
using RynthCore.Engine.UI;
namespace BarLayoutTests;
// Offline tests for the toolbar's rows. 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 int Main()
{
PerRow();
RowCount();
Clamps();
StepMaxPerRow();
PickerIndexes();
ParseAndFormat();
Console.WriteLine();
Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)");
return _fails == 0 ? 0 : 1;
}
private static void PerRow()
{
Console.WriteLine("PerRow");
Eq(BarLayout.PerRow(12, 1, 0), 12, "one row, no limit: every icon on it (today's bar)");
Eq(BarLayout.PerRow(12, 2, 0), 6, "12 icons, 2 rows");
Eq(BarLayout.PerRow(13, 2, 0), 7, "13 icons, 2 rows: ceil");
Eq(BarLayout.PerRow(13, 3, 0), 5, "13 icons, 3 rows: ceil(13/3)");
Eq(BarLayout.PerRow(12, 1, 5), 5, "one row capped at 5: the cap adds rows");
Eq(BarLayout.RowCount(12, BarLayout.PerRow(12, 1, 5)), 3, "12 icons capped at 5 take 3 rows");
Eq(BarLayout.PerRow(12, 3, 10), 4, "a cap above ceil(icons/rows) changes nothing");
Eq(BarLayout.PerRow(3, 6, 0), 1, "more rows than icons: one a row");
Eq(BarLayout.PerRow(0, 2, 0), 1, "no icons: still at least 1 (no divide by zero)");
Eq(BarLayout.PerRow(12, 0, 0), 12, "rows 0 reads as 1");
Eq(BarLayout.PerRow(12, 99, 0), 2, "rows 99 reads as 6");
Eq(BarLayout.PerRow(12, 1, 1), 2, "a limit of 1 reads as 2");
}
private static void RowCount()
{
Console.WriteLine("RowCount");
Eq(BarLayout.RowCount(0, 1), 1, "an empty bar is one row");
Eq(BarLayout.RowCount(12, 6), 2, "12 by 6");
Eq(BarLayout.RowCount(13, 6), 3, "13 by 6: a short last row");
Eq(BarLayout.RowCount(5, 0), 5, "perRow 0 reads as 1");
}
private static void Clamps()
{
Console.WriteLine("Clamps");
Eq(BarLayout.ClampRows(0), 1, "rows below 1");
Eq(BarLayout.ClampRows(7), 6, "rows above 6");
Eq(BarLayout.ClampRows(3), 3, "rows in range");
Eq(BarLayout.ClampMaxPerRow(0), 0, "0 is no limit");
Eq(BarLayout.ClampMaxPerRow(-5), 0, "negative is no limit");
Eq(BarLayout.ClampMaxPerRow(1), 2, "1 becomes 2");
Eq(BarLayout.ClampMaxPerRow(31), 30, "above 30 becomes 30");
Eq(BarLayout.ClampMaxPerRow(17), 17, "in range");
}
private static void StepMaxPerRow()
{
Console.WriteLine("StepMaxPerRow");
Eq(BarLayout.StepMaxPerRow(0, 1, 12), 0, "+ at no limit stays no limit");
Eq(BarLayout.StepMaxPerRow(0, -1, 12), 11, "- from no limit caps one below the shown row");
Eq(BarLayout.StepMaxPerRow(0, -1, 2), 2, "- from no limit never below 2");
Eq(BarLayout.StepMaxPerRow(0, -1, 50), 30, "- from no limit never above 30");
Eq(BarLayout.StepMaxPerRow(30, 1, 12), 0, "+ at 30 is no limit");
Eq(BarLayout.StepMaxPerRow(2, -1, 12), 2, "- stops at 2");
Eq(BarLayout.StepMaxPerRow(5, 1, 12), 6, "+ one");
Eq(BarLayout.StepMaxPerRow(5, -1, 12), 4, "- one");
Eq(BarLayout.StepMaxPerRow(5, 0, 12), 5, "no step");
}
private static void PickerIndexes()
{
Console.WriteLine("PickerIndexes");
Eq(BarLayout.RowNames.Length, 6, "rows picker: 1..6");
Eq(BarLayout.RowNames[0], "1", "rows picker starts at 1");
Eq(BarLayout.MaxPerRowNames.Length, 30, "limit picker: no limit + 2..30");
Eq(BarLayout.MaxPerRowNames[0], "No limit", "limit picker starts with no limit");
Eq(BarLayout.MaxPerRowNames[^1], "30", "limit picker ends at 30");
for (int max = 0; max <= 30; max++)
{
if (max == 1) continue; // not a value (clamps to 2)
int index = BarLayout.MaxPerRowToIndex(max);
Eq(BarLayout.IndexToMaxPerRow(index), max, $"limit {max} round-trips through the picker");
Eq(BarLayout.MaxPerRowNames[index], BarLayout.DescribeMaxPerRow(max), $"limit {max}'s label");
}
}
private static void ParseAndFormat()
{
Console.WriteLine("ParseAndFormat");
Check(BarLayout.TryParse("2,8", out int r, out int m) && r == 2 && m == 8, "reads 2,8");
Eq(BarLayout.Format(2, 8), "2,8", "writes 2,8");
Check(BarLayout.TryParse(BarLayout.Format(6, 0), out r, out m) && r == 6 && m == 0, "round trip 6, no limit");
Check(BarLayout.TryParse(" 3 , 1 ", out r, out m) && r == 3 && m == 2, "spaces; a limit of 1 clamps to 2");
Check(BarLayout.TryParse("9,99", out r, out m) && r == 6 && m == 30, "out of range clamps");
Check(!BarLayout.TryParse(null, out r, out m) && r == 1 && m == 0, "no row (an old file): defaults");
Check(!BarLayout.TryParse("", out r, out m) && r == 1 && m == 0, "empty: defaults");
Check(!BarLayout.TryParse("2", out r, out m) && r == 1 && m == 0, "one value: defaults");
Check(!BarLayout.TryParse("two,8", out r, out m) && r == 1 && m == 0, "not a number: defaults");
Check(!BarLayout.TryParse("2,8,1", out r, out m) && r == 1 && m == 0, "three values: defaults");
}
}

View file

@ -0,0 +1,139 @@
using System.IO.Compression;
using RynthCore.App.Avalonia;
// World map packs (RynthUpdater.MapPacks.cs): the optional HD / Ultra downloads. Part of the same program as
// the NavData tests (same signed feed, same local HTTP server).
internal static partial class Program
{
private static byte[] Rand(int n, int seed) { var b = new byte[n]; new Random(seed).NextBytes(b); return b; }
/// <summary>A feed entry for a pack whose bytes are served under the feed's folder.</summary>
private static Dictionary<string, object> PackEntry(string tag, string key, string name, string file, byte[] data, string? sha = null, long? size = null)
{
lock (Served) Served[$"{tag}/packs/{file}"] = data;
return new Dictionary<string, object>
{
["key"] = key, ["name"] = name, ["file"] = file, ["url"] = _base + $"{tag}/packs/{file}", ["size"] = size ?? data.Length,
["sha256"] = sha ?? Sha(data), ["release"] = 2026100201, ["description"] = name + " test map",
};
}
private static async Task NoMapPacksInFeed()
{
var (upd, nav, plugin, _) = SetupInFeedFolder("nopack", null, withNavData: false);
var c = await upd.CheckAsync(new[] { plugin });
Check(c.Manifest.MapPacks.Count == 0 && c.MapPacks.Count == 0, "a feed without mappacks (every feed so far) still parses, nothing to offer");
}
private static async Task MapPacksListedInstalledAndRemoved()
{
byte[] hd = Rand(300_000, 1), ul = Rand(500_000, 2);
var packs = new object[] { PackEntry("packs", "hd", "HD", "worldmap-hd.rmap", hd), PackEntry("packs", "ultra", "Ultra", "worldmap-ultra.rmap", ul) };
var (upd, nav, plugin, _) = SetupInFeedFolder("packs", null, withNavData: false, mapPacks: packs);
var c = await upd.CheckAsync(new[] { plugin });
Check(c.MapPacks.Count == 2 && c.MapPacks.All(p => p.State == RynthUpdater.MapPackState.NotInstalled), "two packs offered, neither installed");
string dir = upd.MapPacksDir;
Check(dir == Path.Combine(Path.GetDirectoryName(nav)!, "MapPacks"), "packs live beside the NavData folder, not inside it");
string line = await upd.InstallMapPackAsync(c.MapPacks[0].Entry);
string file = Path.Combine(dir, "worldmap-hd.rmap");
Check(File.Exists(file) && File.ReadAllBytes(file).AsSpan().SequenceEqual(hd), "the HD pack is installed, byte for byte");
Check(!File.Exists(file + ".part"), "no partial file is left");
Check(line.Contains("HD") && line.Contains("installed"), "the activity line says what happened");
var again = await upd.CheckAsync(new[] { plugin });
Check(again.MapPacks[0].State == RynthUpdater.MapPackState.UpToDate && again.MapPacks[1].State == RynthUpdater.MapPackState.NotInstalled, "HD is current, Ultra still not installed");
Check(upd.RemoveMapPack(again.MapPacks[0].Entry), "removing reports it was there");
Check(!File.Exists(file) && !File.Exists(file + ".sha256"), "the pack and its marker are gone");
Check(!upd.RemoveMapPack(again.MapPacks[0].Entry), "removing again reports it was not there");
// A file put there by hand, the size the feed says and no marker, counts as installed.
Directory.CreateDirectory(dir);
File.WriteAllBytes(Path.Combine(dir, "worldmap-ultra.rmap"), ul);
var hand = await upd.CheckAsync(new[] { plugin });
Check(hand.MapPacks[1].State == RynthUpdater.MapPackState.UpToDate, "a hand-copied pack of the right size counts as installed");
File.WriteAllBytes(Path.Combine(dir, "worldmap-ultra.rmap"), new byte[10]);
var wrong = await upd.CheckAsync(new[] { plugin });
Check(wrong.MapPacks[1].State == RynthUpdater.MapPackState.NeedsUpdate, "one of the wrong size is an update");
}
private static async Task MapPackNewBuildIsAnUpdate()
{
byte[] v1 = Rand(200_000, 3), v2 = Rand(210_000, 4);
var (upd, nav, plugin, _) = SetupInFeedFolder("packupd", null, withNavData: false, mapPacks: new object[] { PackEntry("packupd", "hd", "HD", "worldmap-hd.rmap", v1) });
var c = await upd.CheckAsync(new[] { plugin });
await upd.InstallMapPackAsync(c.MapPacks[0].Entry);
// The feed now carries a new build of the same pack.
var (upd2, _, plugin2, _) = SetupInFeedFolder("packupd", null, withNavData: false, mapPacks: new object[] { PackEntry("packupd", "hd", "HD", "worldmap-hd.rmap", v2) });
var c2 = await upd2.CheckAsync(new[] { plugin2 });
Check(c2.MapPacks[0].State == RynthUpdater.MapPackState.NeedsUpdate, "a new build of an installed pack is an update");
await upd2.InstallMapPackAsync(c2.MapPacks[0].Entry);
Check(File.ReadAllBytes(Path.Combine(upd2.MapPacksDir, "worldmap-hd.rmap")).AsSpan().SequenceEqual(v2), "the update replaced the file");
var c3 = await upd2.CheckAsync(new[] { plugin2 });
Check(c3.MapPacks[0].State == RynthUpdater.MapPackState.UpToDate, "and it is current afterwards");
}
private static async Task MapPackBadDownloadChangesNothing()
{
byte[] good = Rand(150_000, 5), served = Rand(150_000, 6);
// The feed says the SHA-256 of one file; another is served.
var entry = PackEntry("packbad", "hd", "HD", "worldmap-hd.rmap", served, sha: Sha(good));
var (upd, nav, plugin, _) = SetupInFeedFolder("packbad", null, withNavData: false, mapPacks: new object[] { entry });
var c = await upd.CheckAsync(new[] { plugin });
string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap");
bool threw = false;
try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry); } catch (Exception) { threw = true; }
Check(threw, "a download that does not match the feed's SHA-256 is refused");
Check(!File.Exists(file) && !File.Exists(file + ".part") && !File.Exists(file + ".sha256"), "nothing was installed and no partial file is left");
// And an installed pack stays as it was when its update is refused.
Directory.CreateDirectory(upd.MapPacksDir);
File.WriteAllBytes(file, new byte[] { 1, 2, 3 });
threw = false;
try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry); } catch (Exception) { threw = true; }
Check(threw && File.ReadAllBytes(file).SequenceEqual(new byte[] { 1, 2, 3 }), "a refused update leaves the installed pack as it was");
}
private static async Task MapPackBadEntriesAreSkipped()
{
byte[] data = Rand(1000, 7);
var good = PackEntry("packskip", "hd", "HD", "worldmap-hd.rmap", data);
var traversal = PackEntry("packskip", "evil", "Evil", "../worldmap-evil.rmap", data);
var wrongKind = PackEntry("packskip", "dll", "Dll", "worldmap-x.dll", data);
var badKey = PackEntry("packskip", "BAD KEY!", "Bad", "worldmap-bad.rmap", data);
var shortSha = PackEntry("packskip", "short", "Short", "worldmap-short.rmap", data, sha: "abc");
var duplicate = PackEntry("packskip", "hd", "HD again", "worldmap-hd.rmap", data);
var huge = PackEntry("packskip", "huge", "Huge", "worldmap-huge.rmap", data, size: 9L << 40);
var (upd, nav, plugin, _) = SetupInFeedFolder("packskip", null, withNavData: false, mapPacks: new object[] { traversal, wrongKind, badKey, shortSha, good, duplicate, huge });
var c = await upd.CheckAsync(new[] { plugin });
Check(c.MapPacks.Count == 1 && c.MapPacks[0].Entry.Key == "hd", "entries with a path in the file name, a wrong extension, a bad key, a short hash, a repeated key or an absurd size are skipped; the good one stays");
}
private static async Task MapPackCancelLeavesNothing()
{
byte[] data = Rand(400_000, 8);
var (upd, nav, plugin, _) = SetupInFeedFolder("packcancel", null, withNavData: false, mapPacks: new object[] { PackEntry("packcancel", "hd", "HD", "worldmap-hd.rmap", data) });
var c = await upd.CheckAsync(new[] { plugin });
using var cts = new CancellationTokenSource();
cts.Cancel();
bool cancelled = false;
try { await upd.InstallMapPackAsync(c.MapPacks[0].Entry, null, cts.Token); } catch (OperationCanceledException) { cancelled = true; }
string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap");
Check(cancelled, "cancelling stops the install");
Check(!File.Exists(file) && !File.Exists(file + ".part"), "and leaves neither the pack nor a partial file");
}
private static async Task NavDataUpdateLeavesMapPacksAlone()
{
byte[] hd = Rand(120_000, 9);
var (upd, nav, plugin, _) = SetupInFeedFolder("packnav", Zip(TileSet), mapPacks: new object[] { PackEntry("packnav", "hd", "HD", "worldmap-hd.rmap", hd) });
OldNavData(nav);
var c = await upd.CheckAsync(new[] { plugin });
await upd.InstallMapPackAsync(c.MapPacks[0].Entry);
Check(c.NavDataUpdateAvailable, "the tiles need an update");
await upd.UpdateNavDataAsync(c);
string file = Path.Combine(upd.MapPacksDir, "worldmap-hd.rmap");
Check(File.Exists(file) && File.ReadAllBytes(file).AsSpan().SequenceEqual(hd) && File.Exists(file + ".sha256"), "updating the tiles swaps the NavData folder but the map pack beside it is untouched");
Check(!Directory.Exists(Path.Combine(nav, "MapPacks")), "and no MapPacks folder appears inside NavData");
}
}

View file

@ -18,6 +18,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.cs" Link="Linked\RynthUpdater.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.NavData.cs" Link="Linked\RynthUpdater.NavData.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.MapPacks.cs" Link="Linked\RynthUpdater.MapPacks.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />

View file

@ -8,7 +8,7 @@ using RynthCore.App.Avalonia;
// Tests for the launcher's RynthNav tile update. A throwaway signing key signs a feed served by
// a local HttpListener; the updater installs the archive into a temp NavData folder.
internal static class Program
internal static partial class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
@ -46,6 +46,13 @@ internal static class Program
await Run(nameof(CancelledDownloadLeavesNothing), CancelledDownloadLeavesNothing);
await Run(nameof(CancelledUnpackLeavesTilesAsTheyWere), CancelledUnpackLeavesTilesAsTheyWere);
await Run(nameof(TamperedArchiveRefusedWithProgress), TamperedArchiveRefusedWithProgress);
await Run(nameof(NoMapPacksInFeed), NoMapPacksInFeed);
await Run(nameof(MapPacksListedInstalledAndRemoved), MapPacksListedInstalledAndRemoved);
await Run(nameof(MapPackNewBuildIsAnUpdate), MapPackNewBuildIsAnUpdate);
await Run(nameof(MapPackBadDownloadChangesNothing), MapPackBadDownloadChangesNothing);
await Run(nameof(MapPackBadEntriesAreSkipped), MapPackBadEntriesAreSkipped);
await Run(nameof(MapPackCancelLeavesNothing), MapPackCancelLeavesNothing);
await Run(nameof(NavDataUpdateLeavesMapPacksAlone), NavDataUpdateLeavesMapPacksAlone);
}
finally
{
@ -133,11 +140,13 @@ internal static class Program
["locations.json"] = "{\"locations\":[]}",
["navgraph.bin"] = "route graph",
["townnet.json"] = "{\"version\":1}",
["worldmap.rmap"] = "world map",
["worldmap.vec"] = "world map vectors",
};
// The feed's URLs must sit in the feed's folder: serve each test's archive under it.
private static (RynthUpdater upd, string nav, string plugin, string state) SetupInFeedFolder(string tag, byte[]? zip, string id = "0123456789abcdef0123456789abcdef",
int? files = null, bool signNavData = true, bool withNavData = true, string? overrideSha = null)
int? files = null, bool signNavData = true, bool withNavData = true, string? overrideSha = null, object[]? mapPacks = null)
{
string zipName = $"{tag}/releases/1/RynthNav-NavData.zip";
string dir = Path.Combine(_root, tag);
@ -159,6 +168,7 @@ internal static class Program
["id"] = id, ["release"] = 2026100201, ["url"] = _base + zipName, ["size"] = zip.Length,
["sha256"] = overrideSha ?? Sha(zip), ["files"] = files ?? TileSet.Count, ["bytes"] = 1000,
};
if (mapPacks != null) manifest["mappacks"] = mapPacks;
if (withNavData && nd != null && signNavData) manifest["navdata"] = nd;
byte[] signedPayload = JsonSerializer.SerializeToUtf8Bytes(manifest);
if (withNavData && nd != null && !signNavData) manifest["navdata"] = nd; // served, but not what was signed
@ -210,6 +220,8 @@ internal static class Program
Check(line.Contains($"{TileSet.Count} files"), "reports what it installed: " + line);
Check(File.ReadAllText(Path.Combine(nav, "navgraph.bin")) == "route graph", "the route graph ships with the tiles");
Check(File.ReadAllText(Path.Combine(nav, "townnet.json")) == "{\"version\":1}", "the Town Network ships with the tiles");
Check(File.ReadAllText(Path.Combine(nav, "worldmap.rmap")) == "world map", "the World Map's tiles ship with the tiles");
Check(File.ReadAllText(Path.Combine(nav, "worldmap.vec")) == "world map vectors", "the World Map's buildings and roads ship with the tiles");
Check(File.ReadAllText(Path.Combine(nav, "nav_A9B4.tile")) == "tile A9B4 v2", "the tile is the new one");
Check(File.Exists(Path.Combine(nav, "nav_AAB4.tile")), "new tiles are there");
Check(!File.Exists(Path.Combine(nav, "nav_0101.tile")), "a stale tile from the old set is gone (old and new don't link)");

View file

@ -0,0 +1,163 @@
using System.IO.Compression;
using RynthCore.Engine.ImGuiBackend;
namespace WorldMapTilesTests
{
/// <summary>worldmap.rmap version 2 (DXT1 tiles, as RynthNav.Baker --map-world writes it) and switching between files.</summary>
internal static class DxtTileTests
{
private static bool WaitOpen(string path)
{
WorldMapTiles.Open(path);
for (int i = 0; i < 300 && !WorldMapTiles.IsOpen; i++) Thread.Sleep(10);
return WorldMapTiles.IsOpen;
}
private static bool Load(int level, int col, int row, out IntPtr tex)
{
tex = IntPtr.Zero;
for (int i = 0; i < 400; i++)
{
WorldMapTiles.BeginFrame(new IntPtr(1));
if (WorldMapTiles.TryGet(level, col, row, out tex)) return true;
Thread.Sleep(2);
}
return false;
}
// A tile's blocks: its number in the first two bytes, the rest filler.
private static byte[] Blocks(int id)
{
var b = new byte[256 * 256 / 2];
b[0] = (byte)id; b[1] = (byte)(id >> 8);
for (int i = 8; i < b.Length; i += 8) b[i] = (byte)(id * 7);
return b;
}
private static void WriteV2(string path, (int Cols, int Rows)[] levels)
{
var blobs = new List<byte[]>();
var first = new int[levels.Length];
for (int l = 0; l < levels.Length; l++)
{
first[l] = blobs.Count;
for (int i = 0; i < levels[l].Cols * levels[l].Rows; i++)
{
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(Blocks(first[l] + i));
blobs.Add(ms.ToArray());
}
}
long header = 4 + 6 * 4 + levels.Length * 20 + 4 + blobs.Count * 12L;
using var fs = new FileStream(path, FileMode.Create);
using var w = new BinaryWriter(fs);
w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' });
w.Write(2u); w.Write(256u); w.Write((uint)levels.Length); w.Write(8u); // 8 px per cell: HD
w.Write((uint)(levels[0].Cols * 256 / 8)); w.Write((uint)(levels[0].Rows * 256 / 8));
for (int l = 0; l < levels.Length; l++)
{ w.Write((uint)(levels[l].Cols * 256)); w.Write((uint)(levels[l].Rows * 256)); w.Write((uint)levels[l].Cols); w.Write((uint)levels[l].Rows); w.Write((uint)first[l]); }
w.Write((uint)blobs.Count);
long off = header;
for (int i = 0; i < blobs.Count; i++)
{
if (i == 5) { w.Write(0UL); w.Write(0u); continue; } // tile 5: not baked (length 0)
w.Write((ulong)off); w.Write((uint)blobs[i].Length); off += blobs[i].Length;
}
for (int i = 0; i < blobs.Count; i++) if (i != 5) w.Write(blobs[i]);
}
public static void Run(Action<bool, string> check, string dir)
{
WorldMapTiles.Shutdown();
string v2 = Path.Combine(dir, "dxt.rmap");
// 16 x 16 tiles at level 0 (256, more than the 192 cap), 8 x 8, then 4 x 4.
WriteV2(v2, new[] { (16, 16), (8, 8), (4, 4) });
check(WaitOpen(v2), "dxt: the version 2 file opens");
check(WorldMapTiles.IsDxt, "dxt: it is recognised as DXT1");
check(WorldMapTiles.PixelsPerCell == 8 && WorldMapTiles.Levels.Count == 3, "dxt: 8 px per cell, three levels");
// A tile reaches the device as DXT1 blocks, untouched: its own number is in the first block.
int before = DX9Backend.DxtCreated;
bool got = Load(1, 3, 2, out IntPtr t);
int id = 256 + 2 * 8 + 3;
check(got && DX9Backend.DxtCreated == before + 1, "dxt: a tile is made with the DXT1 upload (not RGBA)");
check(got && DX9Backend.Live.TryGetValue(t, out var px) && px.R == (byte)id && px.G == (byte)(id >> 8), "dxt: its blocks are that tile's, as written");
// A tile the baker didn't make (length 0) never loads and never throws.
check(!Load(0, 5, 0, out _) || true, "dxt: an unbaked tile is asked for without trouble");
check(!WorldMapTiles.Peek(0, 5, 0, out _), "dxt: an unbaked tile has no texture");
// The cap is 192 textures, not 96.
Check(WorldMapTiles.Peek(1, 3, 2, out _), check, "dxt: the first tile is still there");
int loaded = 0;
for (int i = 6; i < 6 + 230; i++) if (Load(0, i % 16, i / 16, out _)) loaded++;
for (int i = 0; i < 4; i++) WorldMapTiles.BeginFrame(new IntPtr(1));
check(loaded == 230, $"dxt: 230 tiles loaded in turn ({loaded})");
check(WorldMapTiles.LiveTextures <= 192 && DX9Backend.Live.Count <= 192, $"dxt: never over 192 textures (engine {WorldMapTiles.LiveTextures}, backend {DX9Backend.Live.Count})");
check(WorldMapTiles.LiveTextures > 150, $"dxt: and more than the RGBA cap of 96 are kept ({WorldMapTiles.LiveTextures})");
check(DX9Backend.Created - DX9Backend.Released == DX9Backend.Live.Count, "dxt: every texture that left the table was released");
// Switching files: the old textures go at the start of the next frame, then the new file opens.
string v1 = Path.Combine(dir, "flat.rmap");
WriteFlat(v1);
WorldMapTiles.Switch(v1);
for (int i = 0; i < 400 && !(WorldMapTiles.IsOpen && WorldMapTiles.CurrentPath == v1); i++) { WorldMapTiles.BeginFrame(new IntPtr(1)); Thread.Sleep(5); }
check(WorldMapTiles.CurrentPath == v1 && WorldMapTiles.IsOpen, "switch: the other file is open");
check(!WorldMapTiles.IsDxt && WorldMapTiles.PixelsPerCell == 2, "switch: and it is the flat, 2 px per cell one");
check(DX9Backend.Live.Count == 0 && WorldMapTiles.LiveTextures == 0, "switch: the old file's textures were all released");
check(Load(0, 0, 0, out IntPtr ft) && DX9Backend.Live[ft].A == 255, "switch: a tile of the new file loads (RGBA)");
// Switching to the file already open does nothing.
int made = DX9Backend.Created;
WorldMapTiles.Switch(v1);
for (int i = 0; i < 5; i++) WorldMapTiles.BeginFrame(new IntPtr(1));
check(DX9Backend.Created == made && WorldMapTiles.IsOpen, "switch: to the same file is a no-op");
WorldMapTiles.Shutdown();
}
private static void Check(bool ok, Action<bool, string> check, string what) => check(ok, what);
/// <summary>A real version 2 file from the baker (a partial bake is fine: tiles it didn't make have no texture).</summary>
public static void RealDxt(string path, Action<bool, string> check)
{
System.Console.WriteLine("real DXT1 file: " + path);
WorldMapTiles.Shutdown();
check(WaitOpen(path), "real dxt: opens (" + WorldMapTiles.Status + ")");
if (!WorldMapTiles.IsOpen) return;
var lv = WorldMapTiles.Levels;
check(WorldMapTiles.IsDxt && WorldMapTiles.PixelsPerCell >= 2 && lv.Count >= 5, $"real dxt: DXT1, {WorldMapTiles.PixelsPerCell} px per cell, {lv.Count} levels");
check(lv[0].Cols == lv[0].Rows && lv[^1].Cols == 1, "real dxt: square, down to one tile");
check(Load(lv.Count - 1, 0, 0, out IntPtr top) && DX9Backend.Live.ContainsKey(top), "real dxt: the whole-world tile loads");
// Holtburg (42.1N, 33.6E: cell 1355.5, 1440.5) at the sharpest level, and a few levels up.
int ppc = WorldMapTiles.PixelsPerCell;
int col = (int)(1355.5 * ppc / 256), row = (int)((2048 - 1440.5) * ppc / 256);
check(lv[0].Width == 2048 * ppc && lv[0].Cols == 2048 * ppc / 256, $"real dxt: level 0 is {lv[0].Width} px = 2048 cells x {ppc}");
if (path.EndsWith("worldmap-p32.rmap", StringComparison.OrdinalIgnoreCase) || lv[0].Cols * lv[0].Rows > 1000)
{
bool all = true;
for (int l = 0; l < Math.Min(lv.Count, 4); l++)
if (!Load(l, col >> l, row >> l, out _)) all = false;
check(all, $"real dxt: the Holtburg tile loads at levels 0-3 (level 0 col {col}, row {row})");
}
WorldMapTiles.Shutdown();
}
// A one-level, one-tile version 1 (RGB) file at 2 px per cell.
private static void WriteFlat(string path)
{
var raw = new byte[256 * 256 * 3];
for (int i = 0; i < raw.Length; i += 3) { raw[i] = 20; raw[i + 1] = 60; raw[i + 2] = 120; }
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(raw);
byte[] blob = ms.ToArray();
long header = 4 + 6 * 4 + 20 + 4 + 12;
using var fs = new FileStream(path, FileMode.Create);
using var w = new BinaryWriter(fs);
w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' });
w.Write(1u); w.Write(256u); w.Write(1u); w.Write(2u); w.Write(128u); w.Write(128u);
w.Write(256u); w.Write(256u); w.Write(1u); w.Write(1u); w.Write(0u);
w.Write(1u); w.Write((ulong)header); w.Write((uint)blob.Length);
w.Write(blob);
}
}
}

View file

@ -0,0 +1,210 @@
using System.IO.Compression;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.ImGuiBackend
{
/// <summary>Stands in for the engine's D3D9 backend: a "texture" is a counter, remembering its first pixel.</summary>
internal static class DX9Backend
{
public static readonly Dictionary<IntPtr, (byte R, byte G, byte B, byte A)> Live = new();
private static long _next = 0x1000;
public static int Created, Released;
public static IntPtr CreateTextureRgba(IntPtr device, int width, int height, ReadOnlySpan<byte> rgba)
{
if (width != 256 || height != 256 || rgba.Length != 256 * 256 * 4) return IntPtr.Zero;
var p = new IntPtr(_next += 0x10);
Live[p] = (rgba[0], rgba[1], rgba[2], rgba[3]);
Created++;
return p;
}
public static int DxtCreated;
/// <summary>A DXT1 tile: the first two bytes (the first block's colour 0) say which tile it is.</summary>
public static IntPtr CreateTextureDxt1(IntPtr device, int width, int height, ReadOnlySpan<byte> blocks)
{
if (width != 256 || height != 256 || blocks.Length != 256 * 256 / 2) return IntPtr.Zero;
var p = new IntPtr(_next += 0x10);
Live[p] = (blocks[0], blocks[1], 0, 255);
Created++; DxtCreated++;
return p;
}
public static void ReleaseTexture(IntPtr tex) { if (Live.Remove(tex)) Released++; }
}
}
namespace WorldMapTilesTests
{
/// <summary>The map file's layout (RynthNav.Baker WorldMapRender.WriteRmap), written here independently.</summary>
internal static class Program
{
private static int _checks, _failed;
private static readonly IntPtr Dev = new(1);
private static int Main(string[] args)
{
string dir = Path.Combine(Path.GetTempPath(), "wmtiles-" + Environment.ProcessId);
Directory.CreateDirectory(dir);
try
{
ProjectionTests.Run(Check);
Synthetic(Path.Combine(dir, "synthetic.rmap"));
VectorTests.Run(Check, dir, args.Length > 1 ? args[1] : null);
DxtTileTests.Run(Check, dir);
if (args.Length > 0) Real(args[0]);
if (args.Length > 2) DxtTileTests.RealDxt(args[2], Check);
}
finally { try { Directory.Delete(dir, true); } catch { } }
Console.WriteLine(_failed == 0 ? $"OK: {_checks} checks" : $"FAILED: {_failed} of {_checks} checks");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (!ok) { _failed++; Console.WriteLine("FAIL: " + what); }
}
// A tile's colour from its level and position, so a read tile can be told from any other.
private static (byte R, byte G, byte B) Colour(int level, int col, int row) =>
((byte)(40 + level * 60), (byte)(10 + col * 17), (byte)(10 + row * 17));
private static void WriteSynthetic(string path, (int Cols, int Rows)[] levels)
{
var blobs = new List<byte[]>();
var first = new int[levels.Length];
for (int l = 0; l < levels.Length; l++)
{
first[l] = blobs.Count;
for (int r = 0; r < levels[l].Rows; r++)
for (int c = 0; c < levels[l].Cols; c++)
{
var (cr, cg, cb) = Colour(l, c, r);
var raw = new byte[256 * 256 * 3];
for (int i = 0; i < raw.Length; i += 3) { raw[i] = cr; raw[i + 1] = cg; raw[i + 2] = cb; }
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(raw);
blobs.Add(ms.ToArray());
}
}
long header = 4 + 6 * 4 + levels.Length * 20 + 4 + blobs.Count * 12L;
using var fs = new FileStream(path, FileMode.Create);
using var w = new BinaryWriter(fs);
w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' });
w.Write(1u); w.Write(256u); w.Write((uint)levels.Length); w.Write(2u);
w.Write((uint)(levels[0].Cols * 256 / 2)); w.Write((uint)(levels[0].Rows * 256 / 2));
for (int l = 0; l < levels.Length; l++)
{ w.Write((uint)(levels[l].Cols * 256)); w.Write((uint)(levels[l].Rows * 256)); w.Write((uint)levels[l].Cols); w.Write((uint)levels[l].Rows); w.Write((uint)first[l]); }
w.Write((uint)blobs.Count);
long off = header;
foreach (byte[] b in blobs) { w.Write((ulong)off); w.Write((uint)b.Length); off += b.Length; }
foreach (byte[] b in blobs) w.Write(b);
}
private static bool WaitOpen(string path)
{
WorldMapTiles.Open(path);
for (int i = 0; i < 300 && !WorldMapTiles.IsOpen; i++) Thread.Sleep(10);
return WorldMapTiles.IsOpen;
}
private static void WaitStatus()
{
for (int i = 0; i < 300 && (WorldMapTiles.Status.Length == 0 || WorldMapTiles.Status == "Loading the map..."); i++) Thread.Sleep(10);
}
/// <summary>Asks for a tile each frame, as a face does, until it's there or the time is up.</summary>
private static bool Load(int level, int col, int row, out IntPtr tex)
{
tex = IntPtr.Zero;
for (int i = 0; i < 400; i++)
{
WorldMapTiles.BeginFrame(Dev);
if (WorldMapTiles.TryGet(level, col, row, out tex)) return true;
Thread.Sleep(2);
}
return false;
}
private static void Synthetic(string path)
{
// 12x12 tiles at level 0 (144, more than the 96-texture cap), 6x6, then 3x3.
WriteSynthetic(path, new[] { (12, 12), (6, 6), (3, 3) });
Check(WaitOpen(path), "the file opens");
Check(WorldMapTiles.Levels.Count == 3, "three levels");
Check(WorldMapTiles.Levels.Count == 3 && WorldMapTiles.Levels[0].Cols == 12 && WorldMapTiles.Levels[1].First == 144 && WorldMapTiles.Levels[2].First == 144 + 36, "level table");
Check(WorldMapTiles.PixelsPerCell == 2 && WorldMapTiles.CellsWide == 1536 && WorldMapTiles.CellsHigh == 1536, "pixels per cell and size in cells");
// A tile arrives with its own pixels, and Peek sees it only once loaded.
Check(!WorldMapTiles.Peek(1, 4, 5, out _), "peek: not loaded yet");
bool got = Load(1, 4, 5, out IntPtr t);
Check(got, "a tile loads");
var (er, eg, eb) = Colour(1, 4, 5);
Check(got && DX9Backend.Live.TryGetValue(t, out var px) && px.R == er && px.G == eg && px.B == eb && px.A == 255, "its pixels are that tile's, opaque");
Check(WorldMapTiles.Peek(1, 4, 5, out IntPtr again) && again == t, "peek finds it");
Check(!WorldMapTiles.TryGet(1, 6, 0, out _) && !WorldMapTiles.TryGet(1, 0, 6, out _) && !WorldMapTiles.TryGet(3, 0, 0, out _) && !WorldMapTiles.TryGet(-1, 0, 0, out _), "out of range: nothing");
// Tiles by column and row: the colours say which one came back.
Check(Load(0, 0, 0, out IntPtr a) && Load(0, 11, 11, out IntPtr b) && a != b
&& DX9Backend.Live[a].G == Colour(0, 0, 0).G && DX9Backend.Live[b].G == Colour(0, 11, 11).G && DX9Backend.Live[b].B == Colour(0, 11, 11).B, "tiles by column and row");
// The cap: 120 tiles of level 0, each loaded once and left; the table never holds more than 96 and the oldest go.
Check(Load(2, 0, 0, out IntPtr topFirst), "the first tile of the top level loads");
int loaded = 0;
for (int i = 0; i < 120; i++) if (Load(0, i % 12, i / 12, out _)) loaded++;
for (int i = 0; i < 4; i++) WorldMapTiles.BeginFrame(Dev);
Check(loaded == 120, "120 tiles loaded in turn (" + loaded + ")");
Check(WorldMapTiles.LiveTextures <= 96 && DX9Backend.Live.Count <= 96, $"never over 96 textures (engine {WorldMapTiles.LiveTextures}, backend {DX9Backend.Live.Count})");
Check(DX9Backend.Created - DX9Backend.Released == DX9Backend.Live.Count && WorldMapTiles.LiveTextures == DX9Backend.Live.Count, "every texture that left the table was released");
Check(!WorldMapTiles.Peek(0, 0, 0, out _), "the oldest was evicted");
Check(WorldMapTiles.Peek(0, 119 % 12, 119 / 12, out _), "the newest is kept");
Check(WorldMapTiles.Peek(2, 0, 0, out IntPtr topAgain) && topAgain == topFirst, "the top level's first tile is never evicted");
// Shutdown: nothing left alive, and it can open again.
WorldMapTiles.Shutdown();
Check(DX9Backend.Live.Count == 0 && WorldMapTiles.LiveTextures == 0, "shutdown released every texture");
Check(!WorldMapTiles.IsOpen && WorldMapTiles.Levels.Count == 0, "shutdown closed the file");
Check(WaitOpen(path) && Load(1, 0, 0, out _), "it opens again after shutdown");
WorldMapTiles.Shutdown();
// A file that isn't a map, and a missing one: a status, no throw.
string dir = Path.GetDirectoryName(path)!;
string junk = Path.Combine(dir, "junk.rmap");
File.WriteAllBytes(junk, new byte[64]);
WorldMapTiles.Open(junk);
WaitStatus();
Check(!WorldMapTiles.IsOpen && WorldMapTiles.Status.Contains("didn't load"), "a bad file says so: " + WorldMapTiles.Status);
WorldMapTiles.Shutdown();
WorldMapTiles.Open(Path.Combine(dir, "nothere.rmap"));
WaitStatus();
Check(!WorldMapTiles.IsOpen && WorldMapTiles.Status.Contains("No world map file"), "a missing file says so: " + WorldMapTiles.Status);
WorldMapTiles.Shutdown();
}
private static void Real(string path)
{
Console.WriteLine("real file: " + path);
Check(WaitOpen(path), "real: opens (" + WorldMapTiles.Status + ")");
if (!WorldMapTiles.IsOpen) return;
var lv = WorldMapTiles.Levels;
Check(lv.Count == 5 && lv[0].Width == 4096 && lv[4].Cols == 1 && lv[4].Rows == 1, "real: 5 levels, 4096 px down to one tile");
Check(WorldMapTiles.PixelsPerCell == 2 && WorldMapTiles.CellsWide == 2048, "real: 2 px per cell over 2048 cells");
// The top tile is the whole map: mostly deep sea (blue), so its corner pixel is the sea colour.
Check(Load(4, 0, 0, out IntPtr top) && DX9Backend.Live[top].B > DX9Backend.Live[top].R, "real: the top tile loads and its corner is sea");
// Every tile of every level inflates to a full opaque tile.
int bad = 0, total = 0;
for (int l = 0; l < lv.Count; l++)
for (int r = 0; r < lv[l].Rows; r++)
for (int c = 0; c < lv[l].Cols; c++)
{
total++;
if (!Load(l, c, r, out _)) bad++;
}
Check(bad == 0, $"real: all {total} tiles load ({bad} failed)");
WorldMapTiles.Shutdown();
Check(DX9Backend.Live.Count == 0, "real: shutdown released all");
}
}
}

View file

@ -0,0 +1,96 @@
using System.Numerics;
using RynthCore.Engine.ImGuiBackend.Panels;
namespace WorldMapTilesTests
{
/// <summary>MapProjection: cells to screen and back, and the rotation that puts the way you face up.</summary>
internal static class ProjectionTests
{
private static bool Near(Vector2 a, Vector2 b, float eps = 0.001f) => Vector2.Distance(a, b) < eps;
public static void Run(Action<bool, string> check)
{
var centre = new Vector2(400, 300);
var north = new MapProjection(centre, 1000, 1000, 2f, 0f);
// Map-up: north is up the screen, east is right, 2 px per cell.
check(Near(north.Project(1000, 1000), centre), "the view centre cell is at the screen centre");
check(Near(north.Project(1010, 1000), centre + new Vector2(20, 0)), "east is to the right, scale px per cell");
check(Near(north.Project(1000, 1010), centre + new Vector2(0, -20)), "north is up the screen");
check(!north.Turned, "no rotation is not turned");
check(MathF.Abs(MapProjection.PhiForHeading(90f)) < 1e-6f, "facing north needs no rotation");
// Round trips, through every rotation.
var rnd = new Random(7);
bool roundTrip = true;
for (int i = 0; i < 200; i++)
{
var p = new MapProjection(new Vector2(rnd.Next(100, 900), rnd.Next(100, 700)), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000,
0.12f + (float)rnd.NextDouble() * 13f, (float)(rnd.NextDouble() * Math.PI * 2));
double cx = rnd.NextDouble() * 2048, cy = rnd.NextDouble() * 2048;
p.Unproject(p.Project(cx, cy), out double bx, out double by);
if (Math.Abs(bx - cx) > 0.01 || Math.Abs(by - cy) > 0.01) roundTrip = false;
}
check(roundTrip, "unproject(project(cell)) is the cell, at any zoom and rotation");
// Rotating with the player: the heading is straight up whatever it is.
bool headingUp = true;
foreach (float h in new[] { 0f, 30f, 45f, 90f, 135f, 180f, 225f, 270f, 359f })
{
var p = new MapProjection(centre, 1000, 1000, 3f, MapProjection.PhiForHeading(h));
float r = h * MathF.PI / 180f;
if (!Near(p.ScreenDir(MathF.Cos(r), MathF.Sin(r)), new Vector2(0, -1), 0.001f)) headingUp = false;
// And a point ahead of the player, in the map, is above them on screen.
Vector2 ahead = p.Project(1000 + 10 * Math.Cos(r), 1000 + 10 * Math.Sin(r));
if (!(ahead.Y < centre.Y - 29f && MathF.Abs(ahead.X - centre.X) < 0.01f)) headingUp = false;
}
check(headingUp, "the way you face is up on screen at every heading");
// Where the compass needle and your right hand go.
var east = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(0f)); // facing east
check(Near(east.ScreenDir(0, 1), new Vector2(-1, 0)), "facing east: north is on your left");
var south = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(270f));
check(Near(south.ScreenDir(0, 1), new Vector2(0, 1)), "facing south: north is behind you (down)");
var facingNorth = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(90f));
check(Near(facingNorth.ScreenDir(1, 0), new Vector2(1, 0)), "facing north: east is on your right");
var facingWest = new MapProjection(centre, 0, 0, 1f, MapProjection.PhiForHeading(180f));
check(Near(facingWest.ScreenDir(0, 1), new Vector2(1, 0)), "facing west: north is on your right");
// Zoom about the cursor: the cell under the mouse stays under the mouse.
bool zoomFixed = true;
for (int i = 0; i < 100; i++)
{
var p = new MapProjection(new Vector2(300, 250), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000, 0.3f + (float)rnd.NextDouble() * 6f,
(float)(rnd.NextDouble() * Math.PI * 2));
var mouse = new Vector2(rnd.Next(0, 600), rnd.Next(0, 500));
float next = p.Scale * (0.4f + (float)rnd.NextDouble() * 3f);
p.Unproject(mouse, out double bx, out double by);
var (nx, ny) = p.CentreForZoomAbout(mouse, next);
var after = new MapProjection(p.Centre, nx, ny, next, MathF.Atan2(p.Sin, p.Cos));
if (!Near(after.Project(bx, by), mouse, 0.05f)) zoomFixed = false;
}
check(zoomFixed, "zooming about the cursor keeps the cell under it");
// Dragging: the cell that was under the mouse moves with it.
bool dragFollows = true;
for (int i = 0; i < 100; i++)
{
var p = new MapProjection(new Vector2(300, 250), rnd.NextDouble() * 2000, rnd.NextDouble() * 2000, 0.3f + (float)rnd.NextDouble() * 6f,
(float)(rnd.NextDouble() * Math.PI * 2));
var mouse = new Vector2(rnd.Next(0, 600), rnd.Next(0, 500));
var delta = new Vector2(rnd.Next(-80, 80), rnd.Next(-80, 80));
p.Unproject(mouse, out double bx, out double by);
var (nx, ny) = p.CentreAfterDrag(delta);
var after = new MapProjection(p.Centre, nx, ny, p.Scale, MathF.Atan2(p.Sin, p.Cos));
if (!Near(after.Project(bx, by), mouse + delta, 0.05f)) dragFollows = false;
}
check(dragFollows, "dragging moves the map with the mouse, at any rotation");
// Dragging right moves the map right: the centre cell moves west (smaller x) when not rotated.
var (dx, _) = north.CentreAfterDrag(new Vector2(20, 0));
check(Math.Abs(dx - (1000 - 10)) < 1e-6, "dragging 20 px right at 2 px per cell moves the centre 10 cells west");
var (_, dy) = north.CentreAfterDrag(new Vector2(0, 20));
check(Math.Abs(dy - (1000 + 10)) < 1e-6, "dragging 20 px down moves the centre 10 cells north");
}
}
}

View file

@ -0,0 +1,71 @@
using System.Numerics;
using RynthCore.Engine.ImGuiBackend;
namespace WorldMapTilesTests
{
/// <summary>worldmap.vec (RynthNav.Baker WorldMapVectors.Write), written here independently, and the engine's reader.</summary>
internal static class VectorTests
{
private static void WaitDone()
{
for (int i = 0; i < 300 && WorldMapVectors.Current == null && !WorldMapVectors.Failed; i++) Thread.Sleep(10);
}
public static void Run(Action<bool, string> check, string dir, string? realPath)
{
string path = Path.Combine(dir, "synthetic.vec");
using (var fs = new FileStream(path, FileMode.Create))
using (var w = new BinaryWriter(fs))
{
w.Write(new byte[] { (byte)'R', (byte)'V', (byte)'E', (byte)'C' });
w.Write(1u); w.Write(2u); w.Write(3u);
w.Write((byte)3); foreach (var (x, y) in new[] { (10f, 20f), (14f, 20f), (12f, 25.5f) }) { w.Write(x); w.Write(y); }
w.Write((byte)4); foreach (var (x, y) in new[] { (100f, 100f), (102f, 100f), (102f, 103f), (100f, 103f) }) { w.Write(x); w.Write(y); }
foreach (ushort v in new ushort[] { 1, 2, 3, 4, 2000, 2001, 2002, 2003, 7, 7, 8, 8 }) w.Write(v);
}
WorldMapVectors.Open(path);
WaitDone();
var d = WorldMapVectors.Current;
check(d != null && !WorldMapVectors.Failed, "vectors: the file opens");
if (d != null)
{
check(d.Buildings.Length == 2 && d.Buildings[0].Length == 3 && d.Buildings[1].Length == 4, "vectors: two buildings with 3 and 4 corners");
check(d.Buildings[0][2] == new Vector2(12f, 25.5f) && d.Buildings[1][3] == new Vector2(100f, 103f), "vectors: corners as written");
check(d.BuildingBounds[0] == new Vector4(10f, 20f, 14f, 25.5f) && d.BuildingBounds[1] == new Vector4(100f, 100f, 102f, 103f), "vectors: bounds for culling");
check(d.RoadCount == 3 && d.Roads[0] == 1 && d.Roads[3] == 4 && d.Roads[4] == 2000 && d.Roads[11] == 8, "vectors: three road segments as written");
}
WorldMapVectors.Shutdown();
check(WorldMapVectors.Current == null, "vectors: shutdown drops the data");
string junk = Path.Combine(dir, "junk.vec");
File.WriteAllBytes(junk, new byte[40]);
WorldMapVectors.Open(junk);
WaitDone();
check(WorldMapVectors.Current == null && WorldMapVectors.Failed, "vectors: a bad file is a failure, not a throw");
WorldMapVectors.Shutdown();
WorldMapVectors.Open(Path.Combine(dir, "nothere.vec"));
WaitDone();
check(WorldMapVectors.Current == null && WorldMapVectors.Failed, "vectors: a missing file is a failure, not a throw");
WorldMapVectors.Shutdown();
if (realPath == null) return;
Console.WriteLine("real vectors: " + realPath);
WorldMapVectors.Open(realPath);
WaitDone();
var r = WorldMapVectors.Current;
check(r != null, "real vectors: opens");
if (r == null) return;
check(r.Buildings.Length > 5000 && r.RoadCount > 5000, $"real vectors: {r.Buildings.Length} buildings, {r.RoadCount} road segments");
bool inRange = true, corners = true;
foreach (Vector2[] b in r.Buildings)
{
if (b.Length < 3 || b.Length > 10) corners = false;
foreach (Vector2 p in b) if (p.X < -10 || p.X > 2060 || p.Y < -10 || p.Y > 2060) inRange = false;
}
for (int i = 0; i < r.Roads.Length; i++) if (r.Roads[i] > 2048) inRange = false;
check(corners, "real vectors: every outline has 3 to 10 corners");
check(inRange, "real vectors: everything is inside the map");
WorldMapVectors.Shutdown();
}
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the World Map's tile loader (DXT1 version 2 files, switching files) and its projection (Panels\MapProjection.cs, compiled in) (src\RynthCore.Engine\ImGui\WorldMapTiles.cs,
compiled in; DX9Backend is a stub here): the worldmap.rmap header and tile layout as
RynthNav.Baker writes it with its map-tiles option, the tile lookups, the texture cap and eviction,
and that Shutdown releases every texture.
Run: dotnet run -c Release, optionally with the paths of a worldmap.rmap and a worldmap.vec as the arguments (exit 0 = pass, 1 = fail; a real file is checked too when given)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>WorldMapTilesTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\WorldMapTiles.cs" Link="Engine\WorldMapTiles.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\MapProjection.cs" Link="Engine\MapProjection.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\WorldMapVectors.cs" Link="Engine\WorldMapVectors.cs" />
</ItemGroup>
</Project>