Snapshot for release 2026.10.31.1 (internal 69b244e)

This commit is contained in:
Tom Bohar 2026-10-31 15:01:58 -04:00
commit 2546497f37
122 changed files with 22896 additions and 170 deletions

View file

@ -0,0 +1,258 @@
// ============================================================================
// GeometryTests - CellTests.cs
// Indoor cells (RynthCore.Geometry.Cells) and models (RynthCore.Geometry.Models)
// against the dats and the creature positions captured from ACE in dungeon
// landblock 0x6146 (Vectors\dungeon-6146.txt).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
namespace GeometryTests;
internal static class CellTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("cells", Run, order: 20);
private const uint Dungeon = 0x6146;
private const uint Town = 0xA9B4;
private static void Run()
{
using var cellDat = new DatDatabase();
using var portalDat = new DatDatabase();
T.Check(cellDat.Open(Dats.Cell), "cell dat opens");
T.Check(portalDat.Open(Dats.Portal), "portal dat opens");
var world = new IndoorWorld(cellDat, portalDat);
LoadsLandblock(world);
PortalSides(world);
var vectors = Dats.Vectors("dungeon-6146.txt");
FindsCells(world, vectors);
TestSpot(world);
TracksCells(world, vectors);
TracksOutdoors(world);
ReadsModels(world, cellDat);
}
private static void LoadsLandblock(IndoorWorld world)
{
var cells = world.LoadLandblock(Dungeon);
int bad = cells.Count(c => !c.GeometryOk);
int portals = cells.Sum(c => c.Portals.Count), noPoly = cells.Sum(c => c.Portals.Count(p => p.Polygon.Length < 3));
T.Info($"landblock {Dungeon:X4}: {cells.Count} EnvCells, {bad} without geometry, {cells.Sum(c => c.Floors.Count)} floors, " +
$"{cells.Sum(c => c.Walls.Count)} walls, {portals} portals ({noPoly} without a polygon)");
T.Check(cells.Count > 0, $"landblock {Dungeon:X4} has EnvCells");
T.Check(bad == 0, $"{bad} cells of {Dungeon:X4} failed to parse geometry: " +
string.Join(" ", cells.Where(c => !c.GeometryOk).Take(10).Select(c => c.Id.ToString("X8"))));
T.Check(noPoly == 0, $"{noPoly} portals of {Dungeon:X4} have no doorway polygon");
T.Check(ReferenceEquals(cells, world.LoadLandblock(Dungeon << 16 | 0x100)), "landblock cells are cached (same list by key or cell id)");
T.Check(cells.All(c => EnvCell.IsIndoor(c.Id) && c.Landblock == Dungeon), "every cell id is an indoor cell of the landblock");
}
// CellPortal.PortalSide says which side of the doorway polygon the cell behind it is on (TrackCell
// relies on it). Check it against the cells' plans: just ahead of every wall doorway, on the side it
// names, the neighbour covers the floor plan, and just behind it this cell does. And both cells of a
// doorway must agree (one says front, the other back of the same polygon).
private static void PortalSides(IndoorWorld world)
{
int tested = 0, ok = 0, pairs = 0, pairsOk = 0, shown = 0;
foreach (var c in world.LoadLandblock(Dungeon))
foreach (var p in c.Portals)
{
if (p.Polygon.Length < 3 || p.LeadsOutdoors) continue;
var other = world.GetCell(c.Neighbour(p));
if (other == null) continue;
Vector3 n = CellDat.Normal(p.Polygon);
// The neighbour's portal back to this cell: same polygon, so the opposite side.
var back = other.Portals.FirstOrDefault(q => q.OtherCell == c.Short && q.Polygon.Length >= 3
&& Vector3.Distance(q.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / q.Polygon.Length,
p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length) < 0.05f);
if (back != null)
{
pairs++;
bool sameNormal = Vector3.Dot(CellDat.Normal(back.Polygon), n) > 0;
if ((back.PortalSide == p.PortalSide) != sameNormal) pairsOk++;
}
if (MathF.Abs(n.Z) > 0.5f) continue;
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length;
Vector3 h = Vector3.Normalize(new Vector3(n.X, n.Y, 0)) * (p.PortalSide ? 0.25f : -0.25f);
tested++;
bool ahead = other.CoversXY(centre.X + h.X, centre.Y + h.Y, 0), behind = c.CoversXY(centre.X - h.X, centre.Y - h.Y, 0);
if (ahead && behind) ok++;
else if (shown++ < 5)
T.Info($"portal {c.Id:X8} -> {other.Id:X8} flags {p.Flags:X}: neighbour covers ahead {ahead}, this cell behind {behind}");
}
T.Info($"PortalSide: {ok}/{tested} wall doorways have the neighbour ahead and this cell behind; {pairsOk}/{pairs} doorway pairs agree");
T.Check(tested > 100 && ok >= tested * 0.98, $"PortalSide matches the cells' plans ({ok}/{tested})");
T.Check(pairs > 100 && pairsOk == pairs, $"both cells of a doorway agree on its sides ({pairsOk}/{pairs})");
}
private static void FindsCells(IndoorWorld world, List<(uint Cell, float X, float Y, float Z)> vectors)
{
// Creatures touch the floor with their lowest collision sphere: on a slope ACE's z (the feet) is
// above the floor plane, so the floor plane matches z on flat floor and StandZ matches it everywhere.
var human = world.Models.Get(ModelReader.HumanSetup);
float radius = human.Spheres.Count > 0 ? human.Spheres.Min(s => s.Radius) : 0.48f;
int cellOk = 0, findZOk = 0, floorOk = 0, standOk = 0, none = 0, flat = 0, flatOk = 0, shown = 0;
float worstStand = 0;
foreach (var v in vectors)
{
var found = world.FindCell(Dungeon, v.X, v.Y, v.Z);
float? fz = world.FloorZ(v.Cell, v.X, v.Y, v.Z);
float? sz = world.StandZ(v.Cell, v.X, v.Y, radius, v.Z);
bool cOk = found?.cellId == v.Cell;
bool zOk = fz != null && MathF.Abs(fz.Value - v.Z) <= 0.05f;
bool sOk = sz != null && MathF.Abs(sz.Value - v.Z) <= 0.05f;
if (cOk) cellOk++;
if (found == null) none++;
if (found != null && MathF.Abs(found.Value.floorZ - v.Z) <= 0.05f) findZOk++;
if (zOk) floorOk++;
if (sOk) standOk++;
if (sz != null) worstStand = MathF.Max(worstStand, MathF.Abs(sz.Value - v.Z));
var cell = world.GetCell(v.Cell);
if (cell != null && cell.Floors.Where(f => Geo.InsideXY(f, v.X, v.Y, 0.6f)).All(f => CellDat.Normal(f).Z > 0.999f))
{
flat++;
if (zOk) flatOk++;
}
if ((!cOk || !sOk) && shown++ < 15)
T.Info($"mismatch {v.Cell:X8} ({v.X:F3},{v.Y:F3},{v.Z:F3}): FindCell " +
(found == null ? "none" : $"{found.Value.cellId:X8} floor {found.Value.floorZ:F3}") +
$", FloorZ(own cell) {(fz == null ? "none" : fz.Value.ToString("F3"))}, StandZ {(sz == null ? "none" : sz.Value.ToString("F3"))}");
}
int n = vectors.Count;
double cellRate = (double)cellOk / n, floorRate = (double)floorOk / n, standRate = (double)standOk / n;
double flatRate = flat == 0 ? 0 : (double)flatOk / flat;
T.Info($"FindCell: {cellOk}/{n} cells match ({cellRate:P2}), {none} found nothing, {findZOk}/{n} with the floor plane within 0.05 m of z");
T.Info($"FloorZ(own cell, floor plane): {floorOk}/{n} within 0.05 m ({floorRate:P2}); on flat floor (no slope within 0.6 m) {flatOk}/{flat} ({flatRate:P2})");
T.Info($"StandZ(own cell, sphere r {radius:F2}): {standOk}/{n} within 0.05 m ({standRate:P2}), worst {worstStand:F3} m");
T.Check(n > 1000, $"dungeon vectors loaded ({n})");
T.Check(cellRate >= 0.95, $"FindCell matches the captured cell for >= 95% ({cellRate:P2})");
T.Check(flatRate >= 0.95, $"FloorZ on flat floor within 0.05 m for >= 95% ({flatRate:P2})");
T.Check(standRate >= 0.95, $"StandZ within 0.05 m for >= 95% ({standRate:P2})");
}
private static void TestSpot(IndoorWorld world)
{
var found = world.FindCell(Dungeon, 91.617874f, -157.55351f, -11.9885f);
T.Info($"the test character's spot (91.618,-157.554,-11.989): {(found == null ? "none" : $"{found.Value.cellId:X8} floor {found.Value.floorZ:F3}")}");
T.Check(found?.cellId == 0x61460249, "the test character's spot is in cell 61460249");
}
private static void TracksCells(IndoorWorld world, List<(uint Cell, float X, float Y, float Z)> vectors)
{
// Pairs of captured positions in portal-connected cells, a few metres apart: walking straight from
// one to the other should end in the other's cell (unless the straight line goes through a wall).
int pairs = 0, ok = 0, stayed = 0, wrong = 0, shown = 0;
int same = 0, sameOk = 0;
for (int i = 0; i < vectors.Count; i++)
for (int j = 0; j < vectors.Count; j++)
{
if (i == j) continue;
var p = vectors[i]; var q = vectors[j];
var a = new Vector3(p.X, p.Y, p.Z); var b = new Vector3(q.X, q.Y, q.Z);
float d = Vector3.Distance(a, b);
if (d > 4f) continue;
if (p.Cell == q.Cell)
{
if (same >= 2000 || d < 1f) continue;
same++;
uint s = world.TrackCell(p.Cell, a, b);
if (s == p.Cell) sameOk++;
else if (same - sameOk <= 5)
T.Info($"track within {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> ({q.X:F2},{q.Y:F2},{q.Z:F2}) ended in {s:X8}");
continue;
}
if (!world.Neighbours(p.Cell).Contains(q.Cell)) continue;
pairs++;
uint got = world.TrackCell(p.Cell, a, b);
if (got == q.Cell) ok++;
else if (got == p.Cell)
{
stayed++;
if (stayed <= 5)
T.Info($"track {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> {q.Cell:X8} ({q.X:F3},{q.Y:F3},{q.Z:F3}) stayed in the start cell");
}
else
{
wrong++;
if (shown++ < 8)
T.Info($"track {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> {q.Cell:X8} ({q.X:F2},{q.Y:F2},{q.Z:F2}) ended in {got:X8}");
}
}
double rate = pairs == 0 ? 0 : (double)ok / pairs;
T.Info($"TrackCell, adjacent cells within 4 m: {ok}/{pairs} reach the other cell ({rate:P2}), {stayed} stayed in the start cell (blocked, or the end is on its side of the doorway), {wrong} in a third cell");
T.Info($"TrackCell, same cell 1-4 m apart: {sameOk}/{same} stay in the cell");
T.Check(pairs >= 50, $"enough adjacent-cell pairs ({pairs})");
T.Check(rate >= 0.99, $"TrackCell reaches the neighbour cell for >= 99% of pairs ({rate:P2})");
// Through a wall: from the middle of the junction cell 1F0 (floor -18, an octagon around (60,-160)
// with doorways on its four straight sides) diagonally out through its south-east chamfer wall.
uint walled = world.TrackCell(0x614601F0, new Vector3(60, -160, -18), new Vector3(66, -166, -18));
T.Check(walled == 0x614601F0, $"TrackCell through a wall keeps the start cell (got {walled:X8})");
T.Check(wrong == 0, $"TrackCell never ends in a third cell ({wrong})");
T.Check(same > 0 && sameOk == same, $"TrackCell inside one cell stays there ({sameOk}/{same})");
}
// Walk out of a town building through a doorway that leads outdoors: TrackCell gives 0.
private static void TracksOutdoors(IndoorWorld world)
{
var cells = world.LoadLandblock(Town);
int tried = 0, ok = 0;
foreach (var c in cells)
foreach (var p in c.Portals.Where(p => p.LeadsOutdoors && p.Polygon.Length >= 3))
{
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length;
Vector3 n = CellDat.Normal(p.Polygon);
if (MathF.Abs(n.Z) > 0.5f) continue; // a doorway in a wall
float floor = p.Polygon.Min(v => v.Z);
Vector3 h = Vector3.Normalize(new Vector3(n.X, n.Y, 0));
// Inside is the side over the cell's floor.
Vector3 inA = centre + h * 0.75f, inB = centre - h * 0.75f;
bool aIn = IndoorWorld.CellFloorZ(c, inA.X, inA.Y) != null, bIn = IndoorWorld.CellFloorZ(c, inB.X, inB.Y) != null;
if (aIn == bIn) continue;
Vector3 from = aIn ? inA : inB, to = aIn ? inB : inA;
from.Z = to.Z = floor;
tried++;
uint got = world.TrackCell(c.Id, from, to);
if (got == 0) ok++;
else if (tried - ok <= 5) T.Info($"walking out of {c.Id:X8} at ({centre.X:F2},{centre.Y:F2}) gave {got:X8}");
}
T.Info($"TrackCell out through outdoor doorways of {Town:X4}: {ok}/{tried} give 0 (outdoors)");
T.Check(tried > 0 && ok == tried, $"walking out through an outdoor doorway gives 0 ({ok}/{tried})");
}
private static void ReadsModels(IndoorWorld world, DatDatabase cellDat)
{
var human = world.Models.Get(ModelReader.HumanSetup);
T.Info($"setup {ModelReader.HumanSetup:X8}: parsed {human.Parsed}, radius {human.Radius:F3}, height {human.Height:F3}, " +
$"{human.Cylinders.Count} cylinders [{string.Join(", ", human.Cylinders.Select(c => $"r {c.Radius:F3} h {c.Height:F3}"))}], " +
$"{human.Spheres.Count} spheres [{string.Join(", ", human.Spheres.Select(s => $"r {s.Radius:F3} at z {s.Center.Z:F3}"))}], {human.Polygons.Count} polygons");
T.Check(human.Parsed, "human setup parses");
T.Check(human.Spheres.Count + human.Cylinders.Count > 0, "human setup has collision spheres or cylinders");
var info = LandblockInfo.Load(cellDat, Town);
T.Check(info != null && info.Complete, $"LandblockInfo {Town:X4}FFFE reads completely");
if (info == null) return;
T.Info($"LandblockInfo {info.Id:X8}: {info.NumCells} cells, {info.Objects.Count} objects, {info.Buildings.Count} buildings");
int withPolys = 0;
foreach (var b in info.Buildings.Take(8))
{
var shape = world.Models.Get(b.ModelId);
if (shape.Polygons.Count > 0) withPolys++;
var placed = shape.Place(b.Origin, b.Rotation).ToList();
string span = placed.Count == 0 ? "" :
$", z {placed.Min(p => p.Min(v => v.Z)):F1}..{placed.Max(p => p.Max(v => v.Z)):F1} at ({b.Origin.X:F1},{b.Origin.Y:F1})";
T.Info($" building {b.ModelId:X8}: parsed {shape.Parsed}, {shape.Polygons.Count} physics polygons, " +
$"portals to [{string.Join(" ", b.PortalCells.Select(c => c.ToString("X4")))}]{span}");
}
T.Check(info.Buildings.Count > 0 && withPolys > 0, "town buildings have physics polygons");
// Building portals open into the landblock's own cells.
var ids = world.LoadLandblock(Town).Select(c => c.Short).ToHashSet();
int portalCells = info.Buildings.Sum(b => b.PortalCells.Count), known = info.Buildings.Sum(b => b.PortalCells.Count(ids.Contains));
T.Check(portalCells > 0 && known == portalCells, $"building portals lead to cells of the landblock ({known}/{portalCells})");
}
}

View file

@ -0,0 +1,320 @@
// ============================================================================
// GeometryTests - CollisionTests.cs
// Collision/OutdoorCollision and Scenery/SceneryPlacer against the real dats
// and the creature positions captured from ACE in five towns
// (Vectors\outdoor-towns.txt): creatures standing on porches and platforms
// must have a walkable object surface at their feet, creatures on the ground
// must have none just above it, and nobody stands inside a wall.
// ============================================================================
using System.Diagnostics;
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Collision;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Scenery;
using RynthCore.Geometry.Terrain;
namespace GeometryTests;
internal static class CollisionTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("collision", Run, order: 30);
private const uint Holtburg = 0xA9B4;
private static void Run()
{
using var cellDat = new DatDatabase();
using var portalDat = new DatDatabase();
T.Check(cellDat.Open(Dats.Cell), "cell dat opens");
T.Check(portalDat.Open(Dats.Portal), "portal dat opens");
using var terrain = new TerrainSampler(portalDat, cellDat);
var models = new ModelReader(portalDat);
var indoor = new IndoorWorld(cellDat, portalDat, models);
var oc = new OutdoorCollision(cellDat, portalDat, terrain, models, indoor);
var outdoor = Dats.Vectors("outdoor-towns.txt").Where(v => (v.Cell & 0xFFFF) < 0x100).ToList();
T.Check(outdoor.Count > 50, $"outdoor vectors loaded ({outdoor.Count})");
BuildsHoltburg(oc);
BuildsInParallel(oc, outdoor);
RaisedSurfaces(oc, terrain, outdoor);
NotInsideSolids(oc, outdoor);
Segments(oc, cellDat, outdoor);
NeighbourEdges(oc, outdoor.Select(v => v.Cell >> 16).Distinct());
SceneryRules(oc, terrain, cellDat, indoor, models);
SetupTails(portalDat);
}
private static void BuildsHoltburg(OutdoorCollision oc)
{
var sw = Stopwatch.StartNew();
var c = oc.Counts(Holtburg);
T.Info($"landblock {Holtburg:X4} built in {sw.ElapsedMilliseconds} ms: {c}");
T.Info($"region scene tables: {oc.Scenery.Tables.SceneTypes.Count} scene types, {oc.Scenery.Tables.TerrainTypes.Count} terrain types" +
(oc.Scenery.Tables.Scanned ? " (found by scanning)" : " (structured read)"));
T.Check(oc.Scenery.Tables.Ready, "region scene tables read");
T.Check(c.StaticObjects > 0 && c.StaticTris > 0, "Holtburg has static objects with collision");
T.Check(c.Buildings > 0 && c.BuildingTris > 0, "Holtburg has building shells with collision");
T.Check(c.BuildingCells > 0 && c.BuildingCellTris > 0, "Holtburg has building cells seen from outside");
T.Check(c.Total == oc.Count(Holtburg), "Count equals the per-kind total");
T.Check(ReferenceEquals(oc.Triangles(Holtburg), oc.Triangles(Holtburg << 16 | 0x0021)), "landblock is cached (same array by key or cell id)");
var tris = oc.Triangles(Holtburg);
int badNormal = tris.Count(t => MathF.Abs(t.Normal.Length() - 1) > 1e-3f);
int disagree = tris.Count(t =>
{
var n = Vector3.Cross(t.B - t.A, t.C - t.A);
return n.LengthSquared() > 1e-8f && Vector3.Dot(Vector3.Normalize(n), t.Normal) < 0.99f;
});
T.Check(badNormal == 0, $"{badNormal} triangles without a unit normal");
T.Check(disagree == 0, $"{disagree} triangles whose normal disagrees with their vertex order");
T.Info($"{tris.Count(t => t.Walkable)} of {tris.Count} triangles are walkable");
}
// Several landblocks built from parallel threads: each is built once and the results agree.
private static void BuildsInParallel(OutdoorCollision oc, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
var lbs = outdoor.Select(v => v.Cell >> 16).Distinct().ToArray();
var sw = Stopwatch.StartNew();
var arrays = new IReadOnlyList<CollisionTri>[lbs.Length * 4];
Parallel.For(0, arrays.Length, i => arrays[i] = oc.Triangles(lbs[i % lbs.Length]));
bool same = true;
for (int i = lbs.Length; i < arrays.Length; i++) same &= ReferenceEquals(arrays[i], arrays[i % lbs.Length]);
T.Check(same, "parallel callers get the same cached triangles");
T.Info($"{lbs.Length} landblocks built in parallel in {sw.ElapsedMilliseconds} ms: " +
string.Join(", ", lbs.Select(lb => $"{lb:X4} {oc.Count(lb)}")));
// How far a landblock's triangles reach past its edge (queries look MaxOverhang into neighbours).
float over = 0; uint worst = 0;
foreach (uint lb in lbs)
foreach (var t in oc.Triangles(lb))
{
float o = MathF.Max(MathF.Max(-t.MinX, t.MaxX - 192), MathF.Max(-t.MinY, t.MaxY - 192));
if (o > over) { over = o; worst = t.Source; }
}
T.Info($"largest overhang past a landblock edge: {over:F1} m (source {worst:X8})");
T.Check(over <= OutdoorCollision.MaxOverhang, $"overhang {over:F1} m is within MaxOverhang");
}
// Creatures above the terrain stand on an object's walkable surface; creatures on the terrain have no
// walkable surface just above the ground (a phantom floor would lift the walker).
private static void RaisedSurfaces(OutdoorCollision oc, TerrainSampler terrain, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
int raised = 0, found = 0, ground = 0, phantom = 0, water = 0;
foreach (var (cell, x, y, z) in outdoor)
{
uint lb = cell >> 16;
float standZ = terrain.GetStandingZ(lb, x, y), meshZ = terrain.GetTerrainZ(lb, x, y);
if (z - standZ > 0.1f && z - meshZ <= 0.1f)
{
// in water: above the standing Z (mesh less water depth) but not above the terrain mesh
water++;
T.Info($"in water {cell:X8} ({x:F2}, {y:F2}, {z:F3}): terrain mesh {meshZ:F3}, standing {standZ:F3} (not an object surface)");
}
if (z - standZ > 0.1f && z - meshZ > 0.1f)
{
raised++;
float? s = oc.SurfaceBelow(lb, x, y, z + 0.5f, 3f);
if (s != null && MathF.Abs(s.Value - z) <= 0.15f) found++;
else
{
var near = oc.Near(lb, x, y, 1f);
T.Info($"raised miss {cell:X8} ({x:F2}, {y:F2}, {z:F3}) terrain {standZ:F3}: surface {(s == null ? "none" : s.Value.ToString("F3"))}; " +
$"{near.Count} tris within 1 m ({near.Count(t => t.Walkable)} walkable" +
(near.Count > 0 ? ", sources " + string.Join(" ", near.Select(t => t.Source.ToString("X8")).Distinct().Take(6)) : "") + ")");
}
}
else if (z - standZ <= 0.1f)
{
ground++;
float top = z + 0.3f, lo = standZ + 0.1f;
float? s = top > lo ? oc.SurfaceBelow(lb, x, y, top, top - lo) : null;
if (s != null)
{
phantom++;
T.Info($"phantom floor {cell:X8} ({x:F2}, {y:F2}, {z:F3}) terrain {standZ:F3}: surface {s.Value:F3}");
}
}
}
float rate = raised == 0 ? 1 : found / (float)raised;
T.Info($"raised vectors: {found}/{raised} have a walkable surface within 0.15 m of their z ({rate:P0}); " +
$"ground vectors: {phantom}/{ground} have a walkable surface 0.1..0.3 m above the ground; {water} in water");
// Known misses (2026-10-28): two creatures in C6A9 at (89.47, 45.20) and (89.39, 52.51) stand 0.22 and
// 0.26 m above the top of a crate (static Setup 0x02000275, a 0.88 x 0.88 x 1 m physics box, top
// 43.025) with nothing else under them: most likely spawn positions that never settled.
T.Check(raised >= 15, $"enough raised vectors ({raised})");
T.Check(rate >= 0.9f, $"raised vectors find their surface ({found}/{raised})");
T.Check(phantom <= ground / 20, $"few phantom floors ({phantom}/{ground})");
}
// A body (radius 0.3 m, from 0.5 to 1.5 m above the feet) at a captured position touches no wall.
private static void NotInsideSolids(OutdoorCollision oc, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
int touching = 0, within10 = 0, within20 = 0;
foreach (var (cell, x, y, z) in outdoor)
{
uint lb = cell >> 16;
float best = float.MaxValue;
CollisionTri hit = default;
foreach (var t in oc.Near(lb, x, y, 0.3f))
{
if (t.Walkable || t.MaxZ < z + 0.5f - 0.3f || t.MinZ > z + 1.5f + 0.3f) continue;
var poly = new[] { t.A, t.B, t.C };
for (float h = 0.5f; h <= 1.501f; h += 0.1f)
{
float d = Geo.DistToPolygon(poly, new Vector3(x, y, z + h));
if (d < best) { best = d; hit = t; }
}
}
if (best >= 0.3f) continue;
touching++;
if (best < 0.1f) within10++;
if (best < 0.2f) within20++;
T.Info($"near a wall {cell:X8} ({x:F2}, {y:F2}, {z:F3}): {best:F2} m from source {hit.Source:X8}, " +
$"normal ({hit.Normal.X:F2}, {hit.Normal.Y:F2}, {hit.Normal.Z:F2}), z {hit.MinZ:F2}..{hit.MaxZ:F2}");
}
T.Info($"{outdoor.Count - touching}/{outdoor.Count} vectors are clear of walls (0.3 m body, 0.5..1.5 m up); " +
$"{touching} within 0.3 m, {within20} within 0.2 m, {within10} within 0.1 m");
T.Check(touching <= outdoor.Count / 20, $"few vectors within 0.3 m of a wall ({touching}/{outdoor.Count})");
T.Check(within10 == 0, $"no vector within 0.1 m of a wall ({within10})");
}
// A horizontal segment from a creature through the middle of a nearby building hits it; a short one in
// open ground hits nothing.
private static void Segments(OutdoorCollision oc, DatDatabase cellDat, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
var info = LandblockInfo.Load(cellDat, Holtburg)!;
var here = outdoor.Where(v => v.Cell >> 16 == Holtburg).ToList();
int tried = 0, hits = 0;
foreach (var b in info.Buildings)
{
var v = here.Select(p => (p, d: Vector2.Distance(new(p.X, p.Y), new(b.Origin.X, b.Origin.Y))))
.Where(q => q.d > 4 && q.d < 40).OrderBy(q => q.d).Select(q => q.p).FirstOrDefault();
if (v.Cell == 0) continue;
float z = MathF.Max(v.Z, b.Origin.Z) + 1f;
var a = new Vector3(v.X, v.Y, z);
var c = new Vector3(b.Origin.X, b.Origin.Y, z);
var end = c + Vector3.Normalize(c - a) * 6f;
tried++;
if (oc.SegmentHit(Holtburg, a, end, out float t, out var tri))
{
hits++;
var p = Vector3.Lerp(a, end, t);
float dist = Geo.DistToPolygon(new[] { tri.A, tri.B, tri.C }, p);
T.Check(dist < 0.01f, $"segment hit point lies on the triangle it names ({dist:F4} m)");
}
else T.Info($"segment to building {b.ModelId:X8} at ({b.Origin.X:F1}, {b.Origin.Y:F1}) from ({v.X:F1}, {v.Y:F1}) hits nothing");
}
T.Info($"segments into Holtburg buildings: {hits}/{tried} hit");
T.Check(tried >= 3, $"enough buildings near a vector ({tried})");
T.Check(hits >= tried - 1, $"segments into buildings hit ({hits}/{tried})");
// open ground: a vector with nothing within 3 m
int open = 0, openHits = 0;
foreach (var (cell, x, y, z) in outdoor)
{
uint lb = cell >> 16;
if (oc.Near(lb, x, y, 3f).Count > 0) continue;
open++;
if (oc.SegmentHit(lb, new Vector3(x - 1, y, z + 1), new Vector3(x + 1, y + 0.5f, z + 1), out _, out _)) openHits++;
}
T.Info($"{open} vectors in open ground (nothing within 3 m)");
T.Check(open > 0, "some vectors stand in open ground");
T.Check(openHits == 0, $"short segments in open ground hit nothing ({openHits}/{open})");
T.Check(!oc.SegmentHit(Holtburg, new Vector3(96, 96, 2000), new Vector3(97, 97, 2000), out _, out _), "a segment high in the air hits nothing");
}
// Triangles near a landblock edge come from the neighbour too, shifted into the queried frame.
private static void NeighbourEdges(OutdoorCollision oc, IEnumerable<uint> landblocks)
{
// a triangle within 6 m of a landblock edge, seen from the landblock across that edge
int tried = 0, seen = 0;
foreach (uint lb in landblocks)
foreach (var (dx, dy) in new[] { (0, -1), (0, 1), (-1, 0), (1, 0) })
{
var t = oc.Triangles(lb).FirstOrDefault(q =>
dy == -1 ? q.MaxY < 6 : dy == 1 ? q.MinY > 186 : dx == -1 ? q.MaxX < 6 : q.MinX > 186);
if (t == default) continue;
uint other = (uint)((int)(lb >> 8) + dx) << 8 | (uint)((int)(lb & 0xFF) + dy);
var shift = new Vector3(-dx * 192f, -dy * 192f, 0); // lb's frame -> other's frame
float cx = (t.A.X + t.B.X + t.C.X) / 3 + shift.X, cy = (t.A.Y + t.B.Y + t.C.Y) / 3 + shift.Y;
tried++;
if (oc.Near(other, cx, cy, 0.5f).Any(q => q.Source == t.Source && Vector3.Distance(q.A, t.A + shift) < 1e-3f)) seen++;
else T.Info($"triangle of {lb:X4} at ({cx - shift.X:F1}, {cy - shift.Y:F1}) not seen from {other:X4}");
}
T.Info($"edge triangles seen from the neighbouring landblock: {seen}/{tried}");
T.Check(tried >= 4 && seen == tried, $"edge triangles are seen from across the edge, shifted ({seen}/{tried})");
T.Check(oc.Near(Holtburg, 96, 96, 2f).All(q => q.MinX > -1 && q.MaxX < 193 && q.MinY > -1 && q.MaxY < 193),
"a query in the middle of a landblock sees no neighbour triangles");
}
// Scenery: some per landblock, none on a road or inside a building's footprint (under a building shell
// polygon, or on the floor of a building cell at about the scenery's height; buildings' cellars run
// under the ground and trees above them are fine).
private static void SceneryRules(OutdoorCollision oc, TerrainSampler terrain, DatDatabase cellDat, IndoorWorld indoor, ModelReader models)
{
uint[] lbs = { 0xA9B4, 0xA9B3, 0xC6A9, 0xDA55, 0x7D64, 0xC98C, 0xA9B6, 0x8A8A, 0x5C9E };
int total = 0, onRoad = 0, inBuilding = 0;
var counts = new List<string>();
foreach (uint lb in lbs)
{
var sc = oc.SceneryOf(lb);
total += sc.Count;
counts.Add($"{lb:X4} {sc.Count} ({oc.Counts(lb).SceneryTris} tris)");
var footprints = new List<Vector3[]>();
var info = LandblockInfo.Load(cellDat, lb);
if (info != null)
foreach (var b in info.Buildings) footprints.AddRange(models.Get(b.ModelId).Place(b.Origin, b.Rotation));
foreach (var c in indoor.LoadLandblock(lb))
if ((c.Flags & 1) != 0) footprints.AddRange(c.Floors);
foreach (var o in sc)
{
if (terrain.OnRoad(lb, o.Position.X, o.Position.Y)) { onRoad++; T.Info($"scenery {o.ModelId:X8} on a road in {lb:X4} at ({o.Position.X:F1}, {o.Position.Y:F1})"); }
if (footprints.Any(f => Geo.AreaXY(f) > 0.01f && Geo.InsideXY(f, o.Position.X, o.Position.Y, 0)
&& MathF.Abs(Geo.PlaneZ(f, o.Position.X, o.Position.Y) - o.Position.Z) < 3f))
{
inBuilding++;
T.Info($"scenery {o.ModelId:X8} inside a building footprint in {lb:X4} at ({o.Position.X:F1}, {o.Position.Y:F1})");
}
T.Check(o.Position.X >= 0 && o.Position.X < 192 && o.Position.Y >= 0 && o.Position.Y < 192, "scenery inside its landblock");
}
}
T.Info($"scenery: {string.Join(", ", counts)}");
T.Check(total > 50, $"scenery is placed ({total} objects in {lbs.Length} landblocks)");
T.Check(onRoad == 0, $"{onRoad} scenery objects on a road");
T.Check(inBuilding == 0, $"{inBuilding} scenery objects inside a building footprint");
T.Info($"Setups whose cylinders/spheres were read from the end of their record (animation hooks): {oc.TailReads} placements");
}
// SetupBounds reads a Setup's cylinders, spheres and sorting sphere from the end of the record when its
// placement frames have animation hooks. Check that tail reading against the front-to-back read on every
// Setup without hooks, and count how many with hooks it reads.
private static void SetupTails(DatDatabase portalDat)
{
int plain = 0, agree = 0, hooked = 0, hookedRead = 0, broken = 0;
var disagree = new List<uint>();
foreach (var e in portalDat.EnumerateEntries())
{
if ((e.ObjectId >> 24) != 0x02) continue;
byte[]? data = portalDat.GetFileData(e.ObjectId);
if (data == null) continue;
SetupBounds? fwd;
try { fwd = SetupBounds.Parse(data, fromEnd: false); }
catch (Exception) { broken++; continue; }
var tail = SetupBounds.Parse(data, fromEnd: true);
if (fwd == null) { hooked++; if (tail != null) hookedRead++; continue; }
plain++;
bool same = tail != null && tail.Cylinders.SequenceEqual(fwd.Cylinders) && tail.Spheres.SequenceEqual(fwd.Spheres)
&& tail.Height == fwd.Height && tail.Radius == fwd.Radius && tail.SortCenter == fwd.SortCenter && tail.SortRadius == fwd.SortRadius;
if (same) agree++; else if (disagree.Count < 10) disagree.Add(e.ObjectId);
}
T.Info($"Setups: {plain} without hooks ({agree} read the same from the end), {hooked} with hooks ({hookedRead} read from the end), {broken} unreadable" +
(disagree.Count > 0 ? "; disagree: " + string.Join(" ", disagree.Select(i => i.ToString("X8"))) : ""));
T.Check(plain > 1000, $"many Setups in the portal dat ({plain})");
T.Check(agree >= plain * 0.99, $"reading from the end agrees with the front-to-back read ({agree}/{plain})");
T.Check(hookedRead >= hooked * 0.95, $"Setups with animation hooks read from the end ({hookedRead}/{hooked})");
}
}

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Checks RynthCore.Geometry against the real dats (C:\Turbine\Asheron's Call, read-only) and
against ground truth captured from the local ACE server (Vectors\: positions of creatures
standing on terrain in five towns, and on dungeon floors in landblock 0x6146).
Without the dats it prints SKIP and exits 0.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>GeometryTests</RootNamespace>
<AssemblyName>GeometryTests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<None Include="Vectors\**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Geometry\RynthCore.Geometry.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,95 @@
// ============================================================================
// GeometryTests - RynthCore.Geometry against the real dats and captured ACE ground truth.
// Each area has its own file (TerrainTests.cs, CellTests.cs, ...) with a Run() that uses T.
// ============================================================================
namespace GeometryTests;
internal static class Program
{
private static int Main()
{
string? ac = Dats.Folder;
if (ac == null)
{
Console.WriteLine("SKIP: no AC dats (client_portal.dat / client_cell_1.dat) found.");
return 0;
}
Console.WriteLine($"dats: {ac}");
foreach (var (name, run) in Suites.All)
{
T.Case(name);
try { run(); }
catch (Exception ex) { T.Check(false, $"threw {ex.GetType().Name}: {ex.Message}"); }
}
Console.WriteLine();
Console.WriteLine($"{T.Checks - T.Failed}/{T.Checks} checks passed.");
Console.WriteLine(T.Failed == 0 ? "ALL GEOMETRY TESTS PASSED." : $"{T.Failed} FAILED.");
return T.Failed == 0 ? 0 : 1;
}
}
/// <summary>
/// The suites. Each area's file registers itself from a module initializer:
/// [System.Runtime.CompilerServices.ModuleInitializer]
/// internal static void Register() => Suites.Add("terrain", Run, order: 10);
/// </summary>
internal static class Suites
{
private static readonly List<(int Order, string Name, Action Run)> _all = new();
public static void Add(string name, Action run, int order) => _all.Add((order, name, run));
public static IEnumerable<(string Name, Action Run)> All => _all.OrderBy(s => s.Order).Select(s => (s.Name, s.Run));
}
internal static class Dats
{
public static string? Folder { get; } = Find();
private static string? Find()
{
foreach (string dir in new[] { Environment.GetEnvironmentVariable("AC_DAT_DIR") ?? "", @"C:\Turbine\Asheron's Call" })
if (dir.Length > 0 && File.Exists(Path.Combine(dir, "client_portal.dat")) && File.Exists(Path.Combine(dir, "client_cell_1.dat")))
return dir;
return null;
}
public static string Portal => Path.Combine(Folder!, "client_portal.dat");
public static string Cell => Path.Combine(Folder!, "client_cell_1.dat");
/// <summary>Ground-truth positions: "cell x y z" lines.</summary>
public static List<(uint Cell, float X, float Y, float Z)> Vectors(string file)
{
var list = new List<(uint, float, float, float)>();
foreach (string line in File.ReadLines(Path.Combine(AppContext.BaseDirectory, "Vectors", file)))
{
if (line.StartsWith('#') || line.Trim().Length == 0) continue;
string[] f = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
list.Add((Convert.ToUInt32(f[0], 16), float.Parse(f[1]), float.Parse(f[2]), float.Parse(f[3])));
}
return list;
}
}
internal static class T
{
public static int Checks, Failed;
private static string _case = "";
public static void Case(string name)
{
_case = name;
Console.WriteLine($"-- {name}");
}
public static void Check(bool ok, string what)
{
Checks++;
if (ok) return;
Failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
public static void Info(string s) => Console.WriteLine($" info: {s}");
}

View file

@ -0,0 +1,322 @@
// ============================================================================
// GeometryTests - TerrainTests.cs
// Terrain/TerrainSampler and Terrain/LandblockData against the real dats and
// the outdoor ground truth in Vectors\outdoor-towns.txt (creatures standing in
// five towns, positions from the local ACE server).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Terrain;
namespace GeometryTests;
internal static class TerrainTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("terrain", Run, order: 10);
private static void Run()
{
using var portal = new DatDatabase();
using var cell = new DatDatabase();
T.Check(portal.Open(Dats.Portal), "portal dat opens");
T.Check(cell.Open(Dats.Cell), "cell dat opens");
using var ts = new TerrainSampler(portal, cell);
var outdoor = Dats.Vectors("outdoor-towns.txt").Where(v => (v.Cell & 0xFFFF) < 0x100).ToList();
T.Check(outdoor.Count > 50, $"outdoor vectors loaded ({outdoor.Count})");
HeightTableAndLandblocks(ts, outdoor);
TerrainZ(ts, outdoor);
SplitPolarity(ts, outdoor);
Normals(ts, outdoor);
RaycastDown(ts, outdoor);
RaycastOblique(ts, outdoor);
Roads(ts, outdoor);
OpenFromFolder();
}
private static void HeightTableAndLandblocks(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
var table = ts.LandHeightTable;
bool monotonic = true;
for (int i = 1; i < table.Count; i++) if (table[i] < table[i - 1]) monotonic = false;
T.Check(table.Count == 256 && monotonic, "land-height table: 256 entries, non-decreasing");
T.Check(table[0] >= 0f && table[0] < 10f && table[255] > 500f && table[255] < 5000f,
$"land-height table range plausible ({table[0]} .. {table[255]})");
T.Info($"land-height table {table[0]} .. {table[255]}, [64]={table[64]} [128]={table[128]}");
var keys = outdoor.Select(v => v.Cell >> 16).Distinct().ToList();
foreach (uint key in keys)
{
var lb = ts.LoadLandblock(key);
T.Check(lb != null, $"landblock {key:X4} loads");
if (lb == null) continue;
lb.GetHeightRange(out float min, out float max);
T.Check(lb.LandblockKey == key && min >= table[0] && max <= table[255] && max - min < 400f,
$"landblock {key:X4} heights plausible ({min:F1} .. {max:F1})");
T.Check(lb.HasObjects, $"town landblock {key:X4} has objects");
T.Check(ReferenceEquals(lb, ts.LoadLandblock(key)), $"landblock {key:X4} is cached");
}
T.Info($"town landblocks: {string.Join(" ", keys.Select(k => k.ToString("X4")))}");
// Cell-id form and key form name the same landblock.
uint k0 = keys[0];
T.Check(ReferenceEquals(ts.LoadLandblock(k0), ts.LoadLandblock((k0 << 16) | 0x0019)), "0xXXYY and 0xXXYYnnnn give the same landblock");
// Neighbouring landblocks share their edge vertices (checks the ix*9+iy indexing).
int shared = 0, sharedMatch = 0;
foreach (uint key in keys)
{
var a = ts.LoadLandblock(key);
var east = ts.LoadLandblock(key + 0x0100);
var north = ts.LoadLandblock(key + 0x0001);
for (int i = 0; i <= 8; i++)
{
if (a != null && east != null) { shared++; if (a.HeightsZ[8, i] == east.HeightsZ[0, i]) sharedMatch++; }
if (a != null && north != null) { shared++; if (a.HeightsZ[i, 8] == north.HeightsZ[i, 0]) sharedMatch++; }
}
}
T.Check(shared > 0 && sharedMatch == shared, $"landblock edges match their neighbours ({sharedMatch}/{shared})");
// 0xFFFF is not a landblock: everything answers "no terrain" rather than throwing.
T.Check(ts.LoadLandblock(0xFFFF) == null && float.IsNaN(ts.GetTerrainZ(0xFFFF, 10, 10))
&& ts.GetNormal(0xFFFF, 10, 10) == Vector3.Zero && !ts.OnRoad(0xFFFF, 10, 10) && ts.TerrainType(0xFFFF, 10, 10) == -1,
"landblock 0xFFFF: null / NaN / zero / false / -1");
}
private static void TerrainZ(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
// Ground truth vs GetStandingZ (terrain mesh less the cell's water depth) and vs the bare mesh.
// Creatures can also stand on porches, platforms and ramps; those come out above the ground
// and can't be checked without the object geometry. Nothing may come out below it.
var rows = new List<(float D, float DMesh, float Wd, bool Flat, uint Cell, float X, float Y, float Z, float Gz)>();
foreach (var v in outdoor)
{
var lb = ts.LoadLandblock(v.Cell)!;
float mesh = ts.GetTerrainZ(v.Cell, v.X, v.Y);
float gz = ts.GetStandingZ(v.Cell, v.X, v.Y);
int cx = Math.Min((int)(v.X / 24f), 7), cy = Math.Min((int)(v.Y / 24f), 7);
float h = lb.GetVertexZ(cx, cy);
bool flat = lb.GetVertexZ(cx + 1, cy) == h && lb.GetVertexZ(cx, cy + 1) == h && lb.GetVertexZ(cx + 1, cy + 1) == h;
rows.Add((v.Z - gz, v.Z - mesh, ts.GetWaterDepth(v.Cell, v.X, v.Y), flat, v.Cell, v.X, v.Y, v.Z, gz));
}
int n = rows.Count;
int mesh05 = rows.Count(r => MathF.Abs(r.DMesh) <= 0.05f), mesh25 = rows.Count(r => MathF.Abs(r.DMesh) <= 0.25f);
int in05 = rows.Count(r => MathF.Abs(r.D) <= 0.05f), in25 = rows.Count(r => MathF.Abs(r.D) <= 0.25f);
var above = rows.Where(r => r.D > 0.05f).ToList();
var below = rows.Where(r => r.D < -0.05f).ToList();
int wet = rows.Count(r => r.Wd > 0f), wetOk = rows.Count(r => r.Wd > 0f && MathF.Abs(r.D) <= 0.05f);
int wetRaised = rows.Count(r => r.Wd > 0f && r.D > 0.05f);
double pct = 100.0 * in05 / n;
T.Info($"bare terrain mesh vs ACE: {mesh05}/{n} ({100.0 * mesh05 / n:F1}%) within 0.05 m, {mesh25}/{n} ({100.0 * mesh25 / n:F1}%) within 0.25 m");
T.Info($"standing Z (mesh - water depth) vs ACE: {in05}/{n} ({pct:F1}%) within 0.05 m, {in25}/{n} ({100.0 * in25 / n:F1}%) within 0.25 m; " +
$"off by > 0.05: {above.Count} above the ground ({above.Count(r => r.Flat)} of them on flat cells), {below.Count} below");
T.Info($"water cells: {wet} vectors, {wetOk} sit exactly the water depth below the mesh, {wetRaised} higher (on an object)");
foreach (var r in rows.OrderByDescending(r => MathF.Abs(r.D)).Take(6))
T.Info($" worst: {r.Cell:X8} ({r.X:F2}, {r.Y:F2}) z={r.Z:F3} ground={r.Gz:F3} off={r.D:+0.000;-0.000}{(r.Flat ? " (flat cell: on an object)" : "")}");
T.Check(rows.All(r => !float.IsNaN(r.Gz)), "every outdoor vector's landblock has terrain");
T.Check(below.Count == 0, $"no vector stands below the ground ({below.Count})");
T.Check(wetOk > 0 && wetOk == wet - wetRaised, $"water depth explains every ground-level vector in a water cell ({wetOk}/{wet - wetRaised})");
// The target was 85%, but about a fifth of the vectors (25 of 135 when written) stand on
// objects above flat cells (equal corner heights, so neither the split nor the height
// table can be at fault) where no terrain answer can match. Hence 80% overall, plus the
// ground-level share below.
T.Check(pct >= 80.0, $"at least 80% of outdoor vectors within 0.05 m of the standing Z (got {pct:F1}%)");
int ground = n - above.Count(r => r.Flat);
T.Check(in05 >= ground * 0.98, $"vectors not raised on objects match within 0.05 m ({in05}/{ground})");
}
private static void SplitPolarity(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
double sumAsIs = 0, sumInv = 0;
int okAsIs = 0, okInv = 0, differ = 0, differAsIs = 0, differInv = 0;
foreach (var v in outdoor)
{
var lb = ts.LoadLandblock(v.Cell)!;
float z = v.Z + TerrainSampler.GetWaterDepth(lb, v.X, v.Y);
float a = MathF.Abs(z - TerrainSampler.GetTerrainZ(lb, v.X, v.Y, invertSplit: false));
float b = MathF.Abs(z - TerrainSampler.GetTerrainZ(lb, v.X, v.Y, invertSplit: true));
sumAsIs += a; sumInv += b;
if (a <= 0.05f) okAsIs++;
if (b <= 0.05f) okInv++;
if (MathF.Abs(a - b) > 0.01f)
{
differ++;
if (a <= 0.05f) differAsIs++;
if (b <= 0.05f) differInv++;
T.Info($" split matters: {v.Cell:X8} ({v.X:F2}, {v.Y:F2}) z={v.Z:F3} err as implemented {a:F3}, inverted {b:F3}");
}
}
int n = outdoor.Count;
T.Info($"split polarity: as implemented mean err {sumAsIs / n:F4} m, {okAsIs}/{n} within 0.05; inverted mean err {sumInv / n:F4} m, {okInv}/{n} within 0.05");
T.Info($" on the {differ} vectors where the polarity matters: {differAsIs} match as implemented, {differInv} inverted");
T.Check(differ >= 5, $"enough vectors sit where the split matters ({differ})");
T.Check(sumAsIs < sumInv && differAsIs > differInv && differInv == 0, "implemented SwToNeCut polarity fits ACE, the inverse doesn't");
// About half the cells each way.
int sw = 0, total = 0;
foreach (uint key in outdoor.Select(v => v.Cell >> 16).Distinct())
for (int cx = 0; cx < 8; cx++)
for (int cy = 0; cy < 8; cy++) { total++; if (TerrainSampler.SwToNeCut(key, cx, cy)) sw++; }
T.Info($"SW->NE cut on {sw}/{total} cells of the town landblocks");
T.Check(sw > total / 4 && sw < total * 3 / 4, "split is roughly 50/50");
}
private static void Normals(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
int bad = 0, walkable = 0, consistent = 0, tested = 0;
foreach (var v in outdoor)
{
var n = ts.GetNormal(v.Cell, v.X, v.Y);
if (!(n.Z > 0f) || MathF.Abs(n.Length() - 1f) > 1e-4f) bad++;
if (TerrainSampler.IsWalkable(n)) walkable++;
// The normal is the gradient of GetTerrainZ: z = z0 - (nx*dx + ny*dy)/nz on the same triangle.
// Step toward the triangle's interior along a tiny offset that stays on the triangle.
var lb = ts.LoadLandblock(v.Cell)!;
float z0 = TerrainSampler.GetTerrainZ(lb, v.X, v.Y);
const float d = 0.01f;
bool all = true;
foreach (var (ox, oy) in new[] { (d, 0f), (0f, d), (-d, 0f), (0f, -d) })
{
if (TerrainSampler.GetNormal(lb, v.X + ox, v.Y + oy) != n) continue; // crossed onto another triangle
float pred = z0 - (n.X * ox + n.Y * oy) / n.Z;
if (MathF.Abs(pred - TerrainSampler.GetTerrainZ(lb, v.X + ox, v.Y + oy)) > 1e-3f) all = false;
}
tested++;
if (all) consistent++;
}
T.Check(bad == 0, $"normals are unit length with Z > 0 ({bad} bad)");
T.Check(consistent == tested, $"normal matches the GetTerrainZ gradient ({consistent}/{tested})");
double pct = 100.0 * walkable / outdoor.Count;
T.Info($"walkable ground under {walkable}/{outdoor.Count} ({pct:F1}%) town vectors");
T.Check(pct >= 95.0, "town ground under creatures is walkable");
T.Check(TerrainSampler.IsWalkable(Vector3.UnitZ) && TerrainSampler.IsWalkable(Vector3.Normalize(new Vector3(1, 0, 1))),
"IsWalkable: flat and 45 degrees yes");
T.Check(!TerrainSampler.IsWalkable(Vector3.Normalize(new Vector3(1.2f, 0, 1))), "IsWalkable: 50 degrees no");
}
private static void RaycastDown(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
int hits = 0, good = 0;
float worst = 0f;
foreach (var v in outdoor)
{
float tz = ts.GetTerrainZ(v.Cell, v.X, v.Y);
bool hit = ts.RaycastTerrain(v.Cell, new Vector3(v.X, v.Y, v.Z + 10f), -Vector3.UnitZ, 100f, out float dist, out var n);
if (!hit) continue;
hits++;
float expect = 10f + (v.Z - tz); // from z+10 down to the terrain
float err = MathF.Max(MathF.Abs(dist - expect), MathF.Abs((v.Z + 10f - dist) - tz));
worst = MathF.Max(worst, err);
if (err <= 0.01f && Vector3.Distance(n, ts.GetNormal(v.Cell, v.X, v.Y)) < 1e-4f) good++;
}
T.Check(hits == outdoor.Count, $"vertical raycast hits terrain under every vector ({hits}/{outdoor.Count})");
T.Check(good == hits, $"vertical raycast distance/normal agree with GetTerrainZ/GetNormal within 0.01 ({good}/{hits}, worst {worst:F5})");
var v0 = outdoor[0];
T.Check(!ts.RaycastTerrain(v0.Cell, new Vector3(v0.X, v0.Y, v0.Z + 10f), Vector3.UnitZ, 100f, out _, out _), "ray pointing up misses");
T.Check(!ts.RaycastTerrain(v0.Cell, new Vector3(v0.X, v0.Y, v0.Z + 10f), -Vector3.UnitZ, 5f, out _, out _), "ray shorter than the drop misses");
}
private static void RaycastOblique(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
// Rays from above the town vectors in random downward directions, long enough to cross
// several cells and often a landblock edge. The hit must lie on the terrain, and the ray
// must stay above the terrain before it.
var rng = new Random(12345);
int rays = 0, hits = 0, onGround = 0, clear = 0, crossed = 0;
float worst = 0f;
foreach (var v in outdoor)
{
for (int k = 0; k < 4; k++)
{
double ang = rng.NextDouble() * Math.PI * 2;
float down = 0.05f + (float)rng.NextDouble() * 0.4f; // shallow: long horizontal runs
var dir = Vector3.Normalize(new Vector3((float)Math.Cos(ang), (float)Math.Sin(ang), -down));
var o = new Vector3(v.X, v.Y, v.Z + 5f + (float)rng.NextDouble() * 20f);
rays++;
if (!ts.RaycastTerrain(v.Cell, o, dir, 600f, out float dist, out var n)) continue;
hits++;
var p = o + dir * dist;
float z = WorldZ(ts, v.Cell, p.X, p.Y, out bool otherLb);
if (otherLb) crossed++;
float err = MathF.Abs(p.Z - z);
worst = MathF.Max(worst, err);
if (err <= 0.01f && n.Z > 0f && MathF.Abs(n.Length() - 1f) < 1e-4f) onGround++;
bool above = true;
for (float s = 0.25f; s < dist - 0.05f; s += 0.25f)
{
var q = o + dir * s;
if (q.Z < WorldZ(ts, v.Cell, q.X, q.Y, out _) - 0.005f) { above = false; break; }
}
if (above) clear++;
}
}
T.Info($"oblique rays: {hits}/{rays} hit, {crossed} hits in a neighbouring landblock, worst hit-point error {worst:F5} m");
T.Check(hits > rays * 3 / 4, "most oblique rays hit the ground");
T.Check(onGround == hits, $"oblique hit points lie on the terrain within 0.01 ({onGround}/{hits})");
T.Check(clear == hits, $"oblique rays stay above the terrain before the hit ({clear}/{hits})");
T.Check(crossed > 0, "some oblique hits land past the starting landblock");
}
/// <summary>Terrain Z at a point given relative to <paramref name="cell"/>'s landblock, which may lie in a neighbour.</summary>
private static float WorldZ(TerrainSampler ts, uint cell, float lx, float ly, out bool otherLandblock)
{
uint key = cell >> 16;
int bx = (int)((key >> 8) & 0xFF) + (int)MathF.Floor(lx / 192f);
int by = (int)(key & 0xFF) + (int)MathF.Floor(ly / 192f);
float x = lx - MathF.Floor(lx / 192f) * 192f, y = ly - MathF.Floor(ly / 192f) * 192f;
uint nk = (uint)((bx << 8) | by);
otherLandblock = nk != key;
return ts.GetTerrainZ(nk, x, y);
}
private static void Roads(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
{
int roadVerts = 0, roadOk = 0, noRoadCells = 0, noRoadOk = 0;
foreach (uint key in outdoor.Select(v => v.Cell >> 16).Distinct())
{
var lb = ts.LoadLandblock(key)!;
for (int ix = 0; ix < 8; ix++)
for (int iy = 0; iy < 8; iy++)
{
float x = ix * 24f + 0.1f, y = iy * 24f + 0.1f;
if (TerrainSampler.RoadBits(lb, ix, iy) != 0)
{
roadVerts++;
if (TerrainSampler.OnRoad(lb, x, y)) roadOk++;
}
if (TerrainSampler.RoadBits(lb, ix, iy) == 0 && TerrainSampler.RoadBits(lb, ix + 1, iy) == 0
&& TerrainSampler.RoadBits(lb, ix, iy + 1) == 0 && TerrainSampler.RoadBits(lb, ix + 1, iy + 1) == 0)
{
noRoadCells++;
if (!ts.OnRoad(key, ix * 24f + 12f, iy * 24f + 12f)) noRoadOk++;
}
}
}
int onRoad = outdoor.Count(v => ts.OnRoad(v.Cell, v.X, v.Y));
T.Info($"roads: {roadVerts} road vertices in the town landblocks; {onRoad}/{outdoor.Count} vectors on a road");
T.Check(roadVerts > 0, "town landblocks have roads");
T.Check(roadOk == roadVerts, $"a point just inside a road vertex is on the road ({roadOk}/{roadVerts})");
T.Check(noRoadOk == noRoadCells, $"cells with no road corners have no road ({noRoadOk}/{noRoadCells})");
var types = outdoor.Select(v => ts.TerrainType(v.Cell, v.X, v.Y)).ToList();
T.Check(types.All(t => t >= 0 && t < 32), "terrain types in 0..31");
T.Info($"terrain types under the vectors: {string.Join(" ", types.GroupBy(t => t).OrderByDescending(g => g.Count()).Select(g => $"{g.Key}x{g.Count()}"))}");
}
private static void OpenFromFolder()
{
using var ts = TerrainSampler.Open(Dats.Folder!);
var v = Dats.Vectors("outdoor-towns.txt")[0];
T.Check(MathF.Abs(ts.GetTerrainZ(v.Cell, v.X, v.Y) - v.Z) < 0.25f, "TerrainSampler.Open(folder) works");
bool threw = false;
try { TerrainSampler.Open(Path.GetTempPath()).Dispose(); } catch (FileNotFoundException) { threw = true; }
T.Check(threw, "Open on a folder without dats throws FileNotFoundException");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,136 @@
# cell x y z (outdoor creatures standing in 5 towns: CreateObject positions with gravity, and grounded UpdatePositions; captured from the local ACE server)
A9B40019 84.000 7.100 94.006
A9B40019 78.096 1.676 93.973
A9B30006 18.079 125.216 93.992
A9B30010 28.052 175.548 92.747
A9B4002A 124.794 31.515 94.010
A9B40029 128.520 4.955 94.005
A9B40021 115.251 6.488 94.005
A9B4001A 91.519 37.745 94.000
A9B40029 122.227 11.951 94.000
A9B40032 154.569 36.201 96.005
A9B40021 101.926 20.412 94.005
A9B40019 83.300 14.036 94.005
A9B40022 97.000 27.000 94.005
A9B40022 112.238 46.380 94.000
A9B40022 114.644 46.356 94.005
DA55001D 84.800 99.000 20.006
D955003D 175.883 104.590 20.005
DA55001D 93.831 98.497 19.973
DA55001D 73.579 98.226 20.005
DA55001D 75.507 116.917 20.010
DA55001F 93.743 148.683 20.005
DA550032 154.009 44.961 20.005
DA550002 20.403 39.743 20.005
DA550008 13.727 172.056 20.005
DA55001F 75.740 153.489 25.005
DA55001D 84.822 109.282 20.005
DA550025 115.172 103.375 20.005
DA550038 154.914 170.884 20.000
DA55000C 39.224 82.093 20.000
DA550007 12.238 151.614 20.000
DA550012 54.482 37.256 20.000
DA55002E 124.598 127.401 20.000
DA55001D 86.340 104.570 20.005
DA55001D 82.000 102.000 20.005
7D64000D 31.900 104.600 11.906
7C640026 119.472 143.944 -0.103
7C640034 144.734 95.263 0.186
7C64003B 168.512 71.781 6.089
7D650001 0.500 0.500 11.992
7D64001E 85.920 138.564 15.605
7D64001B 78.387 51.565 12.010
7D640018 62.303 173.546 12.000
7D64001D 86.636 105.347 12.005
7D64001B 81.841 63.649 15.605
7D64001B 78.763 64.290 15.605
7D640018 66.199 183.290 12.005
7D64002C 140.955 87.873 15.497
7D64001B 85.052 65.269 20.805
7D64001C 90.563 90.580 12.005
7D640015 60.374 116.128 12.000
7D640024 100.928 84.661 12.000
7D64001F 85.618 148.353 12.000
7D64001D 95.773 113.577 12.000
7D64001E 95.772 132.065 12.000
7D64000D 39.203 102.204 12.005
7D640015 58.000 106.000 12.005
7D640022 106.470 32.042 11.992
7D64002E 139.691 134.168 14.452
7D64000D 30.148 111.945 11.156
C6A90009 46.805 4.219 42.011
C5A80036 156.578 138.985 41.992
C6A80015 52.798 102.910 42.005
C6A9001C 81.350 94.862 42.005
C6A90019 79.758 22.932 43.041
C6A9000B 27.440 66.958 42.005
C6A9000B 28.855 65.493 42.005
C6A90019 77.195 22.920 43.032
C6A9000B 30.486 64.544 42.005
C6A9000B 32.375 64.493 42.005
C6A9000B 34.818 64.519 42.005
C6A90019 82.369 22.988 43.027
C6A9001A 89.352 29.061 43.102
C6A9001A 89.369 27.142 43.155
C6A9001A 89.394 30.969 43.169
C6A9001A 89.385 32.920 43.155
C6A9001A 89.382 43.356 43.088
C6A9001A 89.467 45.201 43.249
C6A9001A 89.430 46.973 43.075
C6A9001B 89.407 48.832 43.022
C6A9001B 89.420 50.715 43.022
C6A9001B 89.387 52.505 43.289
C6A9001B 89.408 54.351 43.022
C6A9001B 89.388 56.113 43.022
C6A90014 70.695 80.516 42.005
C6A90022 102.932 39.494 42.005
C6A90022 102.900 35.586 42.005
C6A9001C 85.691 94.233 42.005
C6A9001C 79.591 94.927 42.005
C6A9001C 88.291 86.716 42.005
C6A90024 107.600 75.233 42.005
C6A9001B 92.510 61.022 71.174
C6A9000B 43.174 66.804 42.005
C6A9001A 74.834 46.387 42.005
C98C0028 113.666 190.259 22.011
C98D0001 18.872 2.470 3.550
C98D0009 30.081 2.246 3.550
C98D0002 23.909 37.389 3.550
C98D000A 29.282 44.763 3.550
C98D0003 20.924 54.795 3.550
C98D0003 18.426 48.139 3.550
C98D000C 31.589 75.195 3.550
C98D0009 24.756 4.202 3.550
C98D001C 94.907 83.491 14.939
C98D0025 100.322 109.610 9.938
C98D002B 133.213 66.673 21.992
C98D002C 139.178 89.631 21.992
C98C0028 107.834 179.356 25.005
C98C0028 102.229 188.555 22.005
C98C000E 30.760 123.202 3.550
C98C0006 18.672 142.042 3.550
C98C000F 28.457 149.060 3.550
C98C000F 24.882 162.099 3.550
C98C000F 24.995 156.887 3.550
C98C0007 17.326 152.303 3.550
C98C000F 30.828 165.435 3.550
C98C0007 17.991 165.103 3.550
C98D002C 138.968 89.764 21.992
C98D002C 138.698 89.868 21.992
C98D002C 138.304 90.093 21.992
C98D002C 138.033 90.195 21.992
A9B40029 133.604 17.392 94.011
A9B4003D 176.730 106.375 65.278
A9B40029 133.604 22.392 94.003
A9B40029 133.604 17.792 94.011
A9B40029 133.604 18.292 94.011
A9B40029 133.604 18.728 94.011
A9B40029 133.604 19.072 94.011
A9B40029 133.604 22.214 94.003
A9B40029 133.604 21.590 94.003
A9B40029 133.604 20.535 94.003
A9B40029 133.604 20.636 94.003
A9B40029 133.604 19.472 94.011
A9B40029 133.604 19.908 94.011
A9B40029 133.604 20.338 94.011
A9B40029 133.604 21.438 94.100

View file

@ -0,0 +1,285 @@
// ============================================================================
// WalkTests - the kinematic walker (RynthCore.Geometry/Walking/Walker.cs) on the real dats,
// checked against positions ACE reported (Vectors\).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Collision;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Terrain;
using RynthCore.Geometry.Walking;
namespace GeometryTests;
internal static class WalkTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("walk", Run, order: 40);
private static void Run()
{
using var portal = new DatDatabase();
using var cell = new DatDatabase();
T.Check(portal.Open(Dats.Portal) && cell.Open(Dats.Cell), "dats open");
var terrain = new TerrainSampler(portal, cell);
var indoor = new IndoorWorld(cell, portal, new ModelReader(portal));
var walker = new Walker(terrain, indoor);
var world = new OutdoorCollision(cell, portal, terrain, indoor.Models, indoor);
var withObstacles = new Walker(terrain, indoor, new StaticObstacles(world));
Dungeon(walker, indoor);
Outdoors(walker, terrain, indoor);
ObstacleWalks(withObstacles, terrain, indoor, world);
IntoBuilding(withObstacles, indoor, terrain);
Planner(withObstacles, terrain);
}
/// <summary>Pairs of town points whose straight walk is blocked: the local planner finds a way and walking it arrives.</summary>
private static void Planner(Walker walker, TerrainSampler terrain)
{
var v = Dats.Vectors("outdoor-towns.txt")
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
var planner = new LocalPlanner(walker);
int blockedPairs = 0, planned = 0, walked = 0;
long ms = 0;
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (var a in v)
{
foreach (var b in v.Where(b => b.Cell >> 16 == a.Cell >> 16 && Dist2(a, b) is > 15 and < 40))
{
var start = new PathPoint(a.Cell, new Vector3(a.X, a.Y, a.Z));
var straight = WalkTo(walker, a.Cell, start.Position, new Vector2(b.X, b.Y));
if (Vector2.Distance(new Vector2(straight.Position.X, straight.Position.Y), new Vector2(b.X, b.Y)) < 0.5f) continue;
blockedPairs++;
sw.Restart();
var path = planner.Find(start, new Vector2(b.X, b.Y), 0.5f);
ms += sw.ElapsedMilliseconds;
if (path == null) continue;
planned++;
// Follow the path with the walker.
var r = new StepResult(a.Cell, start.Position, false);
foreach (var pt in path.Skip(1))
{
var target = LocalPlanner.InFrame(a.Cell >> 16, pt.Cell, pt.Position);
var here = LocalPlanner.InFrame(a.Cell >> 16, r.Cell, r.Position);
r = walker.Step(r.Cell, r.Position, target.X - here.X, target.Y - here.Y);
if (r.Blocked) break;
}
if (!r.Blocked && Vector2.Distance(LocalPlanner.InFrame(a.Cell >> 16, r.Cell, r.Position), new Vector2(b.X, b.Y)) < 0.6f) walked++;
if (blockedPairs >= 25) break;
}
if (blockedPairs >= 25) break;
}
T.Info($"planner: {blockedPairs} blocked pairs, {planned} planned ({(planned > 0 ? ms / planned : 0)} ms each), {walked} walked to the goal");
T.Check(blockedPairs >= 5, "there are blocked pairs to plan around");
T.Check(planned >= blockedPairs * 0.7, $"most blocked pairs get a path ({planned}/{blockedPairs})");
T.Check(walked == planned, $"every planned path walks to the goal ({walked}/{planned})");
}
private static void Dungeon(Walker walker, IndoorWorld indoor)
{
var v = Dats.Vectors("dungeon-6146.txt");
var byCell = v.GroupBy(p => p.Cell).ToDictionary(g => g.Key, g => g.ToList());
// Walk from a captured position to one in a neighbouring cell (up to 4 m away, roughly level).
int pairs = 0, arrived = 0, rightCell = 0, rightZ = 0;
var misses = new List<string>();
var rng = new Random(7);
foreach (var a in v.OrderBy(_ => rng.Next()).Take(600))
{
foreach (uint n in indoor.Neighbours(a.Cell))
{
if (!byCell.TryGetValue(n, out var list)) continue;
var b = list.FirstOrDefault(p => Dist2(a, p) < 4 && Dist2(a, p) > 0.5f && MathF.Abs(p.Z - a.Z) < 0.3f);
if (b.Cell == 0) continue;
pairs++;
var r = WalkTo(walker, a.Cell, new Vector3(a.X, a.Y, a.Z), new Vector2(b.X, b.Y));
bool there = Vector2.Distance(new Vector2(r.Position.X, r.Position.Y), new Vector2(b.X, b.Y)) < 0.05f;
if (there) arrived++;
if (there && r.Cell == b.Cell) rightCell++;
if (there && MathF.Abs(r.Position.Z - b.Z) < 0.15f) rightZ++;
if ((!there || r.Cell != b.Cell) && misses.Count < 8)
misses.Add($"{a.Cell:X8} ({a.X:F2},{a.Y:F2}) -> {b.Cell:X8} ({b.X:F2},{b.Y:F2}): ended {r.Cell:X8} ({r.Position.X:F2},{r.Position.Y:F2}) {r.Why}");
break;
}
}
T.Info($"dungeon neighbour walks: {pairs} pairs, {arrived} arrived, {rightCell} in the right cell, {rightZ} at ACE's height (0.15 m)");
foreach (string m in misses) T.Info(" " + m);
T.Check(pairs > 100, "enough neighbour pairs");
T.Check(arrived >= pairs * 0.85, $"most straight walks between neighbouring cells get there ({arrived}/{pairs})");
T.Check(rightCell >= arrived * 0.97, $"and end in ACE's cell ({rightCell}/{arrived})");
T.Check(rightZ >= arrived * 0.9, $"at ACE's height ({rightZ}/{arrived})");
// Long walks in random directions: never end outside a cell, the cell agrees with FindCell.
int walks = 0, consistent = 0, blocked = 0;
foreach (var a in v.OrderBy(_ => rng.Next()).Take(200))
{
float ang = (float)(rng.NextDouble() * Math.PI * 2);
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 30, MathF.Sin(ang) * 30);
walks++;
if (r.Blocked) blocked++;
var found = indoor.FindCell(0x6146, r.Position.X, r.Position.Y, r.Position.Z);
if (r.Cell >> 16 == 0x6146 && indoor.GetCell(r.Cell)?.CoversXY(r.Position.X, r.Position.Y) == true && found?.cellId == r.Cell) consistent++;
}
T.Info($"30 m walks: {walks}, {blocked} stopped by walls, {consistent} end in a consistent cell");
T.Check(consistent >= walks * 0.97, $"walks end where FindCell agrees ({consistent}/{walks})");
// The test character's spot.
var start = new Vector3(91.617874f, -157.55351f, -11.9885f);
var rb = walker.Step(0x61460249, start, 1.5f, 0);
T.Check(!rb.Blocked || rb.Why != null, "a step from the test character's spot resolves");
SlopedDoorway(walker);
}
/// <summary>
/// The Matron hive (0x6346): tunnel 0x01A5 opens into room 0x01A6 through a doorway that slopes up over the
/// tunnel's end, so the doorway is crossed above the feet before the room's floor begins. A 4Hives
/// route walks straight through it (2026-10-29: the walker stopped at the tunnel's end until TrackCell
/// learned sloping doorways).
/// </summary>
private static void SlopedDoorway(Walker walker)
{
var east = WalkTo(walker, 0x634601A5, new Vector3(136f, -10f, -24f), new Vector2(151.5f, -10f));
T.Check(east.Cell == 0x634601B1 && MathF.Abs(east.Position.X - 151.5f) < 0.3f,
$"hive tunnel -> room -> loot room through the sloping doorway (ended {east.Cell:X8} x {east.Position.X:F1})");
var west = WalkTo(walker, 0x634601B1, new Vector3(150f, -10f, -24f), new Vector2(136f, -10f));
T.Check(west.Cell == 0x634601A5 && MathF.Abs(west.Position.X - 136f) < 0.3f,
$"and back out under it (ended {west.Cell:X8} x {west.Position.X:F1})");
var beside = WalkTo(walker, 0x634601A6, new Vector3(142f, -6f, -24f), new Vector2(136f, -6f));
T.Check(beside.Cell != 0x634601A5, $"beside the tunnel mouth the room's ramp is not the tunnel (ended {beside.Cell:X8})");
}
private static void Outdoors(Walker walker, TerrainSampler terrain, IndoorWorld indoor)
{
var v = Dats.Vectors("outdoor-towns.txt")
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
int walks = 0, onGround = 0, cellOk = 0;
var rng = new Random(11);
foreach (var a in v.Take(60))
{
float ang = (float)(rng.NextDouble() * Math.PI * 2);
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 10, MathF.Sin(ang) * 10);
walks++;
uint lb = r.Cell >> 16;
if (EnvCell.IsIndoor(r.Cell))
{
// Walked in through a ground-level doorway: fine if the cell agrees.
bool ok = indoor.FindCell(lb, r.Position.X, r.Position.Y, r.Position.Z)?.cellId == r.Cell;
if (ok) { onGround++; cellOk++; }
else T.Info($" entered {r.Cell:X8} but FindCell disagrees");
continue;
}
float g = terrain.GetStandingZ(lb, r.Position.X, r.Position.Y);
if (MathF.Abs(g - r.Position.Z) < 0.01f) onGround++;
if (r.Cell == Walker.OutdoorCell(lb, r.Position.X, r.Position.Y)) cellOk++;
else T.Info($" land cell miss: from {a.Cell:X8} ({a.X:F2},{a.Y:F2}) ended {r.Cell:X8} ({r.Position.X:F2},{r.Position.Y:F2}) blocked {r.Blocked} {r.Why}");
}
T.Info($"outdoor 10 m walks (no obstacles loaded, ground-level doors count when the cell agrees): {walks}, {onGround} on the terrain, {cellOk} with the right land cell");
T.Check(onGround == walks && cellOk == walks, "outdoor walks follow the terrain and land cells");
// Across a landblock edge: Holtburg 0xA9B4 east edge -> 0xAAB4.
float z0 = terrain.GetStandingZ(0xA9B4, 190f, 100f);
var e = walker.Step(Walker.OutdoorCell(0xA9B4, 190f, 100f), new Vector3(190f, 100f, z0), 5f, 0f);
T.Check(!e.Blocked && e.Cell >> 16 == 0xAAB4 && MathF.Abs(e.Position.X - 3f) < 0.01f,
$"crossing east into 0xAAB4 (ended 0x{e.Cell:X8} x {e.Position.X:F2}{(e.Blocked ? ", " + e.Why : "")})");
T.Check(MathF.Abs(e.Position.Z - terrain.GetStandingZ(0xAAB4, e.Position.X, e.Position.Y)) < 0.01f, "and on its terrain");
}
/// <summary>Outdoor walks among buildings, statics and scenery: feet on terrain or a walkable surface, never in a wall.</summary>
private static void ObstacleWalks(Walker walker, TerrainSampler terrain, IndoorWorld indoor, OutdoorCollision world)
{
var v = Dats.Vectors("outdoor-towns.txt")
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
int walks = 0, grounded = 0, clear = 0, blocked = 0;
var rng = new Random(13);
foreach (var a in v.Take(70))
{
float ang = (float)(rng.NextDouble() * Math.PI * 2);
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 15, MathF.Sin(ang) * 15);
walks++;
if (r.Blocked) blocked++;
uint lb = r.Cell >> 16;
var q = r.Position;
bool ok;
if (EnvCell.IsIndoor(r.Cell))
{
// Inside: the cell index agrees, or we stopped on the threshold just past the doorway's
// plane (ACE changes cells at that plane too) before the cell's floor starts.
ok = indoor.FindCell(lb, q.X, q.Y, q.Z)?.cellId == r.Cell
|| (indoor.GetCell(r.Cell)?.Portals.Any(cp => cp.LeadsOutdoors && cp.Polygon.Length >= 3
&& RynthCore.Geometry.Cells.Geo.DistToPolygon(cp.Polygon, q + new Vector3(0, 0, 0.6f)) < 1.0f) ?? false);
}
else
{
float g = terrain.GetStandingZ(lb, q.X, q.Y);
float? s = world.SurfaceBelow(lb, q.X, q.Y, q.Z + 0.01f, 0.05f);
ok = MathF.Abs(g - q.Z) < 0.01f || (s is { } sz && MathF.Abs(sz - q.Z) < 0.01f);
}
if (ok) grounded++;
else T.Info($" not grounded: from {a.Cell:X8} ({a.X:F2},{a.Y:F2},{a.Z:F2}) ended {r.Cell:X8} ({q.X:F2},{q.Y:F2},{q.Z:F2}) terrain {terrain.GetStandingZ(lb, q.X, q.Y):F2} surface {world.SurfaceBelow(lb, q.X, q.Y, q.Z + 1, 3)?.ToString("F2") ?? "-"} {r.Why}");
bool inWall = !EnvCell.IsIndoor(r.Cell) && world.Near(lb, q.X, q.Y, 0.3f)
.Any(t => !t.Walkable && RynthCore.Geometry.Cells.Geo.DistToPolygon(new[] { t.A, t.B, t.C }, q + new Vector3(0, 0, 1.0f)) < 0.3f);
if (!inWall) clear++;
}
T.Info($"15 m walks among obstacles: {walks}, {blocked} stopped, {grounded} standing on terrain or a surface, {clear} clear of walls");
T.Check(grounded == walks, $"feet always on terrain, an object surface or a cell floor ({grounded}/{walks})");
T.Check(clear == walks, $"never ends inside a wall ({clear}/{walks})");
}
private static void IntoBuilding(Walker walker, IndoorWorld indoor, TerrainSampler terrain)
{
int tried = 0, entered = 0, windows = 0;
var misses = new List<string>();
foreach (EnvCell c in indoor.LoadLandblock(0xA9B4))
{
if ((c.Flags & 1) == 0) continue;
foreach (CellPortal p in c.Portals.Where(p => p.LeadsOutdoors && p.Polygon.Length >= 3))
{
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, q) => s + q) / p.Polygon.Length;
Vector3 n = CellDat.Normal(p.Polygon);
var flat = Vector2.Normalize(new Vector2(n.X, n.Y));
if (float.IsNaN(flat.X)) continue;
// Outward = toward the side PortalSide names (the way TrackCell leaves the cell).
Vector2 outward = p.PortalSide ? flat : -flat;
var outside = new Vector2(centre.X, centre.Y) + outward * 3f;
var inside = new Vector2(centre.X, centre.Y) - outward * 1.2f;
float z = terrain.GetStandingZ(0xA9B4, outside.X, outside.Y);
// Windows are outdoor portals too: skip openings whose sill is more than a step above the ground.
float sill = p.Polygon.Min(q => q.Z);
float ground = terrain.GetStandingZ(0xA9B4, centre.X + outward.X * 0.6f, centre.Y + outward.Y * 0.6f);
if (sill - ground > walker.StepUp + 0.1f) { windows++; continue; }
tried++;
var r = WalkTo(walker, Walker.OutdoorCell(0xA9B4, outside.X, outside.Y), new Vector3(outside, z), inside);
if (r.Cell == c.Id || (EnvCell.IsIndoor(r.Cell) && r.Cell >> 16 == 0xA9B4)) entered++;
else if (misses.Count < 6) misses.Add($"door of {c.Id:X8}: ended {r.Cell:X8} ({r.Position.X:F1},{r.Position.Y:F1},{r.Position.Z:F2}) {r.Why}");
}
}
T.Info($"Holtburg doorways: {tried} tried, {entered} walked inside ({windows} windows skipped)");
foreach (string m in misses) T.Info(" " + m);
T.Check(tried > 5, "Holtburg has buildings with outdoor doorways");
T.Check(entered >= tried * 0.8, $"walking through a doorway enters the building ({entered}/{tried})");
}
/// <summary>Steps toward a point in 0.4 m pieces until there, blocked, or 100 steps.</summary>
private static StepResult WalkTo(Walker w, uint cell, Vector3 pos, Vector2 goal)
{
var r = new StepResult(cell, pos, false);
for (int i = 0; i < 100; i++)
{
var d = goal - new Vector2(r.Position.X, r.Position.Y);
float len = d.Length();
if (len < 0.01f) break;
float s = Math.Min(len, 0.4f);
var n = w.Step(r.Cell, r.Position, d.X / len * s, d.Y / len * s);
if (n.Blocked) return n;
r = n;
}
return r;
}
private static float Dist2((uint Cell, float X, float Y, float Z) a, (uint Cell, float X, float Y, float Z) b)
=> MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
}

View file

@ -0,0 +1,771 @@
// ============================================================================
// ActionsTests - the ACTIONS area: each action's game action (type + payload), the
// busy count with its events, use-done / weenie-error sequences, merge results,
// selection, chat (InvokeChatParser through a plugin's OnChatBarEnter, WriteToChat
// echo), confirmations, jumps and manual driving (autorun + heading, turning, stops,
// living with a planned walk and the server's move-to).
// ============================================================================
using System.Buffers.Binary;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore.Headless.Host;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
using RynthCore.PluginSdk;
namespace HeadlessHostTests;
internal static unsafe class ActionsTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("actions", Run, order: 30);
private const uint TurnRight = 0x6500000D, WalkBackwards = 0x45000006;
private static Fixture F => Fixture.Shared;
private static RynthCoreApiNative* Api => F.Api;
private static uint Me => F.Session.World.Player.Id;
private static void Run()
{
WieldOnUse();
PickUpOnUseInCorpse();
SalvageDirect();
Fixture f = F;
using var _ = f.Context.Enter();
T.Check(f.Session.State == SessionState.InWorld, "session in world");
Combat();
BusyAndUseDone();
Errors();
Inventory();
Merge();
Selection();
Chat();
Confirmation();
Jumps();
Drive();
DriveAndWalks();
}
// ── helpers ─────────────────────────────────────────────────────────────
private static uint U32(byte[] b, int at) => BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan(at));
private static int I32(byte[] b, int at) => BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(at));
private static float F32(byte[] b, int at) => BinaryPrimitives.ReadSingleLittleEndian(b.AsSpan(at));
private static string S16(byte[] b, ref int at)
{
int n = BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan(at));
string s = Encoding.Latin1.GetString(b, at + 2, n);
at += 2 + n;
at = (at + 3) & ~3;
return s;
}
/// <summary>Exactly one action of <paramref name="type"/> sent since the mark (and nothing else): its payload.</summary>
private static byte[] One(int mark, uint type, string what)
{
var sent = F.ActionsSince(mark);
T.Check(sent.Count == 1 && sent[0].Type == type,
$"{what}: one 0x{type:X4} sent (got {string.Join(", ", sent.Select(s => $"0x{s.Type:X4}"))})");
return sent.Count > 0 ? sent[^1].Payload : Array.Empty<byte>();
}
private static byte[] GameEvent(uint type, byte[] body)
{
var b = new byte[16 + body.Length];
BinaryPrimitives.WriteUInt32LittleEndian(b, 0xF7B0);
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), Me);
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8), 0x1000);
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(12), type);
body.CopyTo(b, 16);
return b;
}
private static byte[] U32s(params uint[] v)
{
var b = new byte[v.Length * 4];
for (int i = 0; i < v.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(i * 4), v[i]);
return b;
}
private static byte[] UseDone(uint error) => GameEvent(0x01C7, U32s(error));
private static List<PluginEvent> Drain() => F.Context.Events.Drain();
/// <summary>A stub object (no ObjectCreate) in a made-up container, so the real world model is untouched.</summary>
private static WorldObject Stub(uint id)
{
F.Receive(GameEvent(0x0022, U32s(id, 0x7FFF00FF, 0, 0)));
return F.Session.World.Get(id)!;
}
private static void Advance(long ms, long step = 50)
{
for (long t = 0; t < ms; t += step)
{
F.Now += step;
F.Session.Tick();
}
}
// Not equipment: "use" on equipment is a wield, as in the retail client (checked in WieldOnUse).
/// <summary>"Use" on carried equipment wields it (the retail client's behaviour); on wielded equipment it unwields.</summary>
private static void WieldOnUse()
{
using var _ = F.Context.Enter();
var w = F.Session.World;
var gear = w.Inventory().FirstOrDefault(o => o.WielderId == 0 && (o.Desc.ValidLocations ?? 0) != 0 && (o.Desc.ValidLocations & 0xC0000) != 0xC0000);
var worn = w.Inventory().FirstOrDefault(o => o.WielderId == Me);
T.Check(gear != null && worn != null, "the replay has pack equipment and worn equipment");
if (gear == null || worn == null) return;
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(gear.Id), 1, "UseObject on pack equipment");
var acts = F.ActionsSince(m);
T.Check(acts.Count == 1 && acts[0].Type == 0x001A && U32(acts[0].Payload, 0) == gear.Id && U32(acts[0].Payload, 4) == gear.Desc.ValidLocations,
"it goes out as GetAndWieldItem with the item's locations");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(worn.Id), 1, "UseObject on worn equipment");
acts = F.ActionsSince(m);
T.Check(acts.Count == 1 && acts[0].Type == 0x0019 && U32(acts[0].Payload, 0) == worn.Id && U32(acts[0].Payload, 4) == Me,
"it goes out as PutItemInContainer into the pack");
}
/// <summary>SalvageDirect: one 0x027D action (tool, count, ids) for carried items; anything else is refused.</summary>
private static void SalvageDirect()
{
using var _ = F.Context.Enter();
var carried = F.Session.World.Inventory().Where(o => !o.IsContainer && o.WielderId == 0).Select(o => o.Id).Take(3).ToArray();
T.Check(carried.Length == 3, "three carried items to stand in for the tool and the salvage");
if (carried.Length < 3) return;
T.Check(Api->SalvageDirectFn != IntPtr.Zero, "SalvageDirect is filled (RynthAi's HasSalvageDirect)");
var salvage = (delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->SalvageDirectFn;
uint tool = carried[0];
uint* ids = stackalloc uint[] { carried[1], carried[2] };
int m = F.Mark;
T.Eq(salvage(tool, ids, 2), 2, "two items sent");
var acts = F.ActionsSince(m);
T.Check(acts.Count == 1 && acts[0].Type == 0x027D && U32(acts[0].Payload, 0) == tool && U32(acts[0].Payload, 4) == 2
&& U32(acts[0].Payload, 8) == carried[1] && U32(acts[0].Payload, 12) == carried[2],
"it goes out as 0x027D: tool, count, ids");
uint* stranger = stackalloc uint[] { carried[1], 0x80FFFFFE };
m = F.Mark;
T.Eq(salvage(tool, stranger, 2), 0, "an item not carried: refused");
T.Eq(salvage(tool, ids, 0), 0, "no items: refused");
T.Check(F.ActionsSince(m).Count == 0, "nothing sent for the refusals");
}
/// <summary>"Use" on an item in the open corpse picks it up into the main pack (the retail client's behaviour).</summary>
private static void PickUpOnUseInCorpse()
{
using var _ = F.Context.Enter();
var w = F.Session.World;
var item = w.Get(FirstPackItem());
T.Check(item != null, "a pack item to stand in for the loot");
if (item == null) return;
uint wasIn = item.ContainerId, wasOpen = w.OpenContainer;
const uint corpse = 0x80004D5B;
try
{
item.ContainerId = corpse;
w.OpenContainer = corpse;
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item.Id), 1, "UseObject on an item in the open corpse");
var acts = F.ActionsSince(m);
T.Check(acts.Count == 1 && acts[0].Type == 0x0019 && U32(acts[0].Payload, 0) == item.Id && U32(acts[0].Payload, 4) == Me,
"it goes out as PutItemInContainer into the main pack, not a Use (and the busy count is untouched)");
}
finally
{
item.ContainerId = wasIn;
w.OpenContainer = wasOpen;
}
}
private static uint FirstPackItem() => F.Session.World.Inventory().FirstOrDefault(o => !o.IsContainer && o.WielderId == 0 && (o.Desc.ValidLocations ?? 0) == 0)?.Id ?? 0;
private static uint SomeCreature() => F.Session.World.Objects.Values.FirstOrDefault(o => o.IsCreature && o.Id != Me)?.Id ?? 0x80001234;
// ── combat + casts ──────────────────────────────────────────────────────
private static void Combat()
{
uint mob = SomeCreature();
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->ChangeCombatModeFn)(2), 1, "ChangeCombatMode(Melee)");
T.Eq(U32(One(m, 0x0053, "ChangeCombatMode"), 0), 2u, "ChangeCombatMode payload");
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->ChangeCombatModeFn)(3), 0, "ChangeCombatMode(3) refused");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MeleeAttackFn)(mob, 1, 0.75f), 1, "MeleeAttack");
byte[] p = One(m, 0x0008, "MeleeAttack");
T.Check(p.Length == 12 && U32(p, 0) == mob && U32(p, 4) == 1 && Math.Abs(F32(p, 8) - 0.75f) < 1e-6, "MeleeAttack payload (target, height, power)");
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MeleeAttackFn)(0, 1, 0.5f), 0, "MeleeAttack(0) refused");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MissileAttackFn)(mob, 3, 0.25f), 1, "MissileAttack");
p = One(m, 0x000A, "MissileAttack");
T.Check(p.Length == 12 && U32(p, 0) == mob && U32(p, 4) == 3 && Math.Abs(F32(p, 8) - 0.25f) < 1e-6, "MissileAttack payload");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->CancelAttackFn)(), 1, "CancelAttack");
T.Eq(One(m, 0x01B7, "CancelAttack").Length, 0, "CancelAttack has no payload");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->QueryHealthFn)(mob), 1, "QueryHealth");
T.Eq(U32(One(m, 0x01BF, "QueryHealth"), 0), mob, "QueryHealth payload");
// NativeAttack: the selected target, by combat mode.
WorldObject me = F.Session.World.PlayerObject!;
bool had = me.Ints.TryGetValue(40, out int oldMode);
try
{
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(mob);
me.Ints[40] = 1;
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(2, 0.5f), 0, "NativeAttack refused in NonCombat");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCurrentCombatModeFn)(), 1, "GetCurrentCombatMode = NonCombat");
me.Ints[40] = 2;
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(2, 0.5f), 1, "NativeAttack in Melee");
T.Eq(U32(One(m, 0x0008, "NativeAttack (melee)"), 0), mob, "NativeAttack hits the selection");
me.Ints[40] = 4;
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(1, 0.5f), 1, "NativeAttack in Missile");
One(m, 0x000A, "NativeAttack (missile)");
}
finally
{
if (had) me.Ints[40] = oldMode; else me.Ints.Remove(40);
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(0);
}
// Casts: targeted 0x4A (target, spell); untargeted 0x48 (spell).
Drain();
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(mob, 27), 1, "CastSpell on a target");
p = One(m, 0x004A, "CastSpell targeted");
T.Check(p.Length == 8 && U32(p, 0) == mob && U32(p, 4) == 27, "CastTargeted payload (target, spell)");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCastBusyStateFn)(), 1, "cast gate closed while the cast is out");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->IsPlayerReadyFn)(), 0, "not ready while casting");
F.Receive(UseDone(0));
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCastBusyStateFn)(), 0, "cast gate open after UseDone");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->IsPlayerReadyFn)(), 1, "ready again");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(0, 2), 1, "CastSpell untargeted");
T.Eq(U32(One(m, 0x0048, "CastSpell untargeted"), 0), 2u, "CastUntargeted payload");
F.Receive(UseDone(0));
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(mob, 0), 0, "CastSpell(spell 0) refused");
var ev = Drain();
T.Eq(ev.Count(e => e is PluginEvent.BusyIncremented), 2, "a cast counts busy");
T.Eq(ev.Count(e => e is PluginEvent.BusyDecremented), 2, "its UseDone uncounts it");
}
// ── busy count, use-done ────────────────────────────────────────────────
private static void BusyAndUseDone()
{
uint item = FirstPackItem();
T.Check(item != 0, "a pack item to use");
var getBusy = (delegate* unmanaged[Cdecl]<int>)Api->GetBusyStateFn;
var seqFn = (delegate* unmanaged[Cdecl]<int>)Api->GetUseDoneSeqFn;
var lastFn = (delegate* unmanaged[Cdecl]<int*, uint*, int>)Api->GetLastUseDoneFn;
Drain();
T.Eq(getBusy(), 0, "busy 0 at rest");
int seq0 = seqFn();
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item), 1, "UseObject");
T.Eq(U32(One(m, 0x0036, "UseObject"), 0), item, "UseObject payload");
T.Eq(getBusy(), 1, "busy 1 after a use");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->UseObjectOnFn)(item, Me), 1, "UseObjectOn");
byte[] p = One(m, 0x0035, "UseObjectOn");
T.Check(U32(p, 0) == item && U32(p, 4) == Me, "UseObjectOn payload (source, target)");
T.Eq(getBusy(), 2, "busy 2 after two uses");
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(0), 0, "UseObject(0) refused");
F.Receive(UseDone(0));
T.Eq(getBusy(), 1, "UseDone takes one off");
T.Eq(seqFn(), seq0 + 1, "use-done seq +1");
F.Receive(UseDone(0x1D));
T.Eq(getBusy(), 0, "second UseDone: busy 0");
int s; uint e;
T.Eq(lastFn(&s, &e), 1, "GetLastUseDone");
T.Check(s == seq0 + 2 && e == 0x1D, $"last use-done (seq {s}, err 0x{e:X}) = (seq0+2, 0x1D)");
F.Receive(UseDone(0));
T.Eq(getBusy(), 0, "an extra UseDone doesn't go negative");
var ev = Drain();
T.Eq(ev.Count(x => x is PluginEvent.BusyIncremented), 2, "two busy-incremented events");
T.Eq(ev.Count(x => x is PluginEvent.BusyDecremented), 2, "two busy-decremented events (none for the unpaired UseDone)");
// Force reset: one decrement per unit.
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
Drain();
((delegate* unmanaged[Cdecl]<void>)Api->ForceResetBusyCountFn)();
T.Eq(getBusy(), 0, "ForceResetBusyCount -> 0");
T.Eq(Drain().Count(x => x is PluginEvent.BusyDecremented), 3, "three decrements for the three units dropped");
// UseEquippedItem is a UseWithTarget too, and counts.
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->UseEquippedItemFn)(item, Me), 1, "UseEquippedItem");
One(m, 0x0035, "UseEquippedItem");
T.Eq(getBusy(), 1, "UseEquippedItem counts busy");
F.Receive(UseDone(0));
Drain();
}
private static void Errors()
{
var fn = (delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)Api->GetLastWeenieErrorFn;
int s0; uint e, t, o;
fn(&s0, &e, &t, &o);
F.Receive(GameEvent(0x028A, U32s(0x0402)));
int s;
T.Eq(fn(&s, &e, &t, &o), 1, "GetLastWeenieError");
T.Check(s == s0 + 1 && e == 0x402 && t == 0x028A && o == 0, $"WeenieError recorded (seq {s}, 0x{e:X}, evt 0x{t:X}, obj 0x{o:X})");
var body = new List<byte>(U32s(0x051F));
body.AddRange(new byte[] { 4, 0, (byte)'f', (byte)'u', (byte)'l', (byte)'l', 0, 0 });
F.Receive(GameEvent(0x028B, body.ToArray()));
fn(&s, &e, &t, &o);
T.Check(s == s0 + 2 && e == 0x51F && t == 0x028B, "WeenieErrorWithString recorded");
F.Receive(GameEvent(0x00A0, U32s(0x7FFF0010, 0x0029)));
fn(&s, &e, &t, &o);
T.Check(s == s0 + 3 && e == 0x29 && t == 0x00A0 && o == 0x7FFF0010, "InventoryServerSaveFailed recorded with its item");
}
// ── inventory ───────────────────────────────────────────────────────────
private static void Inventory()
{
uint item = FirstPackItem();
uint pack = 0x7FFF0020; // a container id the server would judge; not one of ours to the client
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->MoveItemInternalFn)(item, pack, 3, 1), 1, "MoveItemInternal");
byte[] p = One(m, 0x0019, "MoveItemInternal");
T.Check(U32(p, 0) == item && U32(p, 4) == pack && I32(p, 8) == 3, "MoveItemInternal payload (item, container, slot)");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->MoveItemInternalFn)(item, pack, 0, 0), 0, "MoveItemInternal amount 0 refused");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->PutItemInContainerFn)(item, Me, 5), 1, "PutItemInContainer");
p = One(m, 0x0019, "PutItemInContainer");
T.Check(U32(p, 0) == item && U32(p, 4) == Me && I32(p, 8) == 5, "PutItemInContainer payload");
WorldObject stack = Stub(0x7FFF0030);
stack.StackSize = 25;
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->MoveItemExternalFn)(stack.Id, Me, 10), 1, "MoveItemExternal part of a stack");
p = One(m, 0x0055, "MoveItemExternal (split)");
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me && I32(p, 8) == 0 && I32(p, 12) == 10, "split payload (stack, container, 0, amount)");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->MoveItemExternalFn)(stack.Id, Me, 0), 1, "MoveItemExternal whole");
p = One(m, 0x0019, "MoveItemExternal (whole)");
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me, "whole move payload");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->SplitStackInternalFn)(stack.Id, Me, 2, 7), 1, "SplitStackInternal");
p = One(m, 0x0055, "SplitStackInternal");
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me && I32(p, 8) == 2 && I32(p, 12) == 7, "SplitStackInternal payload");
uint npc = SomeCreature();
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->GiveObjectToFn)(stack.Id, npc, 0), 1, "GiveObjectTo whole stack");
p = One(m, 0x00CD, "GiveObjectTo");
T.Check(U32(p, 0) == npc && U32(p, 4) == stack.Id && I32(p, 8) == 25, "give payload (target, item, whole stack = 25)");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->WieldItemFn)(item, 0x00100000), 1, "WieldItem");
p = One(m, 0x001A, "WieldItem");
T.Check(U32(p, 0) == item && U32(p, 4) == 0x00100000, "wield payload (item, mask)");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->WieldItemFn)(item, 0), 0, "WieldItem mask 0 refused");
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->CloseContainerFn)(0x7FFF0040), 1, "CloseContainer");
T.Eq(U32(One(m, 0x0195, "CloseContainer"), 0), 0x7FFF0040u, "close payload");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetBusyStateFn)(), 0, "inventory sends don't count busy");
T.Eq(((delegate* unmanaged[Cdecl]<uint>)Api->GetGroundContainerIdFn)(), F.Context.GroundContainer, "GetGroundContainerId");
}
private static void Merge()
{
WorldObject a = Stub(0x7FFF0050), b = Stub(0x7FFF0051);
a.StackSize = 30; b.StackSize = 80;
a.Desc.MaxStackSize = 100; b.Desc.MaxStackSize = 100;
var merge = (delegate* unmanaged[Cdecl]<uint, uint, int>)Api->MergeStackInternalFn;
var result = (delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)Api->GetMergeStackResultFn;
int amount, age;
T.Eq(result(a.Id, b.Id, &amount, &age), 0, "no merge result before a merge");
int m = F.Mark;
T.Eq(merge(a.Id, b.Id), 1, "MergeStackInternal");
byte[] p = One(m, 0x0054, "MergeStackInternal");
T.Check(U32(p, 0) == a.Id && U32(p, 4) == b.Id && I32(p, 8) == 20, "merge payload (from, to, what fits = 20)");
T.Eq(result(a.Id, b.Id, &amount, &age), 2, "merge result Sent");
T.Eq(amount, 20, "merge result amount");
b.StackSize = 100;
m = F.Mark;
T.Eq(merge(a.Id, b.Id), 0, "merge onto a full stack refused");
T.Eq(F.ActionsSince(m).Count, 0, "nothing sent for a full target");
T.Eq(result(a.Id, b.Id, &amount, &age), 3, "merge result TargetFull");
}
// ── selection ───────────────────────────────────────────────────────────
private static void Selection()
{
var select = (delegate* unmanaged[Cdecl]<uint, int>)Api->SelectItemFn;
var get = (delegate* unmanaged[Cdecl]<uint>)Api->GetSelectedItemIdFn;
var prev = (delegate* unmanaged[Cdecl]<uint>)Api->GetPreviousSelectedItemIdFn;
uint a = SomeCreature();
WorldObject b = Stub(0x7FFF0060);
F.Now += 1000;
Drain();
uint before = get();
T.Eq(select(a), 1, "SelectItem");
T.Eq(get(), a, "selected");
var ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
T.Check(ev.Count == 1 && ev[0].Current == a && ev[0].Previous == before, "SelectedTargetChange(a, previous)");
T.Eq(select(a), 1, "the same target again within 150 ms: still 1");
T.Eq(Drain().OfType<PluginEvent.SelectedTargetChange>().Count(), 0, "no event for a repeat");
T.Eq(select(b.Id), 1, "select another");
T.Eq(get(), b.Id, "selected b");
T.Eq(prev(), a, "previous = a");
ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
T.Check(ev.Count == 1 && ev[0].Current == b.Id && ev[0].Previous == a, "SelectedTargetChange(b, a)");
// The selected object leaving the world clears the selection.
var del = new byte[8];
BinaryPrimitives.WriteUInt32LittleEndian(del, 0xF747);
BinaryPrimitives.WriteUInt32LittleEndian(del.AsSpan(4), b.Id);
F.Receive(del);
T.Eq(get(), 0u, "selection cleared when its object is deleted");
ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
T.Check(ev.Count == 1 && ev[0].Current == 0 && ev[0].Previous == b.Id, "SelectedTargetChange(0, b)");
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(a), 1, "SetSelectedObjectId");
T.Eq(get(), a, "set selected");
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(0);
Drain();
}
// ── chat ────────────────────────────────────────────────────────────────
private static readonly List<string> ChatBarLines = new();
/// <summary>A plugin's OnChatBarEnter: eats "/ra ..."; "/chain" sends "/ra chained" back through InvokeChatParser.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void FakeChatBarEnter(IntPtr text, int* eat)
{
string s = Marshal.PtrToStringUni(text) ?? "";
ChatBarLines.Add(s);
if (s.StartsWith("/ra ", StringComparison.Ordinal)) *eat = 1;
if (s == "/chain")
{
IntPtr t = Marshal.StringToHGlobalUni("/ra chained");
try { ((delegate* unmanaged[Cdecl]<IntPtr, int>)Fixture.Shared.Api->InvokeChatParserFn)(t); }
finally { Marshal.FreeHGlobal(t); }
*eat = 1;
}
}
private static int Parse(string line)
{
IntPtr t = Marshal.StringToHGlobalUni(line);
try { return ((delegate* unmanaged[Cdecl]<IntPtr, int>)Api->InvokeChatParserFn)(t); }
finally { Marshal.FreeHGlobal(t); }
}
private static int Write(string line, int type)
{
IntPtr t = Marshal.StringToHGlobalUni(line);
try { return ((delegate* unmanaged[Cdecl]<IntPtr, int, int>)Api->WriteToChatFn)(t, type); }
finally { Marshal.FreeHGlobal(t); }
}
private static void Chat()
{
// Without plugins: straight to the server.
int m = F.Mark;
T.Eq(Parse("hello there"), 1, "InvokeChatParser bare text");
byte[] p = One(m, 0x0015, "bare text -> Talk");
int at = 0;
T.Eq(S16(p, ref at), "hello there", "Talk text");
m = F.Mark;
T.Eq(Parse("/tell Bob Smith, meet at the lifestone"), 1, "/tell");
p = One(m, 0x005D, "/tell -> Tell");
at = 0;
string msg = S16(p, ref at), target = S16(p, ref at);
T.Check(msg == "meet at the lifestone" && target == "Bob Smith", $"Tell payload (message '{msg}', target '{target}')");
m = F.Mark;
T.Eq(Parse("/myquests"), 1, "an unknown slash command");
at = 0;
T.Eq(S16(One(m, 0x0015, "/myquests -> Talk"), ref at), "@myquests", "sent as an @ server command");
m = F.Mark;
T.Eq(Parse("/f anyone?"), 0, "/f refused headless");
T.Eq(F.ActionsSince(m).Count, 0, "nothing sent for /f");
m = F.Mark;
T.Eq(Parse("/e waves"), 1, "/e");
One(m, 0x01DF, "/e -> Emote");
// With a plugin: offered first, eaten lines stay home.
var host = new PluginHost(F.Context);
try
{
var plugin = new PluginHost.Plugin
{
Path = "fake",
Name = "FakeChat",
Exports = new Dictionary<string, IntPtr>
{
["RynthPluginOnChatBarEnter"] = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int*, void>)&FakeChatBarEnter,
},
Initialized = true,
};
var list = (List<PluginHost.Plugin>)typeof(PluginHost).GetField("_plugins", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(host)!;
list.Add(plugin);
ChatBarLines.Clear();
m = F.Mark;
T.Eq(Parse("/ra start"), 1, "a line a plugin eats");
T.Check(ChatBarLines.SequenceEqual(new[] { "/ra start" }), "offered to the plugin's OnChatBarEnter");
T.Eq(F.ActionsSince(m).Count, 0, "an eaten line isn't sent");
m = F.Mark;
T.Eq(Parse("good morning"), 1, "a line no plugin eats");
One(m, 0x0015, "not eaten -> Talk");
ChatBarLines.Clear();
m = F.Mark;
T.Eq(Parse("/chain"), 1, "a plugin chaining InvokeChatParser from its handler");
T.Check(ChatBarLines.SequenceEqual(new[] { "/chain" }), "the chained line isn't offered again (no loop)");
at = 0;
T.Eq(S16(One(m, 0x0015, "chained line -> Talk"), ref at), "@ra chained", "the chained line goes to the server");
}
finally
{
F.Context.Plugins = null;
}
// WriteToChat: logged and echoed as chat-window text, one line per 100 ms.
F.Now += 1000;
Drain();
var logged = new List<string>();
Action<string> sink = F.Context.LogSink;
F.Context.LogSink = logged.Add;
try
{
T.Eq(Write("RynthAi: buffing", 5), 1, "WriteToChat");
T.Eq(Write("too soon", 5), 0, "a second line within 100 ms is dropped");
F.Now += 100;
T.Eq(Write("bad\u0001line", 5), 0, "control characters refused");
T.Eq(Write("later", 0x16), 1, "after 100 ms");
}
finally { F.Context.LogSink = sink; }
T.Check(logged.Any(l => l.Contains("RynthAi: buffing")), "WriteToChat logged");
var echo = Drain().OfType<PluginEvent.ChatWindowText>().ToList();
T.Check(echo.Count == 2 && echo[0].Text == "RynthAi: buffing" && echo[0].ChatType == 5 && echo[1].ChatType == 0x16,
"echoed to the plugins as chat-window text");
}
// ── confirmations, jumps ────────────────────────────────────────────────
private static void Confirmation()
{
var arm = (delegate* unmanaged[Cdecl]<uint, int, int, int>)Api->ArmConfirmationFn;
var last = (delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)Api->GetLastConfirmationFn;
T.Eq(arm(0, 50, 1000), -3, "ArmConfirmation bad type");
T.Eq(arm(5, 50, 10_000), 1, "ArmConfirmation(craft, 50%)");
int m = F.Mark;
F.Context.OnConfirmationRequest(5, 0x1234, "You determine that you have a 38 percent chance to succeed.");
byte[] p = One(m, 0x0275, "declined prompt answered");
T.Check(U32(p, 0) == 5 && U32(p, 4) == 0x1234 && U32(p, 8) == 0, "ConfirmationResponse (type, context, no)");
uint type, ctx; int pct, outcome, age;
int seq = last(&type, &ctx, &pct, &outcome, &age);
T.Check(seq >= 1 && type == 5 && ctx == 0x1234 && pct == 38 && outcome == 3, $"last confirmation (seq {seq}, pct {pct}, outcome {outcome})");
m = F.Mark;
F.Context.OnConfirmationRequest(5, 0x1235, "You determine that you have a 90 percent chance to succeed.");
T.Eq(F.ActionsSince(m).Count, 0, "one-shot: an unarmed prompt isn't answered");
last(&type, &ctx, &pct, &outcome, &age);
T.Eq(outcome, 1, "unarmed prompt: Shown");
arm(5, 50, 10_000);
m = F.Mark;
F.Context.OnConfirmationRequest(5, 0x1236, "You determine that you have a 90 percent chance to succeed.");
T.Eq(U32(One(m, 0x0275, "accepted prompt answered"), 8), 1u, "answered yes");
}
private static void Jumps()
{
int m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->TapJumpFn)(), 1, "TapJump");
byte[] p = One(m, 0xF61B, "TapJump -> Jump");
T.Check(p.Length >= 16 && F32(p, 0) == 0f && F32(p, 12) > 0f, "tap jump: extent 0, upward velocity");
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->CommenceJumpFn)(), 1, "CommenceJump");
F.Now += 500;
m = F.Mark;
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->DoJumpFn)(1), 1, "DoJump");
p = One(m, 0xF61B, "DoJump -> Jump");
T.Check(Math.Abs(F32(p, 0) - 0.5f) < 0.01f, $"half a second's charge = extent 0.5 (got {F32(p, 0)})");
}
// ── driving ─────────────────────────────────────────────────────────────
private static WorldPosition Pos => F.Session.World.PlayerObject!.Position!.Value;
private static (float X, float Y) Global(WorldPosition p) => (p.X + (p.Cell >> 24) * 192f, p.Y + ((p.Cell >> 16) & 0xFF) * 192f);
private static List<uint> Types(int mark) => F.ActionsSince(mark).Select(a => a.Type).ToList();
private static void Drive()
{
var autorun = (delegate* unmanaged[Cdecl]<int, int>)Api->SetAutoRunFn;
var turnTo = (delegate* unmanaged[Cdecl]<float, int>)Api->TurnToHeadingFn;
var stop = (delegate* unmanaged[Cdecl]<int>)Api->StopCompletelyFn;
var setMotion = (delegate* unmanaged[Cdecl]<uint, int, int>)Api->SetMotionFn;
T.Check(F.Session.World.PlayerObject?.Position != null, "player has a position");
if (F.Session.World.PlayerObject?.Position == null) return;
if (F.Session.Moving) F.Session.StopMoving();
// Autorun east for 3 s.
var start = Global(Pos);
int m = F.Mark;
T.Eq(autorun(1), 1, "SetAutoRun(1)");
T.Eq(turnTo(90f), 1, "TurnToHeading(90)");
var sent = F.ActionsSince(m);
T.Check(sent.Count >= 1 && sent[0].Type == 0xF61C, "autorun: MoveToState first");
if (sent.Count >= 1 && sent[0].Type == 0xF61C)
{
byte[] mts = sent[0].Payload;
T.Check(U32(mts, 0) == 0x0D && U32(mts, 4) == 2 && U32(mts, 8) == MotionCommand.WalkForward && U32(mts, 12) == 2,
$"MoveToState = run forward (flags 0x{U32(mts, 0):X})");
}
Advance(3000);
var end = Global(Pos);
float dx = end.X - start.X, dy = end.Y - start.Y;
float speed = F.Session.MoveSpeed;
T.Info($"3 s of autorun at {speed:F2} m/s moved ({dx:F2}, {dy:F2}); heading {ClientSession.HeadingDegrees(Pos):F1}");
T.Check(dx > speed * 2.5f && dx < speed * 3.3f, $"moved east about 3 s x {speed:F2} m/s (dx {dx:F2})");
T.Check(Math.Abs(dy) < 0.5f, $"not north/south (dy {dy:F2})");
T.Check(Math.Abs(ClientSession.HeadingDegrees(Pos) - 90f) < 0.5f, "facing east");
var types = Types(m);
int reports = types.Count(t => t == 0xF753);
T.Check(reports >= 5 && reports <= 9, $"AutonomousPosition about every 0.5 s ({reports} in 3 s)");
T.Eq(types.Count(t => t == 0xF61C), 1, "one MoveToState while the keys didn't change");
var lastReport = F.ActionsSince(m).Last(a => a.Type == 0xF753).Payload;
T.Check(U32(lastReport, 0) == Pos.Cell && Math.Abs(F32(lastReport, 4) - Pos.X) <= speed * 0.6f, "the reports carry the new position");
// Stop.
m = F.Mark;
T.Eq(stop(), 1, "StopCompletely");
sent = F.ActionsSince(m);
T.Check(sent.Count == 2 && sent[0].Type == 0xF61C && U32(sent[0].Payload, 0) == 0 && sent[1].Type == 0xF753,
$"stop: MoveToState (no keys) + position (got {string.Join(", ", sent.Select(s => $"0x{s.Type:X4}"))})");
var stopped = Global(Pos);
m = F.Mark;
Advance(1000);
var after = Global(Pos);
T.Check(Math.Abs(after.X - stopped.X) < 0.01f && Math.Abs(after.Y - stopped.Y) < 0.01f, "stays put after the stop");
T.Eq(Types(m).Count(t => t is 0xF61C or 0xF753), 0, "nothing sent standing still");
T.Eq(autorun(0), 1, "SetAutoRun(0) when already off");
T.Eq(F.ActionsSince(m).Count, 0, "an unchanged autorun sends nothing");
// Turning in place: SetMotion(TurnRight) for 1 s turns about 135 degrees.
float h0 = ClientSession.HeadingDegrees(Pos);
m = F.Mark;
T.Eq(setMotion(TurnRight, 1), 1, "SetMotion(TurnRight, on)");
Advance(1000);
T.Eq(setMotion(TurnRight, 0), 1, "SetMotion(TurnRight, off)");
float turned = (ClientSession.HeadingDegrees(Pos) - h0 + 360f) % 360f;
T.Check(turned > 110f && turned < 160f, $"turned right about 135 deg in 1 s (got {turned:F1})");
var turnSent = F.ActionsSince(m);
T.Check(turnSent.Count >= 2 && turnSent[0].Type == 0xF61C && (U32(turnSent[0].Payload, 0) & 0x100) != 0, "turn: MoveToState with the turn command");
T.Check(turnSent.Last(a => a.Type == 0xF61C).Payload is var lp && U32(lp, 0) == 0, "turn released: MoveToState stop");
var turnedAt = Global(Pos);
T.Check(Math.Abs(turnedAt.X - stopped.X) < 0.01f, "turning in place doesn't move");
// TurnToHeading standing still: the heading goes out with the next step.
m = F.Mark;
turnTo(180f);
T.Eq(F.ActionsSince(m).Count, 0, "TurnToHeading standing still: nothing yet");
Advance(200);
T.Check(Types(m).Contains(0xF753u), "the new heading is reported within a step");
T.Check(Math.Abs(ClientSession.HeadingDegrees(Pos) - 180f) < 0.5f, "facing south");
// Backwards (DoMovement / StopMovement) moves north while facing south, slower.
var b0 = Global(Pos);
T.Eq(((delegate* unmanaged[Cdecl]<uint, float, int, int>)Api->DoMovementFn)(WalkBackwards, 1f, 1), 1, "DoMovement(WalkBackwards)");
Advance(1000);
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->StopMovementFn)(WalkBackwards, 1), 1, "StopMovement(WalkBackwards)");
var b1 = Global(Pos);
T.Check(b1.Y - b0.Y > speed * 0.4f && b1.Y - b0.Y < speed * 0.8f, $"backwards: north at ~0.65 x speed (dy {b1.Y - b0.Y:F2})");
T.Check(!F.Session.Driving, "no keys held after the stop");
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->SetMotionFn)(0x10000057, 1), 0, "an unsupported motion (an emote) refused");
}
private static void DriveAndWalks()
{
var autorun = (delegate* unmanaged[Cdecl]<int, int>)Api->SetAutoRunFn;
var stop = (delegate* unmanaged[Cdecl]<int>)Api->StopCompletelyFn;
ClientSession s = F.Session;
if (s.World.PlayerObject?.Position == null) return;
// A planned walk that starts while driving ends the drive (its stop first, then the walk's run).
autorun(1);
Advance(300);
WorldPosition here = Pos;
WorldPosition goal = here with { X = here.X + (here.X < 96 ? 20 : -20) };
int m = F.Mark;
s.WalkTo(goal);
Advance(200);
T.Check(!s.Driving && s.Moving, "WalkTo takes over from the drive");
var mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
T.Check(mts.Count == 2 && mts[0] == 0 && mts[1] == 0x0D, $"drive stop, then the walk's run ({string.Join(", ", mts.Select(x => $"0x{x:X}"))})");
// A drive key cancels the planned walk.
m = F.Mark;
T.Eq(autorun(1), 1, "SetAutoRun(1) during a walk");
T.Check(!s.Moving && s.Driving, "the drive cancels the walk");
mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
T.Check(mts.Count == 1 && mts[0] == 0x0D, $"just the drive's run goes out ({string.Join(", ", mts.Select(x => $"0x{x:X}"))})");
stop();
// The server's move-to pauses the drive: no MoveToState while it lasts, the keys go out once it ends.
MethodInfo begin = typeof(ClientSession).GetMethod("BeginMove", BindingFlags.NonPublic | BindingFlags.Instance)!;
begin.Invoke(s, new object[] { 0u, new[] { Pos with { X = Pos.X + (Pos.X < 96 ? 30 : -30) } }, 0.3f, 15_000L, true });
T.Check(s.ServerMoving, "server move-to in progress");
m = F.Mark;
T.Eq(autorun(1), 1, "SetAutoRun(1) during the server's move-to");
Advance(600);
var during = Types(m);
T.Eq(during.Count(t => t == 0xF61C), 0, "no MoveToState during the server's move-to");
T.Check(during.Contains(0xF753u), "the server's move-to still reports positions");
m = F.Mark;
s.StopMoving();
Advance(200);
T.Check(!s.Moving && s.Driving, "move-to over, the drive resumes");
mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
T.Check(mts.Count == 1 && mts[0] == 0x0D, "the held keys go out once the move-to ends");
stop();
Advance(100);
T.Check(!s.Driving && !s.Moving, "all stopped");
}
}

View file

@ -0,0 +1,27 @@
// ============================================================================
// CoreTests - the host's core slots (version, player id, names, screen mode).
// ============================================================================
using System.Runtime.InteropServices;
namespace HeadlessHostTests;
internal static unsafe class CoreTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("core", Run, order: 0);
private static void Run()
{
Fixture f = Fixture.Shared;
using var _ = f.Context.Enter();
T.Eq(f.Api->Version, 92u, "API version");
T.Check(f.Api->ImGuiContext == IntPtr.Zero && f.Api->GameHwnd == IntPtr.Zero, "no ImGui, no window");
T.Eq(((delegate* unmanaged[Cdecl]<uint>)f.Api->GetPlayerIdFn)(), 0x50000001u, "GetPlayerId while in the world");
T.Eq(Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)f.Api->GetAccountNameFn)()), Fixture.Account, "account name");
T.Eq(Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)f.Api->GetWorldNameFn)()), "RynthAce", "world name");
int mode = 0;
T.Check(((delegate* unmanaged[Cdecl]<int*, int>)f.Api->GetScreenModeFn)(&mode) == 1 && mode == 0x10000008, "screen mode: in world");
T.Eq(((delegate* unmanaged[Cdecl]<uint>)f.Api->GetClientHookFlagsFn)(), 0x1FFFFu, "client hook flags");
}
}

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the headless plugin host's API (src/RynthCore.Headless/Host): a session
replayed from a captured ACE session (tools/HeadlessNetTests/Captures/ace-p1-session.txt)
gives a real world model; the API table is built and its functions are called through the
same function pointers plugins use; the game actions they send are decoded and checked.
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>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>HeadlessHostTests</RootNamespace>
<AssemblyName>HeadlessHostTests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<!-- Left out of the public source snapshots (it holds a live login): the tests then skip (Program.Main). -->
<None Include="..\HeadlessNetTests\Captures\ace-p1-session.txt" Link="Captures\ace-p1-session.txt" CopyToOutputDirectory="PreserveNewest"
Condition="Exists('..\HeadlessNetTests\Captures\ace-p1-session.txt')" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Headless\RynthCore.Headless.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,475 @@
// ============================================================================
// ObjectsTests - the objects / properties slots (HostApi.Objects.cs) against the replayed
// session: names, positions, types, flags, every property kind with the CreateObject
// header fallbacks, ownership, container contents and counts, live ids, identify
// (request, appraisal data, spell book, creature vitals from a synthetic reply), door
// motion, server age, ghost removal, the v84 record, container order, wielded items.
// ============================================================================
using System.Buffers.Binary;
using System.Runtime.InteropServices;
using RynthCore.Headless.Host;
using RynthCore.Headless.Net;
using RynthCore.Headless.World;
using RynthCore.PluginSdk;
namespace HeadlessHostTests;
internal static unsafe class ObjectsTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("objects", Run, order: 10);
private const uint Player = 0x50000001;
private static Fixture F => Fixture.Shared;
private static RynthCoreApiNative* Api => F.Api;
private static WorldState W => F.Session.World;
private static WorldObject First(string name) => W.Objects.Values.Where(o => o.Name == name).OrderBy(o => o.Id).First();
// ── the slots, called through the table as plugins do ──────────────────
private static string? Name(uint id) => Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<uint, IntPtr>)Api->GetObjectNameFn)(id));
private static bool Int(uint id, uint stype, out int v)
{
int x = 0;
bool ok = ((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectIntPropertyFn)(id, stype, &x) != 0;
v = x;
return ok;
}
private static int? IntOrNull(uint id, uint stype) => Int(id, stype, out int v) ? v : null;
private static double? Dbl(uint id, uint stype)
{
double x = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, double*, int>)Api->GetObjectDoublePropertyFn)(id, stype, &x) != 0 ? x : null;
}
private static long? Quad(uint id, uint stype)
{
long x = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, long*, int>)Api->GetObjectQuadPropertyFn)(id, stype, &x) != 0 ? x : null;
}
private static bool? Bool(uint id, uint stype)
{
int x = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectBoolPropertyFn)(id, stype, &x) != 0 ? x != 0 : null;
}
private static string? Str(uint id, uint stype) => Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<uint, uint, IntPtr>)Api->GetObjectStringPropertyFn)(id, stype));
private static uint? Did(uint id, uint stype)
{
uint x = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)Api->GetObjectDataIdPropertyFn)(id, stype, &x) != 0 ? x : null;
}
private static uint? Iid(uint id, uint stype)
{
uint x = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)Api->GetObjectInstanceIdPropertyFn)(id, stype, &x) != 0 ? x : null;
}
private static uint[] Contents(uint container, int max = 512)
{
uint[] buf = new uint[max];
fixed (uint* p = buf)
{
int n = ((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetContainerContentsFn)(container, p, max);
return buf.Take(n).ToArray();
}
}
private static int SpellIds(uint id, uint[] buf)
{
fixed (uint* p = buf)
return ((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetObjectSpellIdsFn)(id, p, buf.Length);
}
private static int Call1(IntPtr fn, uint id) => ((delegate* unmanaged[Cdecl]<uint, int>)fn)(id);
private static void Run()
{
using var _ = F.Context.Enter();
Identity();
Positions();
Properties();
Ownership();
Identify();
Physics();
Removal();
Record();
OrderAndWielded();
}
private static void Identity()
{
// The captured character's own name, from the server's character list (no "+" admin prefix).
string listed = F.Session.Characters.FirstOrDefault(c => c.Id == Player).Name?.TrimStart('+') ?? "";
T.Check(listed.Length > 0, "the character list names the player");
T.Eq(Name(Player), listed, "GetObjectName: the player");
WorldObject boots = First("Viamontian Laced Boots");
T.Eq(Name(boots.Id), "Viamontian Laced Boots", "GetObjectName: an item in the pack");
T.Check(Name(0) == null && Name(0x7FFFFFF0) == null, "GetObjectName: 0 / unknown id answer null");
WorldObject sack = First("Sack");
uint flags = 0;
var itemType = (delegate* unmanaged[Cdecl]<uint, uint*, int>)Api->GetItemTypeFn;
T.Check(itemType(sack.Id, &flags) == 1 && flags == 0x200, $"GetItemType: Sack = Container 0x200 (got 0x{flags:X})");
T.Check(itemType(Player, &flags) == 1 && flags == 0x10, "GetItemType: the player = Creature");
T.Eq(itemType(0x7FFFFFF0, &flags), 0, "GetItemType: unknown id");
T.Eq(itemType(sack.Id, null), 0, "GetItemType: null out-pointer");
var bitfield = (delegate* unmanaged[Cdecl]<uint, uint>)Api->GetObjectBitfieldFn;
var wcid = (delegate* unmanaged[Cdecl]<uint, uint>)Api->GetObjectWcidFn;
T.Eq(bitfield(sack.Id), 0x13u, "GetObjectBitfield: Sack (Openable|Inscribable|Requires... 0x13)");
T.Eq(wcid(sack.Id), 166u, "GetObjectWcid: Sack");
T.Eq(wcid(0x7FFFFFF0), 0u, "GetObjectWcid: unknown id");
WorldObject slasher = First("Olthoi Slasher");
WorldObject shop = First("Shopkeeper Renald the Elder");
T.Eq(Call1(Api->ObjectIsAttackableFn, slasher.Id), 1, "ObjectIsAttackable: a monster (Attackable bit)");
T.Eq(Call1(Api->ObjectIsAttackableFn, shop.Id), 0, "ObjectIsAttackable: a vendor NPC");
T.Eq(Call1(Api->ObjectIsAttackableFn, Player), 0, "ObjectIsAttackable: never the player");
T.Eq(Call1(Api->ObjectIsAttackableFn, sack.Id), 0, "ObjectIsAttackable: an item");
T.Eq(Call1(Api->ObjectIsAttackableFn, 0x7FFFFFF0), 0, "ObjectIsAttackable: unknown id");
T.Eq(Call1(Api->ObjectIsAttackableFn, First("Corpse of Drudge Skulker").Id), 0, "ObjectIsAttackable: a corpse");
T.Eq(Call1(Api->ObjectIsAttackableFn, First("Trade Note (250,000)").Id), 0, "ObjectIsAttackable: an item with the Attackable bit");
// Players: only PK vs PK (or PK-lite vs PK-lite).
static WorldObject Pc(uint id, uint bf) => new(id) { Desc = new RynthCore.Headless.Messages.ObjectCreateData { Id = id, ItemType = 0x10, DescriptionFlags = bf } };
T.Check(RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x38), Pc(1, 0x38)), "attackable: PK vs PK");
T.Check(!RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x38), Pc(1, 0x18)), "not attackable: PK vs non-PK");
T.Check(!RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x18), Pc(1, 0x18)), "not attackable: non-PK players");
T.Check(RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x2000018), Pc(1, 0x2000018)), "attackable: PK-lite vs PK-lite");
// Live ids: every created object, ascending; the total even when the buffer is short.
int created = W.Objects.Values.Count(o => o.Desc.Id != 0);
var live = (delegate* unmanaged[Cdecl]<uint*, int, int>)Api->GetLiveObjectIdsFn;
uint[] ids = new uint[1024];
int total;
fixed (uint* p = ids) total = live(p, ids.Length);
T.Eq(total, created, "GetLiveObjectIds: the count of created objects");
T.Check(ids.Take(total).Contains(Player) && ids.Take(total).Contains(sack.Id), "GetLiveObjectIds: player and pack items listed");
T.Check(ids.Take(total).SequenceEqual(ids.Take(total).OrderBy(x => x)), "GetLiveObjectIds: ascending");
uint* small = stackalloc uint[3];
T.Eq(live(small, 3), created, "GetLiveObjectIds: the total with a short buffer");
T.Eq(live(null, 0), created, "GetLiveObjectIds: count only");
}
private static void Positions()
{
var pos = (delegate* unmanaged[Cdecl]<uint, uint*, float*, float*, float*, int>)Api->GetObjectPositionFn;
uint cell = 0; float x = 0, y = 0, z = 0;
WorldObject me = W.PlayerObject!;
T.Check(pos(Player, &cell, &x, &y, &z) == 1 && cell == me.Position!.Value.Cell && x == me.Position.Value.X && z == me.Position.Value.Z,
$"GetObjectPosition: the player (cell 0x{cell:X8} {x:F1},{y:F1},{z:F1})");
WorldObject slasher = First("Olthoi Slasher");
T.Check(pos(slasher.Id, &cell, &x, &y, &z) == 1 && cell == slasher.Position!.Value.Cell, "GetObjectPosition: a monster");
cell = 0xDEAD;
T.Check(pos(First("Viamontian Laced Boots").Id, &cell, &x, &y, &z) == 0 && cell == 0xDEAD, "GetObjectPosition: a pack item has none (out untouched)");
T.Eq(pos(Player, null, &x, &y, &z), 0, "GetObjectPosition: null out-pointer");
T.Eq(pos(0x7FFFFFF0, &cell, &x, &y, &z), 0, "GetObjectPosition: unknown id");
}
private static void Properties()
{
// Header fallbacks (never identified): a stack's size, value, burden, type.
WorldObject note = First("Trade Note (250,000)");
T.Eq(IntOrNull(note.Id, 12), 215, "int 12 StackSize: Trade Notes from CreateObject");
T.Eq(IntOrNull(note.Id, 19), 53750000, "int 19 Value");
T.Eq(IntOrNull(note.Id, 5), 215, "int 5 EncumbranceVal (burden)");
T.Eq(IntOrNull(note.Id, 1), 0x40000, "int 1 ItemType");
T.Eq(IntOrNull(note.Id, 11), (int?)note.Desc.MaxStackSize, "int 11 MaxStackSize");
WorldObject pyreals = W.Objects.Values.First(o => o.Name == "Pyreal" && o.ContainerId != 0);
T.Eq(IntOrNull(pyreals.Id, 12), (int)pyreals.StackSize, $"int 12: the Pyreal stack in a pack ({pyreals.StackSize})");
WorldObject sack = First("Sack");
T.Eq(IntOrNull(sack.Id, 6), 24, "int 6 ItemsCapacity: Sack");
T.Eq(IntOrNull(sack.Id, 12), null, "int 12 on a non-stackable answers nothing");
T.Eq(IntOrNull(sack.Id, 9999), null, "unknown int stype");
WorldObject coat = First("Academy Coat");
T.Eq(IntOrNull(coat.Id, 10), 0x1E00, "int 10 CurrentWieldedLocation: the worn Academy Coat");
T.Eq(IntOrNull(coat.Id, 9), (int?)coat.Desc.ValidLocations, "int 9 ValidLocations");
T.Eq(IntOrNull(First("Viamontian Laced Boots").Id, 10), null, "int 10 on an item in a pack answers nothing");
// The player's own tables (PlayerDescription): every int, int64 and bool as the world model has it.
WorldObject me = W.PlayerObject!;
T.Check(me.Ints.Count > 0 && me.Ints.All(kv => IntOrNull(Player, kv.Key) == kv.Value), $"player ints from PlayerDescription ({me.Ints.Count})");
T.Check(me.Int64s.All(kv => Quad(Player, kv.Key) == kv.Value), $"player int64s ({me.Int64s.Count})");
T.Check(me.Bools.All(kv => Bool(Player, kv.Key) == kv.Value), $"player bools ({me.Bools.Count})");
T.Check(me.Strings.All(kv => Str(Player, kv.Key) == kv.Value), $"player strings ({me.Strings.Count})");
T.Eq(Quad(Player, 0x7FFF), null, "unknown quad stype");
// Identify-merged tables (the boots' replayed identify).
WorldObject boots = First("Viamontian Laced Boots");
T.Check(boots.Ints.Count > 0 && boots.Ints.Where(kv => kv.Key is not (10 or 12)).All(kv => IntOrNull(boots.Id, kv.Key) == kv.Value),
$"boots: identify ints ({boots.Ints.Count})");
T.Check(boots.Floats.All(kv => Dbl(boots.Id, kv.Key) == kv.Value), $"boots: identify floats ({boots.Floats.Count})");
T.Check(boots.Strings.All(kv => Str(boots.Id, kv.Key) == kv.Value), $"boots: identify strings ({boots.Strings.Count})");
// Strings and doubles from the header.
T.Eq(Str(sack.Id, 1), "Sack", "string 1 Name from the header");
T.Eq(Str(sack.Id, 9999), null, "unknown string stype");
WorldObject? withRadius = W.Objects.Values.FirstOrDefault(o => o.Desc.UseRadius is > 0f && !o.Floats.ContainsKey(54));
if (withRadius != null) T.Eq(Dbl(withRadius.Id, 54), (double)withRadius.Desc.UseRadius!.Value, $"double 54 UseRadius ({withRadius.Name})");
else T.Info("no object with a UseRadius in the capture");
WorldObject? worked = W.Objects.Values.FirstOrDefault(o => o.Desc.Workmanship is > 0f);
if (worked != null)
{
T.Eq(Dbl(worked.Id, 280), (double)worked.Desc.Workmanship!.Value, $"double 280 workmanship ({worked.Name})");
if (!worked.Ints.ContainsKey(105)) T.Eq(IntOrNull(worked.Id, 105), (int)MathF.Round(worked.Desc.Workmanship.Value), "int 105 ItemWorkmanship from the header");
}
else T.Info("no object with a workmanship in the capture");
T.Eq(Dbl(sack.Id, 9999), null, "unknown double stype");
// Data ids and instance ids.
T.Eq(Did(sack.Id, 8), sack.Desc.Icon, "data id 8 Icon from the header");
T.Check((sack.Desc.Icon & 0xFF000000) == 0x06000000, "the icon is a full 0x06 data id");
T.Eq(Did(sack.Id, 9999), null, "unknown data id stype");
T.Eq(Iid(boots.Id, 2), Player, "instance id 2 Container: boots in the main pack");
T.Eq(Iid(coat.Id, 3), Player, "instance id 3 Wielder: the worn coat");
T.Eq(Iid(coat.Id, 2), null, "instance id 2 of a wielded item answers nothing");
T.Eq(Iid(0x7FFFFFF0, 2), null, "instance id of an unknown object");
// Null out-pointers.
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectIntPropertyFn)(note.Id, 12, null), 0, "int: null out-pointer");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, double*, int>)Api->GetObjectDoublePropertyFn)(note.Id, 54, null), 0, "double: null out-pointer");
}
private static void Ownership()
{
WorldObject coat = First("Academy Coat");
uint c = 1, w = 1, l = 1;
var own = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)Api->GetObjectOwnershipInfoFn;
T.Check(own(coat.Id, &c, &w, &l) == 1 && c == 0 && w == Player && l == 0x1E00, $"GetObjectOwnershipInfo: worn coat ({c:X8},{w:X8},0x{l:X})");
WorldObject boots = First("Viamontian Laced Boots");
T.Check(own(boots.Id, &c, &w, &l) == 1 && c == Player && w == 0 && l == 0, "GetObjectOwnershipInfo: boots in the main pack");
T.Eq(own(boots.Id, null, &w, &l), 0, "GetObjectOwnershipInfo: null out-pointer");
T.Eq(own(0x7FFFFFF0, &c, &w, &l), 0, "GetObjectOwnershipInfo: unknown id");
var wi = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)Api->GetObjectWielderInfoFn;
T.Check(wi(coat.Id, &w, &l) == 1 && w == Player && l == 0x1E00, "GetObjectWielderInfo: worn coat");
// A pack's contents: what the world model has in it, ascending.
WorldObject sack = First("Sack");
uint[] inSack = Contents(sack.Id);
uint[] expected = W.Objects.Values.Where(o => o.ContainerId == sack.Id || o.WielderId == sack.Id).Select(o => o.Id).OrderBy(x => x).ToArray();
T.Check(inSack.Length > 0 && inSack.SequenceEqual(expected), $"GetContainerContents: Sack holds {inSack.Length}");
// The player: main pack + side packs/foci (PlayerState) + what she wields.
PlayerState p = W.Player;
uint[] mine = Contents(Player);
var fromState = p.MainPackOrder.Concat(p.SidePackOrder).Concat(p.EquippedItems.Keys).OrderBy(x => x).ToArray();
T.Check(mine.SequenceEqual(fromState), $"GetContainerContents: the player = main pack {p.MainPackOrder.Count} + packs {p.SidePackOrder.Count} + wielded {p.EquippedItems.Count} (got {mine.Length})");
uint[] three = Contents(Player, 3);
T.Check(three.SequenceEqual(fromState.Take(3)), "GetContainerContents: a short buffer gets the lowest ids");
T.Eq(Contents(0x7FFFFFF0).Length, 0, "GetContainerContents: unknown container");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetContainerContentsFn)(Player, null, 10), 0, "GetContainerContents: null buffer");
T.Eq(Call1(Api->GetNumContainedItemsFn, Player), p.MainPackOrder.Count, "GetNumContainedItems: the player's main pack");
T.Eq(Call1(Api->GetNumContainedContainersFn, Player), 7, "GetNumContainedContainers: 3 sacks + 4 foci");
int sackItems = W.Objects.Values.Count(o => o.ContainerId == sack.Id);
T.Eq(Call1(Api->GetNumContainedItemsFn, sack.Id), sackItems, "GetNumContainedItems: a sack");
T.Eq(Call1(Api->GetNumContainedContainersFn, sack.Id), 0, "GetNumContainedContainers: a sack holds no packs");
T.Eq(Call1(Api->GetNumContainedItemsFn, 0x7FFFFFF0), -1, "GetNumContainedItems: unknown id");
}
// An identify reply (game event 0xC9) for a monster: one int, a two-spell book, a creature profile with attributes.
private static byte[] IdentifyReply(uint id, uint level, uint[] spells, uint hp, uint hpMax, uint st, uint stMax, uint mp, uint mpMax)
{
var w = new WireWriter(128);
w.U32(0xF7B0).U32(Player).U32(9999).U32(0xC9);
w.U32(id).U32(0x0001 | 0x0010 | 0x0100).U32(1);
w.U16(1).U16(8).U32(25).U32(level); // int table: Level
w.U32((uint)spells.Length);
foreach (uint s in spells) w.U32(s);
w.U32(0x8).U32(hp).U32(hpMax); // creature profile, ShowAttributes
for (int i = 0; i < 6; i++) w.U32(50);
w.U32(st).U32(mp).U32(stMax).U32(mpMax);
return w.ToArray();
}
private static byte[] UpdateHealth(uint id, float ratio)
=> new WireWriter(32).U32(0xF7B0).U32(Player).U32(10000).U32(0x01C0).U32(id).F32(ratio).ToArray();
private static void Identify()
{
WorldObject boots = First("Viamontian Laced Boots");
WorldObject slasher = First("Olthoi Slasher");
// RequestId sends IdentifyObject (0xC8) with the id.
int mark = F.Mark;
T.Eq(Call1(Api->RequestIdFn, slasher.Id), 1, "RequestId: sent");
var sent = F.ActionsSince(mark);
T.Check(sent.Count == 1 && sent[0].Type == 0xC8 && BinaryPrimitives.ReadUInt32LittleEndian(sent[0].Payload) == slasher.Id,
$"RequestId: game action 0xC8 with the id ({string.Join(",", sent.Select(a => $"0x{a.Type:X}"))})");
T.Eq(Call1(Api->RequestIdFn, 0), 0, "RequestId: id 0 refused");
// The replayed identify of the boots.
T.Eq(Call1(Api->HasAppraisalDataFn, boots.Id), 1, "HasAppraisalData: the identified boots");
T.Eq(Call1(Api->HasAppraisalDataFn, slasher.Id), 0, "HasAppraisalData: a monster not identified yet");
var lastId = (delegate* unmanaged[Cdecl]<uint, long>)Api->GetLastIdTimeFn;
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
T.Check(Math.Abs(lastId(boots.Id) - now) < 600, "GetLastIdTime: the boots (Unix seconds)");
T.Eq(lastId(slasher.Id), 0L, "GetLastIdTime: never identified");
uint[] buf = new uint[16];
int n = SpellIds(boots.Id, buf);
T.Check(n == boots.Spells.Count && n > 0 && buf.Take(n).SequenceEqual(boots.Spells), $"GetObjectSpellIds: the boots' spell book ({n}: {string.Join(",", buf.Take(Math.Max(n, 0)))})");
uint[] one = new uint[1];
T.Eq(SpellIds(boots.Id, one), boots.Spells.Count, "GetObjectSpellIds: the total with a short buffer");
T.Eq(one[0], boots.Spells[0], "GetObjectSpellIds: the first id copied");
T.Eq(SpellIds(slasher.Id, buf), -1, "GetObjectSpellIds: no identify = -1");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetObjectSpellIdsFn)(boots.Id, null, 4), -1, "GetObjectSpellIds: null buffer = -1");
var vitals = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, uint*, uint*, uint*, int>)Api->GetTargetVitalsFn;
uint h = 0, hm = 0, s = 0, sm = 0, m = 0, mm = 0;
T.Eq(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm), 0, "GetTargetVitals: nothing before an identify");
// A synthetic identify reply with a spell book and a creature profile.
F.Context.Events.Drain();
F.Receive(IdentifyReply(slasher.Id, 100, new uint[] { 0x3E1, 0x3E2 }, 150, 200, 90, 100, 40, 50));
T.Eq(Call1(Api->HasAppraisalDataFn, slasher.Id), 1, "HasAppraisalData after the reply");
T.Check(Math.Abs(lastId(slasher.Id) - now) < 600, "GetLastIdTime after the reply");
T.Eq(IntOrNull(slasher.Id, 25), 100, "the reply's int table merged (Level 25)");
n = SpellIds(slasher.Id, buf);
T.Check(n == 2 && buf[0] == 0x3E1 && buf[1] == 0x3E2, $"GetObjectSpellIds: the reply's spell book ({n})");
T.Check(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm) == 1 && h == 150 && hm == 200 && s == 90 && sm == 100 && m == 40 && mm == 50,
$"GetTargetVitals: the creature profile ({h}/{hm} {s}/{sm} {m}/{mm})");
T.Eq(vitals(slasher.Id, null, &hm, &s, &sm, &m, &mm), 0, "GetTargetVitals: null out-pointer");
var events = F.Context.Events.Drain();
T.Check(events.OfType<PluginEvent.UpdateHealth>().Any(e => e.Target == slasher.Id && e.CurrentHealth == 150 && e.MaxHealth == 200),
"the reply's creature profile is reported as a health update (as the engine does)");
T.Eq(F.Context.MaxHealthOf(slasher.Id), 200u, "MaxHealthHook: the identify's max health");
T.Eq(F.Context.HealthOf(slasher.Id, 0.5f), (100u, 200u), "HealthOf: ratio 0.5 of 200");
// UpdateHealth keeps the target's current health.
F.Receive(UpdateHealth(slasher.Id, 0.25f));
T.Check(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm) == 1 && h == 50 && hm == 200, $"GetTargetVitals after UpdateHealth 0.25 ({h}/{hm})");
}
private static byte[] DoorMotion(uint id, ushort command)
=> new WireWriter(32).U32(0xF74C).U32(id).U16(1).U16(1).U16(0).U8(0).U8(0).U8(0).U8(0).U16(0x3D)
.U32(0x2).U16(command).Align4().ToArray();
private static void Physics()
{
var heading = (delegate* unmanaged[Cdecl]<uint, float*, int>)Api->GetObjectHeadingFn;
float hd = -1;
WorldObject me = W.PlayerObject!;
float expect = (float)(((-2.0 * Math.Atan2(me.Position!.Value.Qz, me.Position.Value.Qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0);
T.Check(heading(Player, &hd) == 1 && hd >= 0 && hd < 360 && Math.Abs(hd - expect) < 0.01f, $"GetObjectHeading: the player ({hd:F1})");
T.Eq(RynthCore.Headless.Host.Objects.ObjectProps.Heading(1, 0), 0f, "heading: identity rotation = north");
T.Check(Math.Abs(RynthCore.Headless.Host.Objects.ObjectProps.Heading(MathF.Cos(-MathF.PI / 4), MathF.Sin(-MathF.PI / 4)) - 90f) < 0.01f,
"heading: a -90 degree yaw = east (clockwise)");
T.Eq(heading(First("Viamontian Laced Boots").Id, &hd), 0, "GetObjectHeading: a pack item has none");
var state = (delegate* unmanaged[Cdecl]<uint, uint*, int>)Api->GetObjectStateFn;
uint st = 0;
T.Check(state(Player, &st) == 1 && st == me.PhysicsState, $"GetObjectState: the player (0x{st:X})");
T.Eq(state(0x7FFFFFF0, &st), 0, "GetObjectState: unknown id");
// Door On / Off from UpdateMotion (a chest stands in for a door).
WorldObject chest = First("Chest");
var motionOn = (delegate* unmanaged[Cdecl]<uint, int*, int>)Api->GetObjectMotionOnFn;
int on = -1;
T.Eq(motionOn(chest.Id, &on), 0, "GetObjectMotionOn: nothing seen yet");
T.Eq(Call1(Api->GetObjectServerAgeFn, chest.Id), -1, "GetObjectServerAge: nothing heard since the host started");
F.Receive(DoorMotion(chest.Id, 0x000B));
T.Check(motionOn(chest.Id, &on) == 1 && on == 1, "GetObjectMotionOn: On (0x4000000B)");
F.Receive(DoorMotion(chest.Id, 0x000C));
T.Check(motionOn(chest.Id, &on) == 1 && on == 0, "GetObjectMotionOn: Off (0x4000000C)");
int age = Call1(Api->GetObjectServerAgeFn, chest.Id);
T.Check(age >= 0 && age < 2000, $"GetObjectServerAge: just heard ({age} ms)");
T.Eq(Call1(Api->GetObjectServerAgeFn, 0), -1, "GetObjectServerAge: id 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, uint*, int, int>)Api->GetObjectPalettesFn)(chest.Id, &st, &st, 1), -1, "GetObjectPalettes: no data");
}
private static void Removal()
{
WorldObject slasher = First("Olthoi Slasher"); // heard from (UpdateHealth) a moment ago
WorldObject ghost = W.Objects.Values.Where(o => o.Name == "Olthoi Slasher" && o.Id != slasher.Id).OrderBy(o => o.Id).First();
T.Eq(Call1(Api->RemoveClientObjectFn, Player), 0, "RemoveClientObject: never the player");
T.Eq(Call1(Api->RemoveClientObjectFn, First("Sack").Id), 0, "RemoveClientObject: not a creature");
T.Eq(Call1(Api->RemoveClientObjectFn, slasher.Id), 0, "RemoveClientObject: heard from in the last 5 s");
F.Context.Events.Drain();
T.Eq(Call1(Api->RemoveClientObjectFn, ghost.Id), 1, "RemoveClientObject: a quiet monster is removed");
T.Check(W.Get(ghost.Id) == null, "the ghost is gone from the world model");
T.Check(F.Context.Events.Drain().OfType<PluginEvent.DeleteObject>().Any(d => d.Id == ghost.Id), "plugins are told (OnDeleteObject)");
T.Eq(Call1(Api->RemoveClientObjectFn, ghost.Id), 0, "RemoveClientObject: already gone");
T.Eq(Name(ghost.Id), null, "the ghost has no name any more");
}
private static byte[]? RecordOf(uint id)
{
var fn = (delegate* unmanaged[Cdecl]<uint, byte*, int, int>)Api->GetObjectPropertiesFn;
int size = fn(id, null, 0);
if (size <= 0) return null;
byte[] buf = new byte[size];
fixed (byte* p = buf)
return fn(id, p, size) == size ? buf : null;
}
private static void Record()
{
var fn = (delegate* unmanaged[Cdecl]<uint, byte*, int, int>)Api->GetObjectPropertiesFn;
WorldObject boots = First("Viamontian Laced Boots");
byte[]? rec = RecordOf(boots.Id);
T.Check(rec != null && ObjectProperties.TryParse(rec, out _), "GetObjectProperties: the boots' record parses");
if (rec != null && ObjectProperties.TryParse(rec, out ObjectProperties? props) && props != null)
{
T.Check(props.HasIdData && (props.Flags & ObjectPropertyFlags.HasCreateData) != 0 && !props.IsPlayer, $"record flags ({props.Flags})");
T.Check(props.LastIdTime > 0, "record: last identify time");
T.Check(props.Spells.SequenceEqual(boots.Spells), $"record: spell book ({props.Spells.Count})");
T.Check(props.Ints.All(kv => IntOrNull(boots.Id, kv.Key) == kv.Value), $"record ints = per-key reads ({props.Ints.Count})");
T.Check(props.Floats.All(kv => Dbl(boots.Id, kv.Key) == kv.Value), $"record floats = per-key reads ({props.Floats.Count})");
T.Eq(props.InstanceIds.GetValueOrDefault(2u), Player, "record: container");
T.Eq(props.Strings.GetValueOrDefault(1u), "Viamontian Laced Boots", "record: name");
T.Eq(props.Ints.GetValueOrDefault(19u), boots.Value, "record: value from the header");
}
byte[]? mine = RecordOf(Player);
T.Check(mine != null && ObjectProperties.TryParse(mine, out ObjectProperties? pp) && pp!.IsPlayer && pp.Ints.Count >= W.PlayerObject!.Ints.Count,
"GetObjectProperties: the player's record (IsPlayer, PlayerDescription ints)");
WorldObject note = First("Trade Note (250,000)");
byte[]? nrec = RecordOf(note.Id);
T.Check(nrec != null && ObjectProperties.TryParse(nrec, out ObjectProperties? np) && np!.Ints.GetValueOrDefault(12u) == 215 && !np.HasIdData,
"GetObjectProperties: an unidentified stack (header stack size, no id data)");
byte small = 0;
T.Eq(fn(boots.Id, &small, 1), rec?.Length ?? -2, "GetObjectProperties: a short buffer gets the size");
T.Eq(fn(0x7FFFFFF0, null, 0), 0, "GetObjectProperties: unknown id = 0");
T.Eq(fn(0, null, 0), -1, "GetObjectProperties: id 0 = -1");
T.Eq(fn(boots.Id, null, -1), -1, "GetObjectProperties: negative size = -1");
T.Eq(fn(boots.Id, null, 10), -1, "GetObjectProperties: null buffer with a size = -1");
}
private static void OrderAndWielded()
{
var order = (delegate* unmanaged[Cdecl]<uint, int, uint*, int, int>)Api->GetContainerOrderFn;
PlayerState p = W.Player;
uint[] buf = new uint[256];
fixed (uint* b = buf)
{
int n = order(Player, 0, b, buf.Length);
T.Check(n == p.MainPackOrder.Count && buf.Take(n).SequenceEqual(p.MainPackOrder), $"GetContainerOrder: the main pack's items in slot order ({n})");
n = order(Player, 1, b, buf.Length);
T.Check(n == 7 && buf.Take(n).SequenceEqual(p.SidePackOrder), $"GetContainerOrder: the pack column ({n})");
T.Eq(order(Player, 0, null, 0), p.MainPackOrder.Count, "GetContainerOrder: count only");
T.Eq(order(First("Sack").Id, 0, b, buf.Length), -1, "GetContainerOrder: a side pack is unknown (-1)");
T.Eq(order(Player, 2, b, buf.Length), -1, "GetContainerOrder: bad slot kind");
T.Eq(order(Player, 0, null, 5), -1, "GetContainerOrder: null buffer with a size");
}
var wielded = (delegate* unmanaged[Cdecl]<uint*, uint*, int, int>)Api->GetWieldedItemsFn;
uint* ids = stackalloc uint[64];
uint* locs = stackalloc uint[64];
int count = wielded(ids, locs, 64);
var got = new Dictionary<uint, uint>();
for (int i = 0; i < Math.Max(count, 0); i++) got[ids[i]] = locs[i];
T.Check(count == p.EquippedItems.Count && p.EquippedItems.All(kv => got.TryGetValue(kv.Key, out uint l) && l == kv.Value),
$"GetWieldedItems: PlayerDescription's equipped list ({count})");
T.Eq(got.GetValueOrDefault(First("Academy Coat").Id), 0x1E00u, "GetWieldedItems: the coat's location");
T.Eq(wielded(ids, locs, 2), 2, "GetWieldedItems: at most max");
T.Eq(wielded(null, locs, 64), -1, "GetWieldedItems: null buffer");
}
}

View file

@ -0,0 +1,511 @@
// ============================================================================
// PlayerTests - the PLAYER slots (vitals, attributes, skills, spells, enchantments,
// server time, pose) against the replayed test session, checked against the portal
// dat formulas and against synthetic enchantment / vitae events.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Headless.Dat;
using RynthCore.Headless.Host;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace HeadlessHostTests;
internal static unsafe class PlayerTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("player", Run, order: 20);
private const uint Me = 0x50000001;
private static void Run()
{
Fixture f = Fixture.Shared;
using var _ = f.Context.Enter();
PlayerState p = f.Session.World.Player;
SkillTable? table = SkillTable.Shared;
T.Check(table != null, "portal dat skill table loads");
if (table == null) return;
DatFacts(table);
Vitals(f, p, table);
Attributes(f, p);
Skills(f, p, table);
SkillEnchantment(f, p);
AttributeEnchantment(f, p, table);
Vitae(f);
Spells(f, p);
Enchantments(f, p);
ServerTime(f);
Pose(f);
EdgeCases(f);
}
// ── the API through its function pointers ───────────────────────────────
private static bool Vitals(Fixture f, out uint h, out uint mh, out uint s, out uint ms, out uint m, out uint mm)
{
uint a = 0, b = 0, c = 0, d = 0, e = 0, g = 0;
int ok = ((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)f.Api->GetPlayerVitalsFn)(&a, &b, &c, &d, &e, &g);
h = a; mh = b; s = c; ms = d; m = e; mm = g;
return ok == 1;
}
private static bool BaseVitals(Fixture f, out uint h, out uint s, out uint m)
{
uint a = 0, b = 0, c = 0;
int ok = ((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)f.Api->GetPlayerBaseVitalsFn)(&a, &b, &c);
h = a; s = b; m = c;
return ok == 1;
}
private static uint? Attr2nd(Fixture f, uint obj, uint stype)
{
uint v = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)f.Api->GetObjectAttribute2ndBaseLevelFn)(obj, stype, &v) == 1 ? v : null;
}
private static uint? Attr(Fixture f, uint obj, uint stype, int raw)
{
uint v = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)f.Api->GetObjectAttributeFn)(obj, stype, raw, &v) == 1 ? v : null;
}
private static (int Buffed, int Training)? Skill(Fixture f, uint obj, uint skill)
{
int b = 0, t = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(obj, skill, &b, &t) == 1 ? (b, t) : null;
}
private static int? SkillLevel(Fixture f, uint obj, uint skill, int raw)
{
int v = 0;
return ((delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)f.Api->GetObjectSkillBuffedFn)(obj, skill, raw, &v) == 1 ? v : null;
}
private static float Vitae(Fixture f, uint id) => ((delegate* unmanaged[Cdecl]<uint, float>)f.Api->GetVitaeFn)(id);
private static double ServerTimeNow(Fixture f) => ((delegate* unmanaged[Cdecl]<double>)f.Api->GetServerTimeFn)();
private static (uint[] Ids, double[] Expiry, int Result) ReadEnchantments(Fixture f, int max = 512)
{
uint[] ids = new uint[max];
double[] exp = new double[max];
int n;
fixed (uint* pi = ids)
fixed (double* pe = exp)
n = ((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(pi, pe, max);
return (ids[..Math.Max(0, n)], exp[..Math.Max(0, n)], n);
}
// ── server messages ─────────────────────────────────────────────────────
private static byte[] GameEvent(uint eventType, byte[] body)
{
var m = new byte[16 + body.Length];
BinaryPrimitives.WriteUInt32LittleEndian(m, 0xF7B0);
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(4), Me);
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(8), 0);
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(12), eventType);
body.CopyTo(m, 16);
return m;
}
private static byte[] EnchantmentBody(ushort spell, ushort layer, ushort category, uint power, double start, double duration,
uint type, uint key, float value)
{
var ms = new MemoryStream();
var w = new BinaryWriter(ms);
w.Write(spell); w.Write(layer); w.Write(category); w.Write((ushort)0);
w.Write(power); w.Write(start); w.Write(duration); w.Write(Me);
w.Write(0f); w.Write(0f); w.Write(0.0);
w.Write(type); w.Write(key); w.Write(value);
return ms.ToArray();
}
private static void AddEnchantment(Fixture f, ushort spell, ushort layer, ushort category, uint power, double start, double duration,
uint type, uint key, float value)
=> f.Receive(GameEvent(0x02C2, EnchantmentBody(spell, layer, category, power, start, duration, type, key, value)));
private static void RemoveEnchantment(Fixture f, ushort spell, ushort layer)
{
var b = new byte[4];
BinaryPrimitives.WriteUInt16LittleEndian(b, spell);
BinaryPrimitives.WriteUInt16LittleEndian(b.AsSpan(2), layer);
f.Receive(GameEvent(0x02C3, b));
}
private const uint SingleStat = 0x1000, Multiplicative = 0x4000, Additive = 0x8000, Beneficial = 0x2000000;
// ── expectations computed here from the dat ─────────────────────────────
private static uint BaseAttr(PlayerState p, uint a) => p.AttributeTable.TryGetValue(a, out AttributeInfo i) ? i.Init + i.Ranks : 0;
private static uint Formula(SkillFormula fm, Func<uint, uint> attr)
{
if (fm.X == 0) return 0;
uint t = attr(fm.Attr1) + (fm.Attr2 != 0 ? attr(fm.Attr2) : 0);
return fm.Divisor > 1 ? (uint)Math.Round((double)t / fm.Divisor, MidpointRounding.AwayFromZero) : t;
}
private static int PlayerInt(Fixture f, uint key)
=> f.Session.World.PlayerObject is { } o && o.TryGetInt(key, out int v) ? v : 0;
// ── checks ──────────────────────────────────────────────────────────────
private static void DatFacts(SkillTable t)
{
T.Eq(t.MaxHealth.ToString(), "a2 / 2", "dat: max health = Endurance / 2");
T.Eq(t.MaxStamina.ToString(), "a2 / 1", "dat: max stamina = Endurance");
T.Eq(t.MaxMana.ToString(), "a6 / 1", "dat: max mana = Self");
T.Eq(t.Get(6)?.Formula.ToString(), "(a3 + a4) / 3", "dat: Melee Defense = (Quickness + Coordination) / 3");
T.Eq(t.Get(15)?.Formula.ToString(), "(a6 + a5) / 7", "dat: Magic Defense = (Self + Focus) / 7");
T.Eq(t.Get(34)?.Formula.ToString(), "(a5 + a6) / 4", "dat: War Magic = (Focus + Self) / 4");
T.Eq(t.Get(6)?.Name, "Melee Defense", "dat: skill 6 name");
T.Check(t.Skills.Count >= 45, $"dat: {t.Skills.Count} skills");
}
private static void Vitals(Fixture f, PlayerState p, SkillTable t)
{
T.Check(Vitals(f, out uint h, out uint mh, out uint s, out uint ms, out uint m, out uint mm), "GetPlayerVitals succeeds");
T.Check(BaseVitals(f, out uint bh, out uint bs, out uint bm), "GetPlayerBaseVitals succeeds");
T.Info($"vitals {h}/{mh} {s}/{ms} {m}/{mm}; base max {bh} {bs} {bm}; attributes {string.Join(" ", Enumerable.Range(1, 6).Select(a => BaseAttr(p, (uint)a)))}");
T.Eq(h, p.CurrentVital(Vital.Health), "current health = PlayerState");
T.Eq(s, p.CurrentVital(Vital.Stamina), "current stamina = PlayerState");
T.Eq(m, p.CurrentVital(Vital.Mana), "current mana = PlayerState");
T.Check(mh >= bh && ms >= bs && mm >= bm, "buffed max >= base max");
int enlightenment = PlayerInt(f, 390);
uint[] expected = new uint[4];
for (uint v = 1; v <= 3; v++)
{
VitalInfo vi = p.Vitals[v];
expected[v] = Formula(t.VitalFormula(v), a => BaseAttr(p, a)) + vi.Init + vi.Ranks;
}
expected[1] += (uint)(enlightenment * 2);
T.Eq(bh, expected[1], "base max health = End/2 + init + ranks (dat formula)");
T.Eq(bs, expected[2], "base max stamina = End + init + ranks");
T.Eq(bm, expected[3], "base max mana = Self + init + ranks");
T.Eq(Attr2nd(f, Me, 1), (uint?)bh, "Attribute2ndBaseLevel(MaxHealth) = base max health");
T.Eq(Attr2nd(f, Me, 3), (uint?)bs, "Attribute2ndBaseLevel(MaxStamina) = base max stamina");
T.Eq(Attr2nd(f, Me, 5), (uint?)bm, "Attribute2ndBaseLevel(MaxMana) = base max mana");
T.Eq(Attr2nd(f, Me, 2), (uint?)h, "Attribute2ndBaseLevel(Health) = current health");
T.Check(Attr2nd(f, 0x12345678, 1) == null && Attr2nd(f, Me, 7) == null && Attr2nd(f, Me, 0) == null, "Attribute2ndBaseLevel: other object / bad stype fail");
// A multiplicative max-health buff (Asheron's Benediction style) and an additive one.
uint before = mh;
AddEnchantment(f, 4100, 1, 0xFFE0, 999, 0, 600, SingleStat | Multiplicative | 0x2 | Beneficial, 1, 1.10f);
AddEnchantment(f, 4101, 1, 0xFFE1, 999, 0, 600, SingleStat | Additive | 0x2 | Beneficial, 1, 7f);
Vitals(f, out _, out uint mh2, out _, out uint ms2, out _, out _);
T.Eq(mh2, (uint)Math.Round(before * 1.10f + 7f, MidpointRounding.AwayFromZero), "max health: * 1.10 (multiplicative) then + 7 (additive)");
T.Eq(ms2, ms, "max stamina unchanged by a max-health buff");
BaseVitals(f, out uint bh2, out _, out _);
T.Eq(bh2, bh, "base max health ignores enchantments");
RemoveEnchantment(f, 4100, 1);
RemoveEnchantment(f, 4101, 1);
Vitals(f, out _, out uint mh3, out _, out _, out _, out _);
T.Eq(mh3, before, "max health back after the buffs are removed");
}
private static void Attributes(Fixture f, PlayerState p)
{
var line = new List<string>();
for (uint a = 1; a <= 6; a++)
{
uint? raw = Attr(f, Me, a, 1), buffed = Attr(f, Me, a, 0);
T.Eq(raw, (uint?)BaseAttr(p, a), $"attribute {a} raw = init + ranks");
T.Check(buffed != null && buffed >= raw, $"attribute {a} buffed ({buffed}) >= raw ({raw})");
line.Add($"{a}:{raw}/{buffed}");
}
T.Info("attributes raw/buffed " + string.Join(" ", line));
T.Check(Attr(f, Me, 0, 0) == null && Attr(f, Me, 7, 0) == null && Attr(f, 0x12345678, 1, 0) == null, "attribute: bad stype / other object fail");
}
private static void Skills(Fixture f, PlayerState p, SkillTable t)
{
T.Eq(p.SkillTable.Count, 38, "38 skills");
int checkedBase = 0;
var lines = new List<string>();
uint[] attrBuffed = new uint[7];
for (uint a = 1; a <= 6; a++) attrBuffed[a] = Attr(f, Me, a, 0) ?? 0;
bool augs = PlayerInt(f, 365) != 0 || PlayerInt(f, 300) != 0 || PlayerInt(f, 301) != 0 || PlayerInt(f, 302) != 0
|| PlayerInt(f, 390) != 0 || PlayerInt(f, 326) != 0 || PlayerInt(f, 344) != 0;
T.Info($"augmentation properties present: {augs}");
foreach (SkillInfo si in p.SkillTable.Values.OrderBy(s => s.Id))
{
var r = Skill(f, Me, si.Id);
int? raw = SkillLevel(f, Me, si.Id, 1), buffed = SkillLevel(f, Me, si.Id, 0);
T.Check(r != null && raw != null && buffed != null, $"skill {si.Id} readable");
if (r == null || raw == null || buffed == null) continue;
T.Eq(r.Value.Training, (int)si.Training, $"skill {si.Id} training class");
T.Eq(r.Value.Buffed, buffed.Value, $"skill {si.Id}: GetObjectSkill = GetObjectSkillBuffed(raw 0)");
T.Check(buffed >= raw, $"skill {si.Id} buffed {buffed} >= base {raw}");
SkillBaseInfo? sb = t.Get(si.Id);
bool usable = si.Training >= 2 || (si.Training == 1 && sb?.MinLevel == 1);
if (!augs && sb != null)
{
uint expectBase = (usable ? Formula(sb.Formula, a => BaseAttr(p, a)) : 0) + si.Init + si.Ranks;
T.Eq(raw.Value, (int)expectBase, $"skill {si.Id} ({sb.Name}) base = formula + init + ranks");
checkedBase++;
}
if (lines.Count < 8 || si.Id is 6 or 15 or 24 or 34)
lines.Add($"{si.Id} {sb?.Name} sac{si.Training} init{si.Init} ranks{si.Ranks} -> {raw}/{buffed}");
}
foreach (string l in lines.Distinct()) T.Info(l);
T.Check(checkedBase >= 30 || augs, $"base formula checked on {checkedBase} skills");
T.Check(Skill(f, Me, 9999) == null, "unknown skill fails");
T.Check(Skill(f, 0x12345678, 6) == null && SkillLevel(f, 0x12345678, 6, 0) == null, "other object's skill fails");
// Melee defense, trained, specialised?
SkillInfo md = p.SkillTable.TryGetValue(6, out SkillInfo x) ? x : default;
T.Check(md.Training >= 2, "Melee Defense trained or specialized");
T.Eq(SkillLevel(f, Me, 6, 1), (int?)(int)(Formula(t.Get(6)!.Formula, a => BaseAttr(p, a)) + md.Init + md.Ranks), "Melee Defense base = (Coord + Quick)/3 + init + ranks");
}
private static void SkillEnchantment(Fixture f, PlayerState p)
{
uint skill = p.SkillTable.Values.Where(s => s.Training >= 2).Select(s => s.Id).OrderBy(i => i).First();
int baseBefore = SkillLevel(f, Me, skill, 1)!.Value;
int before = SkillLevel(f, Me, skill, 0)!.Value;
AddEnchantment(f, 4102, 1, 0xFFE2, 999, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 25f);
int after = SkillLevel(f, Me, skill, 0)!.Value;
T.Eq(after - before, 25, $"skill {skill}: +25 additive enchantment adds 25");
T.Eq(SkillLevel(f, Me, skill, 1), (int?)baseBefore, $"skill {skill}: base unchanged by the enchantment");
T.Eq(Skill(f, Me, skill)?.Buffed, (int?)after, $"skill {skill}: GetObjectSkill sees it");
// Same category, lower power: does not stack (top layer only).
AddEnchantment(f, 4103, 2, 0xFFE2, 10, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 50f);
T.Eq(SkillLevel(f, Me, skill, 0), (int?)after, $"skill {skill}: a weaker spell in the same category is ignored");
// Same category, higher power: replaces.
AddEnchantment(f, 4104, 3, 0xFFE2, 2000, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 40f);
T.Eq(SkillLevel(f, Me, skill, 0), (int?)(before + 40), $"skill {skill}: the stronger spell in the category wins");
RemoveEnchantment(f, 4103, 2);
RemoveEnchantment(f, 4104, 3);
// Multiplicative (applies before the additive).
AddEnchantment(f, 4105, 1, 0xFFE3, 999, 0, 600, SingleStat | Multiplicative | 0x10 | Beneficial, skill, 1.5f);
int mult = SkillLevel(f, Me, skill, 0)!.Value;
T.Check(mult > after, $"skill {skill}: * 1.5 raises it ({after} -> {mult})");
// A different skill's key doesn't apply.
AddEnchantment(f, 4106, 1, 0xFFE4, 999, 0, 600, SingleStat | Additive | 0x10, skill + 1000, 99f);
T.Eq(SkillLevel(f, Me, skill, 0), (int?)mult, $"skill {skill}: another skill's enchantment doesn't apply");
RemoveEnchantment(f, 4102, 1);
RemoveEnchantment(f, 4105, 1);
RemoveEnchantment(f, 4106, 1);
T.Eq(SkillLevel(f, Me, skill, 0), (int?)before, $"skill {skill}: back to {before} when removed");
}
private static void AttributeEnchantment(Fixture f, PlayerState p, SkillTable t)
{
// +20 Quickness: buffed Quickness +20 and Melee Defense ((Coord + Quick)/3) up by about 20/3.
uint q0 = Attr(f, Me, 3, 0)!.Value;
int md0 = SkillLevel(f, Me, 6, 0)!.Value;
int mdBase0 = SkillLevel(f, Me, 6, 1)!.Value;
AddEnchantment(f, 4107, 1, 0xFFE5, 999, 0, 600, SingleStat | Additive | 0x1 | Beneficial, 3, 30f);
uint q1 = Attr(f, Me, 3, 0)!.Value;
T.Eq(q1 - q0, 30u, "Quickness +30 additive");
T.Eq(Attr(f, Me, 3, 1), (uint?)BaseAttr(p, 3), "Quickness raw unchanged");
int md1 = SkillLevel(f, Me, 6, 0)!.Value;
T.Eq(md1 - md0, 10, "Melee Defense follows buffed Quickness (+30 / 3)");
T.Eq(SkillLevel(f, Me, 6, 1), (int?)mdBase0, "Melee Defense base uses base attributes");
// Endurance buff raises max health (End/2) and stamina.
Vitals(f, out _, out uint mh0, out _, out uint ms0, out _, out _);
AddEnchantment(f, 4108, 1, 0xFFE6, 999, 0, 600, SingleStat | Additive | 0x1 | Beneficial, 2, 40f);
Vitals(f, out _, out uint mh1, out _, out uint ms1, out _, out _);
T.Eq(mh1 - mh0, 20u, "max health follows buffed Endurance (+40 / 2)");
T.Eq(ms1 - ms0, 40u, "max stamina follows buffed Endurance (+40)");
RemoveEnchantment(f, 4107, 1);
RemoveEnchantment(f, 4108, 1);
T.Eq(Attr(f, Me, 3, 0), (uint?)q0, "Quickness back after removal");
}
private static void Vitae(Fixture f)
{
T.Eq(Vitae(f, Me), 1.0f, "no vitae: 1.0");
T.Eq(Vitae(f, 0x12345678), 1.0f, "another object's vitae: 1.0");
Vitals(f, out _, out uint mh0, out _, out uint ms0, out _, out uint mm0);
BaseVitals(f, out uint bh0, out _, out _);
int sk0 = SkillLevel(f, Me, 6, 0)!.Value;
int skBase0 = SkillLevel(f, Me, 6, 1)!.Value;
int count0 = ReadEnchantments(f).Result;
AddEnchantment(f, 666, 0, 204, 0, 0, -1, 0x800000 | 0x2 | Multiplicative, 0, 0.9f);
T.Eq(Vitae(f, Me), 0.9f, "vitae 10%: 0.9");
Vitals(f, out _, out uint mh1, out _, out uint ms1, out _, out uint mm1);
T.Eq(mh1, (uint)Math.Round(mh0 * 0.9f, MidpointRounding.AwayFromZero), "vitae scales max health");
T.Eq(mm1, (uint)Math.Round(mm0 * 0.9f, MidpointRounding.AwayFromZero), "vitae scales max mana");
T.Check(ms1 < ms0, "vitae lowers max stamina");
BaseVitals(f, out uint bh1, out _, out _);
T.Eq(bh1, bh0, "vitae doesn't change base max");
// ACE / the client: (formula(buffed attributes) + init + ranks) * multipliers * vitae, then the additives.
// Melee Defense has no multiplicative mods here, so the additive part is what the buffs add on top.
SkillInfo md = f.Session.World.Player.SkillTable[6];
uint mdPlain = (uint)Math.Round((Attr(f, Me, 3, 0)!.Value + Attr(f, Me, 4, 0)!.Value) / 3.0, MidpointRounding.AwayFromZero) + md.Init + md.Ranks;
int mdAdd = sk0 - (int)mdPlain;
T.Info($"Melee Defense {sk0} = {mdPlain} + {mdAdd} from additive buffs");
T.Eq(SkillLevel(f, Me, 6, 0), (int?)(int)Math.Round(mdPlain * 0.9f + mdAdd, MidpointRounding.AwayFromZero), "vitae scales buffed skills before the additives");
T.Eq(SkillLevel(f, Me, 6, 1), (int?)skBase0, "vitae doesn't change base skills");
T.Eq(ReadEnchantments(f).Result, count0, "vitae is not listed by ReadPlayerEnchantments");
RemoveEnchantment(f, 666, 0);
T.Eq(Vitae(f, Me), 1.0f, "vitae removed: 1.0");
}
private static void Spells(Fixture f, PlayerState p)
{
uint[] buf = new uint[1024];
int n;
fixed (uint* b = buf) n = ((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(b, buf.Length);
T.Eq(n, 503, "ReadKnownSpells: 503 spells");
T.Check(buf.Take(Math.Max(0, n)).Contains(24u), "spellbook has Armor Self I (24)");
T.Check(buf.Take(Math.Max(0, n)).ToHashSet().SetEquals(p.SpellBook), "ReadKnownSpells = the spellbook");
fixed (uint* b = buf) n = ((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(b, 10);
T.Eq(n, 10, "ReadKnownSpells stops at maxCount");
var known = (delegate* unmanaged[Cdecl]<uint, uint, int>)f.Api->IsSpellKnownFn;
T.Eq(known(Me, 24), 1, "IsSpellKnown(Armor Self I) = 1");
uint unknown = Enumerable.Range(1, 7000).Select(i => (uint)i).First(i => !p.SpellBook.Contains(i));
T.Eq(known(Me, unknown), 0, $"IsSpellKnown({unknown}) = 0");
T.Eq(known(0x12345678, 24), -1, "IsSpellKnown(another object) = -1");
T.Eq(known(0, 24), -1, "IsSpellKnown(0) = -1");
}
private static void Enchantments(Fixture f, PlayerState p)
{
double now = ServerTimeNow(f);
var (ids, exp, n) = ReadEnchantments(f);
int expected = p.ActiveEnchantments.Count(e => e.SpellId != 666);
T.Eq(n, expected, "ReadPlayerEnchantments: every enchantment but vitae");
T.Info($"{n} enchantments, server time {now:F1}; spells {string.Join(",", ids.Take(12))}...");
int forever = 0, finite = 0;
for (int i = 0; i < n; i++)
{
Enchantment e = p.ActiveEnchantments.First(x => x.SpellId == ids[i]);
if (e.Duration <= 0) { forever++; T.Eq(exp[i], double.MaxValue, $"spell {ids[i]} (duration {e.Duration}): no expiry"); }
else { finite++; T.Check(exp[i] > now && exp[i] <= now + e.Duration + 0.001, $"spell {ids[i]}: expiry {exp[i] - now:F1}s ahead, within its duration {e.Duration}"); }
}
T.Info($"{finite} timed, {forever} without duration (item spells)");
T.Check(finite > 0, "some timed enchantments");
int armor = Array.IndexOf(ids, 24u);
T.Check(armor >= 0, "Armor Self I (24, cast during the capture) is active");
if (armor >= 0)
{
Enchantment e = p.ActiveEnchantments.First(x => x.SpellId == 24);
T.Info($"Armor Self I: start {e.StartTime:F1}, duration {e.Duration}, {exp[armor] - now:F1}s left");
T.Check(Math.Abs(exp[armor] - now - (e.Duration + e.StartTime)) < 1.0, "Armor Self I expiry = now + duration + (negative) start");
}
// A fresh cast: StartTime 0, duration 100 -> expires 100 s from now; time passes; it gets closer.
AddEnchantment(f, 4109, 1, 0xFFE7, 999, 0, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
double t0 = ServerTimeNow(f);
var r1 = ReadEnchantments(f);
int k = Array.IndexOf(r1.Ids, 4109u);
T.Check(k >= 0 && Math.Abs(r1.Expiry[k] - (t0 + 100)) < 0.01, "new enchantment expires at server time + duration");
f.Now += 30_000;
double t1 = ServerTimeNow(f);
T.Check(Math.Abs(t1 - t0 - 30) < 0.001, "server time advances with the clock");
var r2 = ReadEnchantments(f);
int k2 = Array.IndexOf(r2.Ids, 4109u);
T.Check(k2 >= 0 && Math.Abs(r2.Expiry[k2] - r1.Expiry[k]) < 0.001 && r2.Expiry[k2] - t1 < 70.01, "expiry is fixed; remaining shrinks as time passes");
// A refresh (the server re-sends it with a new StartTime) moves the expiry.
AddEnchantment(f, 4109, 1, 0xFFE7, 999, 0, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
var r3 = ReadEnchantments(f);
int k3 = Array.IndexOf(r3.Ids, 4109u);
T.Check(k3 >= 0 && Math.Abs(r3.Expiry[k3] - (t1 + 100)) < 0.01, "a refreshed enchantment expires 100 s from the refresh");
// An ACE resend of a running one: StartTime -40 (running 40 s).
AddEnchantment(f, 4110, 1, 0xFFE8, 999, -40, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
var r4 = ReadEnchantments(f);
int k4 = Array.IndexOf(r4.Ids, 4110u);
T.Check(k4 >= 0 && Math.Abs(r4.Expiry[k4] - (t1 + 60)) < 0.01, "StartTime -40 with duration 100 expires in 60 s");
RemoveEnchantment(f, 4109, 1);
RemoveEnchantment(f, 4110, 1);
T.Eq(ReadEnchantments(f).Result, expected, "removed enchantments are gone");
// maxCount clips; ReadObjectEnchantments for the player = ReadPlayerEnchantments; others -1.
T.Eq(ReadEnchantments(f, 5).Result, Math.Min(5, expected), "ReadPlayerEnchantments stops at maxCount");
uint[] ids2 = new uint[512];
double[] exp2 = new double[512];
int n2, n3;
fixed (uint* pi = ids2)
fixed (double* pe = exp2)
{
n2 = ((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(Me, pi, pe, 512);
n3 = ((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(0x12345678, pi, pe, 512);
}
T.Eq(n2, expected, "ReadObjectEnchantments(player) = the player's");
T.Eq(n3, -1, "ReadObjectEnchantments(other) = -1");
}
private static void ServerTime(Fixture f)
{
double t = ServerTimeNow(f);
T.Check(t > 0, $"server time known ({t:F1})");
T.Check(t >= f.Session.ServerTime, "server time >= the last sync");
f.Now += 2_500;
T.Check(Math.Abs(ServerTimeNow(f) - t - 2.5) < 0.001, "server time = last sync + local time since");
}
private static void Pose(Fixture f)
{
WorldPosition pos = f.Session.World.PlayerObject!.Position!.Value;
uint cell = 0;
float x = 0, y = 0, z = 0, qw = 0, qx = 0, qy = 0, qz = 0;
int ok = ((delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)f.Api->GetPlayerPoseFn)(&cell, &x, &y, &z, &qw, &qx, &qy, &qz);
T.Eq(ok, 1, "GetPlayerPose succeeds");
T.Info($"pose cell 0x{cell:X8} ({x:F2}, {y:F2}, {z:F2}) q({qw:F3}, {qx:F3}, {qy:F3}, {qz:F3})");
T.Eq(cell, 0x61460249u, "pose cell = her dungeon spot");
T.Check(cell == pos.Cell && x == pos.X && y == pos.Y && z == pos.Z && qw == pos.Qw && qz == pos.Qz, "pose = the world model's position");
float heading = 0;
T.Eq(((delegate* unmanaged[Cdecl]<float*, int>)f.Api->GetPlayerHeadingFn)(&heading), 1, "GetPlayerHeading succeeds");
// The engine: compass = -2 atan2(qz, qw) (0 = north, clockwise); GetPlayerHeading = 90 - compass.
double compass = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
double expect = ((90.0 - compass) % 360.0 + 360.0) % 360.0;
T.Info($"heading {heading:F2} (compass {compass:F2})");
T.Check(Math.Abs(heading - expect) < 0.01 || Math.Abs(Math.Abs(heading - expect) - 360) < 0.01, "heading = 90 - compass of her quaternion");
// Convention: facing north -> 90, east -> 0, south -> 270, west -> 180 (0 = east, counter-clockwise).
static (float W, float Z) Facing(double compassDeg) { double yaw = -compassDeg * Math.PI / 180; return ((float)Math.Cos(yaw / 2), (float)Math.Sin(yaw / 2)); }
foreach ((double c, float h) in new[] { (0.0, 90f), (90.0, 0f), (180.0, 270f), (270.0, 180f), (45.0, 45f) })
{
(float w, float zq) = Facing(c);
float got = HostApi.DecalHeadingFromQuaternion(w, zq);
float d = Math.Abs(got - h);
T.Check(d < 0.01f || Math.Abs(d - 360f) < 0.01f, $"facing compass {c}: heading {got:F2}, expected {h}");
}
double ns = 0, ew = 0;
T.Eq(((delegate* unmanaged[Cdecl]<double*, double*, int>)f.Api->GetCurCoordsFn)(&ns, &ew), 1, "GetCurCoords succeeds");
double eEw = (((cell >> 24) & 0xFF) * 8.0 + x / 24.0 - 1019.5) / 10.0;
double eNs = (((cell >> 16) & 0xFF) * 8.0 + y / 24.0 - 1019.5) / 10.0;
T.Info($"coords {Math.Abs(ns):F2}{(ns >= 0 ? "N" : "S")} {Math.Abs(ew):F2}{(ew >= 0 ? "E" : "W")}");
T.Check(Math.Abs(ns - eNs) < 1e-9 && Math.Abs(ew - eEw) < 1e-9, "coords = the landblock formula");
}
private static void EdgeCases(Fixture f)
{
uint u = 0;
int i = 0;
float fl = 0;
double d = 0;
T.Eq(((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)f.Api->GetPlayerVitalsFn)(null, &u, &u, &u, &u, &u), 0, "GetPlayerVitals(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)f.Api->GetPlayerBaseVitalsFn)(&u, null, &u), 0, "GetPlayerBaseVitals(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)f.Api->GetObjectAttribute2ndBaseLevelFn)(Me, 1, null), 0, "Attribute2ndBaseLevel(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(Me, 6, null, &i), 0, "GetObjectSkill(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)f.Api->GetObjectSkillBuffedFn)(Me, 6, 0, null), 0, "GetObjectSkillBuffed(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)f.Api->GetObjectAttributeFn)(Me, 1, 0, null), 0, "GetObjectAttribute(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(null, 10), -1, "ReadKnownSpells(null) = -1");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(&u, 0), -1, "ReadKnownSpells(max 0) = -1");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(null, &d, 4), -1, "ReadPlayerEnchantments(null) = -1");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(&u, &d, 0), 0, "ReadPlayerEnchantments(max 0) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(Me, &u, null, 4), -1, "ReadObjectEnchantments(null) = -1");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)f.Api->GetPlayerPoseFn)(&u, &fl, &fl, null, &fl, &fl, &fl, &fl), 0, "GetPlayerPose(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<float*, int>)f.Api->GetPlayerHeadingFn)(null), 0, "GetPlayerHeading(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<double*, double*, int>)f.Api->GetCurCoordsFn)(&d, null), 0, "GetCurCoords(null) = 0");
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, uint*, int>)f.Api->GetCharacterTitlesFn)(null, 0, &u), -1, "GetCharacterTitles = -1 (not tracked)");
T.Check(f.Api->GetPlayerVitalsFn != IntPtr.Zero && f.Api->GetVitaeFn != IntPtr.Zero && f.Api->GetServerTimeFn != IntPtr.Zero
&& f.Api->ReadKnownSpellsFn != IntPtr.Zero && f.Api->GetCharacterTitlesFn != IntPtr.Zero, "player slots filled");
// No context at all (a plugin thread before any context exists can't happen here; with the
// fixture's context current, an out-of-world question is answered by the "not the player" paths).
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(0, 6, &i, &i), 0, "GetObjectSkill(0) = 0");
}
}

View file

@ -0,0 +1,166 @@
// ============================================================================
// HeadlessHostTests - the plugin host's API against a replayed ACE session.
// Each area has its own file (ObjectsTests.cs, PlayerTests.cs, ActionsTests.cs) that
// registers its suite from a module initializer:
// [System.Runtime.CompilerServices.ModuleInitializer]
// internal static void Register() => Suites.Add("objects", Run, order: 10);
// and uses Fixture.Shared (a session that replayed the capture, its HostContext and the
// API table) plus T.Check / T.Eq / T.Info.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Engine.Net;
using RynthCore.Headless.Dat;
using RynthCore.Headless.Host;
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
using RynthCore.PluginSdk;
namespace HeadlessHostTests;
internal static class Program
{
private static int Main()
{
// Every suite runs against the captured session. The public source snapshots leave the
// captures out (they hold a live login), so without one there is nothing to check.
if (!File.Exists(Fixture.CapturePath))
{
Console.WriteLine($"SKIPPED: no captured session at {Fixture.CapturePath} (the public source leaves the captures out).");
return 0;
}
Fixture f = Fixture.Shared;
Console.WriteLine($"fixture: player 0x{f.Session.World.Player.Id:X8}, {f.Session.World.Objects.Count} objects, state {f.Session.State}, spells table {(f.Context.Spells != null ? "yes" : "no")}");
foreach (var (name, run) in Suites.All)
{
T.Case(name);
try { run(); }
catch (Exception ex) { T.Check(false, $"threw {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); }
}
Console.WriteLine();
Console.WriteLine($"{T.Checks - T.Failed}/{T.Checks} checks passed.");
Console.WriteLine(T.Failed == 0 ? "ALL HEADLESS HOST TESTS PASSED." : $"{T.Failed} FAILED.");
return T.Failed == 0 ? 0 : 1;
}
}
internal static class Suites
{
private static readonly List<(int Order, string Name, Action Run)> _all = new();
public static void Add(string name, Action run, int order) => _all.Add((order, name, run));
public static IEnumerable<(string Name, Action Run)> All => _all.OrderBy(s => s.Order).Select(s => (s.Name, s.Run));
}
/// <summary>
/// A ClientSession that has replayed the captured P1 session (the test character: login, teleport out,
/// identify, use, cast, pickup, give, drop, melee kill, teleport back), its HostContext and the API table.
/// Call API functions inside <c>using var _ = f.Context.Enter();</c>.
/// </summary>
internal sealed unsafe class Fixture
{
public static Fixture Shared { get; } = new();
/// <summary>The account name the replay logs in with (only the outbound LoginRequest, which the capture leaves out, uses it).</summary>
public const string Account = "testaccount";
/// <summary>The captured session (tools\HeadlessNetTests\Captures, copied beside the test).</summary>
public static string CapturePath => Path.Combine(AppContext.BaseDirectory, "Captures", "ace-p1-session.txt");
public readonly FakeLink Link = new();
public readonly ClientSession Session;
public readonly HostContext Context;
public readonly RynthCoreApiNative* Api;
public long Now = 1000;
private Fixture()
{
Session = new ClientSession(Link, new SessionOptions { Account = Account, PickFirstCharacter = true }, () => Now);
// The API suites look at objects from every part of the capture (Holtburg's shop and corpse after
// the teleport back): keep them. TeleportForgets checks the real behaviour on its own replay.
Session.World.ForgetOnTeleport = false;
Session.Start("x");
foreach (string line in File.ReadLines(CapturePath))
{
if (line.StartsWith('#') || line.Length == 0) continue;
string[] f = line.Split(' ');
if (f[1] != "S") continue;
Link.Inbox.Enqueue(Convert.FromHexString(f[2]));
Now += 5;
Session.Tick();
}
string? ac = DatFile.FindAcFolder();
Context = new HostContext(Session, Account, geometry: null, spells: ac != null ? SpellTable.Load(ac, out _) : null);
Api = HostApi.Build();
}
/// <summary>A mark for <see cref="ActionsSince"/>.</summary>
public int Mark => Link.Sent.Count;
/// <summary>The game actions (type, payload) sent since a mark.</summary>
public List<(uint Type, byte[] Payload)> ActionsSince(int mark)
{
var list = new List<(uint, byte[])>();
foreach (byte[] m in MessagesSince(mark))
if (m.Length >= 12 && BinaryPrimitives.ReadUInt32LittleEndian(m) == 0xF7B1)
list.Add((BinaryPrimitives.ReadUInt32LittleEndian(m.AsSpan(8)), m.AsSpan(12).ToArray()));
return list;
}
/// <summary>Every whole message (opcode first) sent since a mark (single-fragment messages).</summary>
public List<byte[]> MessagesSince(int mark)
{
var list = new List<byte[]>();
foreach (var (d, _) in Link.Sent.Skip(mark))
{
if (!InboundPacket.TryParse(d, out InboundPacket p) || !p.Has(PacketFlags.BlobFragments)) continue;
int at = p.OptionalEnd;
int size = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(at + 10));
list.Add(d.AsSpan(at + 16, size - 16).ToArray());
}
return list;
}
/// <summary>Feeds a server message (opcode first) straight into the world model, as if it had arrived.</summary>
public void Receive(byte[] message)
{
if (RynthCore.PluginSdk.Net.ServerMessage.TryFromWire(message, out var msg)) Session.World.Apply(msg);
}
}
internal sealed class FakeLink : IDatagramLink
{
public readonly List<(byte[] Data, bool ConnectPort)> Sent = new();
public readonly Queue<byte[]> Inbox = new();
public void Send(ReadOnlySpan<byte> d, bool connectPort) => Sent.Add((d.ToArray(), connectPort));
public bool TryReceive(out byte[] d) => Inbox.TryDequeue(out d!);
}
internal static class T
{
public static int Checks, Failed;
private static string _case = "";
public static void Case(string name)
{
_case = name;
Console.WriteLine($"-- {name}");
}
public static void Check(bool ok, string what)
{
Checks++;
if (ok) return;
Failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
public static void Eq<TV>(TV actual, TV expected, string what)
{
Checks++;
if (EqualityComparer<TV>.Default.Equals(actual, expected)) return;
Failed++;
Console.WriteLine($" FAIL [{_case}] {what}: got {actual}, expected {expected}");
}
public static void Info(string s) => Console.WriteLine($" info: {s}");
}

View file

@ -0,0 +1,124 @@
// ============================================================================
// StatusTests - the per-character status files and command inbox (StatusExporter) and
// the phone's hold-to-move rules (RemoteMove), in a temp folder.
// ============================================================================
using System.Text.Json;
using RynthCore.Headless.Host.Status;
namespace HeadlessHostTests;
internal static class StatusTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("status", Run, order: 50);
private static void Run()
{
Move();
Exporter();
}
private static void Move()
{
var m = new RemoteMove();
T.Check(RemoteMove.TryParseStart("forward", out string d, out long? dm) && d == "forward" && dm == null, "legacy start: a bare direction");
T.Check(RemoteMove.TryParseStart("{\"dir\":\"Right\",\"deadmanMs\":800}", out d, out dm) && d == "right" && dm == 800, "protocol 2 start");
T.Check(RemoteMove.TryParseStart("{\"dir\":\"left\"}", out _, out dm) && dm == RemoteMove.DefaultDeadMs, "protocol 2 start: default dead-man");
T.Check(!RemoteMove.TryParseStart("{\"dir\":\"up\"}", out _, out _), "an unknown direction is refused");
T.Check(RemoteMove.TryParseKeepAlive("{\"dirs\":[\"forward\",\"jump\",\"FORWARD\"]}", out var dirs) && dirs.Count == 1, "keep-alive: unknown and repeated names dropped");
T.Eq(RemoteMove.ParseStop("garbage"), "stop", "an unreadable stop stops everything");
// Legacy: 2 s window, re-armed by a repeated start.
T.Eq(m.Start("forward", null, 0).Count, 1, "start presses once");
T.Eq(m.Start("forward", null, 1500).Count, 0, "a repeated start doesn't press again");
m.Tick(3000, out bool fired);
T.Check(!fired, "re-armed: still held at 3.0 s");
m.Tick(3600, out fired);
T.Check(fired && m.Held.Count == 0, "legacy dead-man at 2 s after the last start");
// Protocol 2: keep-alives hold it, a keep-alive naming less lets go, the dead-man fires, resume.
m.Start("forward", 600, 10_000);
m.Start("left", 600, 10_000);
m.KeepAlive(new[] { "forward", "left" }, 10_500);
m.Tick(11_000, out fired);
T.Check(!fired && m.Held.Count == 2, "keep-alive refreshes the dead-man");
var acts = m.KeepAlive(new[] { "forward" }, 11_100);
T.Check(acts.Count == 1 && acts[0] == ("left", false), "a keep-alive that no longer names a direction lets go of it");
m.Tick(11_800, out fired);
T.Check(fired && m.Held.Count == 0 && m.KeepAliveMode, "no keep-alive for 600 ms: dead-man");
acts = m.KeepAlive(new[] { "forward" }, 12_500);
T.Check(acts.Count == 1 && acts[0] == ("forward", true), "a keep-alive soon after resumes what the dead-man stopped");
m.Stop("stop");
T.Eq(m.KeepAlive(new[] { "forward" }, 12_600).Count, 0, "but never after an explicit stop");
}
private static void Exporter()
{
Fixture f = Fixture.Shared;
string dir = Path.Combine(Path.GetTempPath(), "rynth-headless-status-" + Guid.NewGuid().ToString("N"));
try
{
int id = StatusExporter.MakeClientId(3);
T.Check(id > 1_000_000_000 && id % 2 == 1, "client id: odd and above a billion (never a real pid)");
T.Check(StatusExporter.MakeClientId(4) != id, "a different slot, a different id");
var x = new StatusExporter(dir, id, Fixture.Account) { ServerName = "ACEmulator", LastCharacter = "+Test Character" };
x.Tick();
using (var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, $"RynthCore.{id}.status.json"))))
{
JsonElement r = doc.RootElement;
T.Check(!r.GetProperty("inWorld").GetBoolean() && r.GetProperty("fps").GetInt32() == 0, "no session yet: not in the world (reads loading)");
T.Check(r.GetProperty("headless").GetBoolean() && r.GetProperty("hostPid").GetInt32() == Environment.ProcessId, "headless + hostPid");
T.Eq(r.GetProperty("character").GetString(), "+Test Character", "the configured character until one is seen");
}
// A command waiting before the first in-world tick is drained (oldest first) and deleted.
Directory.CreateDirectory(Path.Combine(dir, "commands"));
string cmd = Path.Combine(dir, "commands", $"RynthCore.{id}.0000000000000000001-a.cmd.json");
File.WriteAllText(cmd, "{\"action\":\"moveStart\",\"value\":{\"dir\":\"forward\",\"deadmanMs\":600}}");
string other = Path.Combine(dir, "commands", "RynthCore.12345.0000000000000000001-a.cmd.json");
File.WriteAllText(other, "{\"action\":\"moveStart\",\"value\":\"forward\"}");
x.Context = f.Context;
x.Tick();
T.Check(!File.Exists(cmd), "its command file is drained");
T.Check(File.Exists(other), "another client's command file is left alone");
T.Check(f.Session.DriveMotion.Moving, "moveStart forward: autorun on");
File.WriteAllText(cmd, "{\"action\":\"moveStop\",\"value\":\"stop\"}");
Thread.Sleep(250);
x.Tick();
T.Check(!f.Session.DriveMotion.Moving, "moveStop: stopped");
using (var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, $"RynthCore.{id}.status.json"))))
{
JsonElement r = doc.RootElement;
T.Eq(r.GetProperty("schema").GetString(), "rynthcore.client-status/1", "status schema");
T.Eq(r.GetProperty("pid").GetInt32(), id, "pid = the client id");
T.Eq(r.GetProperty("account").GetString(), Fixture.Account, "account");
T.Eq(r.GetProperty("server").GetString(), "ACEmulator", "server (the configured name)");
T.Check(r.GetProperty("inWorld").GetBoolean(), "in the world");
T.Check(r.TryGetProperty("opos", out JsonElement opos) && opos.GetProperty("cell").GetString()!.Length == 8, "opos with the cell");
T.Check(r.GetProperty("enchantments").ValueKind == JsonValueKind.Array, "enchantments listed");
T.Eq(r.GetProperty("moveProto").GetInt32(), 2, "move protocol 2");
}
string sheet = Path.Combine(dir, $"RynthCore.{id}.character.json");
T.Check(File.Exists(sheet), "character sheet written");
using (var doc = JsonDocument.Parse(File.ReadAllText(sheet)))
{
JsonElement r = doc.RootElement;
T.Eq(r.GetProperty("schema").GetString(), "rynthcore.character/1", "sheet schema");
T.Eq(r.GetProperty("attributes").GetArrayLength(), 6, "six attributes");
T.Eq(r.GetProperty("vitals").GetArrayLength(), 3, "three vitals");
T.Check(r.GetProperty("skills").GetArrayLength() > 0, "trained skills listed");
T.Check(r.GetProperty("level").GetInt32() > 0, "level");
}
x.Retire();
T.Check(!File.Exists(Path.Combine(dir, $"RynthCore.{id}.status.json")) && !File.Exists(sheet), "retire removes its files");
}
finally
{
try { Directory.Delete(dir, recursive: true); } catch (IOException) { }
}
}
}

View file

@ -0,0 +1,44 @@
// ============================================================================
// TeleportTests - a teleport drops the surroundings, as the retail client does (the captured session
// goes from the dungeon to Holtburg and back: Holtburg's shop and corpse must not follow the character home).
// ============================================================================
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace HeadlessHostTests;
internal static class TeleportTests
{
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register() => Suites.Add("teleport", Run, order: 60);
private static void Run()
{
long now = 1000;
var link = new FakeLink();
var session = new ClientSession(link, new SessionOptions { Account = Fixture.Account, PickFirstCharacter = true }, () => now);
session.Start("x");
int teleports = 0, deleted = 0;
session.World.PlayerTeleported += () => teleports++;
session.World.ObjectDeleted += _ => deleted++;
foreach (string line in File.ReadLines(Fixture.CapturePath))
{
if (line.StartsWith('#') || line.Length == 0) continue;
string[] f = line.Split(' ');
if (f[1] != "S") continue;
link.Inbox.Enqueue(Convert.FromHexString(f[2]));
now += 5;
session.Tick();
}
WorldState w = session.World;
bool Has(string name) => w.Objects.Values.Any(o => o.Name == name);
T.Check(teleports >= 2, $"the capture teleports out and back ({teleports})");
T.Check(deleted > 0, $"plugins hear the dropped objects as deletes ({deleted})");
T.Check(!Has("Shopkeeper Renald the Elder") && !Has("Corpse of Drudge Skulker"), "Holtburg's shopkeeper and corpse are gone after the teleport home");
T.Check(Has("Viamontian Laced Boots") && Has("Sack"), "what the character carries stays");
T.Check(w.Objects.ContainsKey(w.Player.Id), "the player stays");
T.Check(w.Objects.Count < Fixture.Shared.Session.World.Objects.Count,
$"fewer objects than the replay that keeps them ({w.Objects.Count} < {Fixture.Shared.Session.World.Objects.Count})");
}
}

View file

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for RynthCore.Headless's protocol layer: Hash32, ISAAC (AC seeding),
String16L/String32L/packed u32, packet build/parse and checksums (plain and encrypted),
byte-identical resends, fragment reassembly, sequence tracking, acks and NAKs, and the
login/ObjectCreate message layouts. No network, no server: a session captured from the
local ACE server (Captures\) is replayed through the transport and parsers.
ISAAC and Hash32 vectors are from OpenAC's tests (MIT, see Program.cs).
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>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>HeadlessNetTests</RootNamespace>
<AssemblyName>HeadlessNetTests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<!-- Datagrams captured from a live session against the local ACE server (rynth-headless capture option). -->
<None Include="Captures\**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Headless\RynthCore.Headless.csproj" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for RynthCore.Headless's ClientSession: a scripted fake server (built from
the protocol description, in-process, no sockets) takes it through login, character
select, enter world, chat and logout, with and without lost packets, and checks every
packet the client sends (sequences, checksums, ISAAC keys, ack/NAK rules).
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>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>HeadlessSessionTests</RootNamespace>
<AssemblyName>HeadlessSessionTests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Headless\RynthCore.Headless.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,420 @@
// ============================================================================
// HeadlessSessionTests - ClientSession against a scripted, in-process fake server.
// The fake server follows the protocol as documented in docs\HEADLESS.md: ConnectRequest,
// CharacterList/ServerName/DDD, ServerReady, PlayerCreate + CreateObjects, speech,
// logout. It checks every client packet (sequence rules, checksums, the client's ISAAC
// keys) and can drop chosen packets in either direction to exercise NAKs and resends.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Engine.Net;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
using RynthCore.PluginSdk.Net;
namespace HeadlessSessionTests;
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
FullSession(dropServer: Array.Empty<uint>(), dropClient: Array.Empty<uint>(), "clean session");
FullSession(dropServer: new uint[] { 3, 6 }, dropClient: Array.Empty<uint>(), "server packets 3 and 6 lost once");
FullSession(dropServer: Array.Empty<uint>(), dropClient: new uint[] { 3 }, "client packet 3 lost once");
Walking();
WrongCharacter();
CharacterError();
ServerGoesSilent();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL HEADLESS SESSION TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
private const uint Player = 0x50000001, Drudge = 0x80000042;
private const string Account = "tester";
// ── scenarios ───────────────────────────────────────────────────────────
private static void FullSession(uint[] dropServer, uint[] dropClient, string name)
{
Case(name);
var h = new Harness(dropServer, dropClient);
var chat = new List<ChatLine>();
var objects = new List<ObjectSeen>();
h.Session.Chat += chat.Add;
h.Session.ObjectCreated += objects.Add;
h.Session.Start("hunter2");
h.RunUntil(() => h.Session.State == SessionState.InWorld && h.Server.LoginCompletes > 0, 10_000);
Eq(h.Session.State, SessionState.InWorld, "in world");
Eq(h.Session.PlayerId, Player, "player id");
Check(h.Server.EnterWorldAccount == Account && h.Server.EnterWorldGuid == Player, "enter-world echoes guid + server account name");
Check(h.Server.LoginCompletes == 1, "LoginComplete once (our object came before PlayerCreate)");
Check(h.Server.DddAnswered, "DDD answered");
Check(objects.Any(o => o.Id == Drudge && o.Name == "Drudge Skulker"), "the drudge appeared");
Check(chat.Any(c => c.Text == "Welcome to Testworld" && c.ChatType == 0x05), "server message");
h.Session.Say("hello world");
h.RunUntil(() => chat.Any(c => c.Text == "hello world"), 5_000);
Check(h.Server.Said.Contains("hello world"), "server heard Talk");
Check(chat.Any(c => c.Text == "hello world" && c.Sender == "Alpha" && c.ChatType == 0x02), "own speech echoed back");
h.Run(3_000); // a few seconds of acks/keepalives
h.Session.Logout();
h.RunUntil(() => h.Session.Finished, 15_000);
Eq(h.Session.State, SessionState.Closed, "closed");
Check(h.Session.FailReason == null, "no failure");
Check(h.Server.LogoffSeen && h.Server.DisconnectSeen, "server saw LogOff then Disconnect");
Eq(h.Server.ClientBadKeys, 0, "every client key matched the ClientSeed stream");
Eq(h.Server.ClientBadPlain, 0, "every plain client checksum valid");
Eq(h.Server.ClientSeqErrors, 0, "client sequence rules");
Eq(h.Session.Transport.BadChecksums, 0L, "client verified every server checksum");
Eq(h.Session.Transport.Missing.Count, 0, "client has no gaps left");
if (dropServer.Length > 0)
Check(h.Server.NaksReceived > 0 && h.Server.Resent >= dropServer.Length, $"client NAKed the lost server packets (naks {h.Server.NaksReceived}, resent {h.Server.Resent})");
if (dropClient.Length > 0)
Check(h.Session.Transport.Resends >= dropClient.Length, "client resent its lost packet");
}
private static void WrongCharacter()
{
Case("unknown character name");
var h = new Harness(Array.Empty<uint>(), Array.Empty<uint>(), character: "Nobody");
h.Session.Start("pw");
h.RunUntil(() => h.Session.Finished, 5_000);
Eq(h.Session.State, SessionState.Failed, "failed");
Check(h.Session.FailReason?.Contains("Nobody") == true, "says which name");
Check(h.Server.DisconnectSeen, "sent Disconnect");
}
private static void CharacterError()
{
Case("server refuses enter world");
var h = new Harness(Array.Empty<uint>(), Array.Empty<uint>()) { };
h.Server.RefuseEnterWorld = true;
h.Session.Start("pw");
h.RunUntil(() => h.Session.Finished, 5_000);
Eq(h.Session.State, SessionState.Failed, "failed");
Check(h.Session.FailReason?.Contains("0xD") == true, "character error code reported");
}
private static void ServerGoesSilent()
{
Case("server goes silent");
var h = new Harness(Array.Empty<uint>(), Array.Empty<uint>());
h.Session.Start("pw");
h.RunUntil(() => h.Session.State == SessionState.InWorld, 5_000);
h.Server.Mute = true;
h.RunUntil(() => h.Session.Finished, 60_000);
Eq(h.Session.State, SessionState.Failed, "failed after silence");
}
private static void Walking()
{
Case("walking (flat walker)");
var h = new Harness(Array.Empty<uint>(), Array.Empty<uint>());
var done = new List<(bool, string)>();
h.Session.MoveFinished += (ok, why) => done.Add((ok, why));
h.Session.Start("pw");
h.RunUntil(() => h.Session.State == SessionState.InWorld && h.Server.LoginCompletes > 0, 5_000);
// The player was created at 0xA9B40029 (1, 2, 3); walk 20 m north (into the next land cell).
var start = h.Session.World.PlayerObject!.Position!.Value;
h.Session.WalkTo(start with { Y = start.Y + 20 });
h.RunUntil(() => done.Count > 0, 15_000);
Check(done.Count == 1 && done[0].Item1, $"arrived ({(done.Count > 0 ? done[0].Item2 : "never")})");
Check(h.Server.Motions.FirstOrDefault() == "forward", "a MoveToState 'run forward' first");
Check(h.Server.Motions.LastOrDefault() == "stop", "a MoveToState 'stop' last");
Check(h.Server.Positions.Count >= 3, $"position reports while walking ({h.Server.Positions.Count})");
var last = h.Server.Positions.LastOrDefault();
Check(MathF.Abs(last.Y - 21.8f) < 0.1f && MathF.Abs(last.X - 1) < 0.01f, $"last report at the goal ({last.X:F2}, {last.Y:F2})");
Check(last.Cell == 0xA9B40001, $"with the land cell recomputed (0x{last.Cell:X8})");
// 1.0 run rate until the server echoes one: 4 m/s, so about 5 s for 20 m.
h.Session.Logout();
h.RunUntil(() => h.Session.Finished, 15_000);
}
// ── harness ─────────────────────────────────────────────────────────────
private sealed class Harness : IDatagramLink
{
public long Now = 1000;
public readonly FakeServer Server;
public readonly ClientSession Session;
private readonly Queue<byte[]> _toClient = new();
private readonly HashSet<uint> _dropClient;
public Harness(uint[] dropServer, uint[] dropClient, string character = "Alpha")
{
_dropClient = new HashSet<uint>(dropClient);
Server = new FakeServer(_toClient, new HashSet<uint>(dropServer));
Session = new ClientSession(this, new SessionOptions { Account = Account, Character = character }, () => Now);
}
void IDatagramLink.Send(ReadOnlySpan<byte> d, bool connectPort)
{
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(d);
uint flags = BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(4));
if ((flags & PacketFlags.Retransmission) == 0 && (flags & PacketFlags.BlobFragments) != 0 && _dropClient.Remove(seq))
return; // lost on the way, once
Server.Receive(d.ToArray(), connectPort, Now);
}
bool IDatagramLink.TryReceive(out byte[] d) => _toClient.TryDequeue(out d!);
public void Run(long ms)
{
long end = Now + ms;
while (Now < end && !Session.Finished) Step();
}
public void RunUntil(Func<bool> done, long maxMs)
{
long end = Now + maxMs;
while (Now < end && !done() && !Session.Finished) Step();
}
private void Step()
{
Now += 15;
Server.Tick(Now);
Session.Tick();
}
}
private sealed unsafe class FakeServer : IServerMessageSink
{
private const uint ClientSeed = 0x0BADF00D, ServerSeed = 0x5EED5EED;
private readonly Queue<byte[]> _out;
private readonly HashSet<uint> _drop;
private readonly Isaac _keys = new(ServerSeed);
private readonly InboundKeys _clientKeys = new(ClientSeed);
private readonly FragmentReassembler _reasm = new();
private readonly Dictionary<uint, byte[]> _cache = new();
private uint _seq = 1, _fragSeq, _lastClientSeq = 1;
private readonly HashSet<uint> _clientMissing = new();
private bool _connected;
private long _lastAck, _lastHeard;
public bool RefuseEnterWorld, Mute;
public int LoginCompletes, NaksReceived, Resent, ClientBadKeys, ClientBadPlain, ClientSeqErrors;
public bool DddAnswered, LogoffSeen, DisconnectSeen;
public string? EnterWorldAccount;
public uint EnterWorldGuid;
public readonly List<string> Said = new();
public readonly List<string> Motions = new();
public readonly List<(uint Cell, float X, float Y)> Positions = new();
public FakeServer(Queue<byte[]> output, HashSet<uint> drop)
{
_out = output;
_drop = drop;
}
public void Receive(byte[] d, bool connectPort, long now)
{
_lastHeard = now;
if (!InboundPacket.TryParse(d, out InboundPacket p)) { ClientBadPlain++; return; }
Packet.TryPayloadHash(d, p.OptionalEnd, out uint payload);
uint header = Packet.HeaderHash(d);
if (p.Encrypted)
{
if (!_clientKeys.TryMatch((p.Checksum - header) ^ payload, p.Has(PacketFlags.Retransmission))) ClientBadKeys++;
}
else if (header + payload != p.Checksum)
{
ClientBadPlain++;
}
if (p.Has(PacketFlags.LoginRequest))
{
if (p.Sequence != 0 || connectPort) ClientSeqErrors++;
var w = new WireWriter();
w.F64(5000.0).U64(0xC00C1E).U32(0x0007).U32(ServerSeed).U32(ClientSeed).U32(0);
Emit(Packet.Build(0, PacketFlags.ConnectRequest, 0x0B, 0, 1, w.Span, null, null, out _), cache: false);
return;
}
if (p.Has(PacketFlags.ConnectResponse))
{
if (!connectPort || p.Sequence != 1 || BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(20)) != 0xC00C1E) ClientSeqErrors++;
if (_connected) return;
_connected = true;
var cl = new WireWriter().U32(Opcode.CharacterList).U32(0).U32(2)
.U32(Player).String16L("Alpha").U32(0)
.U32(0x50000002).String16L("Beta").U32(0)
.U32(0).U32(11).String16L(Account).U32(1).U32(1);
Send(cl.ToArray());
Send(new WireWriter().U32(Opcode.ServerName).I32(1).I32(100).String16L("Testworld").ToArray());
Send(new WireWriter().U32(Opcode.DddInterrogation).U32(1).U32(1).U32(1).U32(2).U32(0).U32(1).ToArray());
return;
}
if (connectPort) { ClientSeqErrors++; return; }
if (p.Id != 0x0007) ClientSeqErrors++;
if (p.Has(PacketFlags.Disconnect)) { DisconnectSeen = true; return; }
if (p.Naks.Length > 0)
{
foreach (uint s in p.Naks)
{
NaksReceived++;
if (_cache.TryGetValue(s, out byte[]? c))
{
// Resend with the Retransmission flag; same key, header re-hashed.
byte[] r = (byte[])c.Clone();
InboundPacket.TryParse(r, out InboundPacket rp);
Packet.TryPayloadHash(r, rp.OptionalEnd, out uint rph);
uint sealedPayload = rp.Checksum - Packet.HeaderHash(r);
BinaryPrimitives.WriteUInt32LittleEndian(r.AsSpan(4), rp.Flags | PacketFlags.Retransmission);
Packet.Seal(r, sealedPayload);
_out.Enqueue(r);
Resent++;
}
}
}
if (p.Flags == PacketFlags.AckSequence)
{
if (p.Sequence > _lastClientSeq + 1) ClientSeqErrors++; // ack-only reuses the current sequence
return;
}
if (p.Has(PacketFlags.BlobFragments))
{
// Like the server: a gap is NAKed (plain, at the server's current sequence).
if (p.Sequence > _lastClientSeq + 1)
{
var nak = new WireWriter().U32(p.Sequence - _lastClientSeq - 1);
for (uint s = _lastClientSeq + 1; s < p.Sequence; s++) { nak.U32(s); _clientMissing.Add(s); }
Emit(Packet.Build(_seq, PacketFlags.RequestRetransmit, 0x0B, 0, 1, nak.Span, null, null, out _), cache: false);
}
else if (p.Sequence <= _lastClientSeq && !_clientMissing.Remove(p.Sequence))
{
ClientSeqErrors++; // a duplicate nobody asked for
}
if (p.Sequence > _lastClientSeq) _lastClientSeq = p.Sequence;
fixed (byte* b = d) _reasm.ProcessDatagram(b, d.Length, now, this);
}
}
public void Tick(long now)
{
if (!_connected || Mute) return;
if (now - _lastAck >= 2000)
{
_lastAck = now;
var w = new WireWriter().U32(_lastClientSeq);
Emit(Packet.Build(_seq, PacketFlags.AckSequence, 0x0B, 0, 1, w.Span, null, null, out _), cache: false);
}
}
void IServerMessageSink.OnServerMessage(uint fragmentSequence, byte* message, int length)
=> Handle(new ReadOnlySpan<byte>(message, length).ToArray());
private void Handle(byte[] m)
{
uint op = BinaryPrimitives.ReadUInt32LittleEndian(m);
var r = new NetReader(m.AsSpan(4));
switch (op)
{
case Opcode.DddInterrogationResponse:
DddAnswered = true;
Send(new WireWriter().U32(Opcode.DddEnd).ToArray());
break;
case Opcode.CharacterEnterWorldRequest:
Send(new WireWriter().U32(Opcode.EnterWorldServerReady).ToArray());
break;
case Opcode.CharacterEnterWorld:
r.U32(out EnterWorldGuid);
r.String16L(out string acct);
EnterWorldAccount = acct;
if (RefuseEnterWorld)
{
Send(new WireWriter().U32(Opcode.CharacterError).U32(0x0D).ToArray());
break;
}
// Our own object arrives before PlayerCreate (different queues).
Send(CreateObject(Player, "Alpha"));
Send(new WireWriter().U32(Opcode.PlayerCreate).U32(Player).ToArray());
Send(CreateObject(Drudge, "Drudge Skulker"));
Send(new WireWriter().U32(Opcode.ServerMessage).String16L("Welcome to Testworld").U32(0x05).ToArray());
break;
case Opcode.GameAction:
r.U32(out _);
r.U32(out uint type);
if (type == GameActionType.LoginComplete) LoginCompletes++;
if (type == ActionType.MoveToState && r.U32(out uint motionFlags))
Motions.Add(motionFlags == 0 ? "stop" : (motionFlags & 0x4) != 0 ? "forward" : $"0x{motionFlags:X}");
if (type == ActionType.AutonomousPosition && r.U32(out uint pcell) && r.F32(out float px) && r.F32(out float py))
Positions.Add((pcell, px, py));
if (type == GameActionType.Talk && r.String16L(out string text))
{
Said.Add(text);
Send(new WireWriter().U32(Opcode.HearSpeech).String16L(text).String16L("Alpha").U32(Player).U32(0x02).ToArray());
}
break;
case Opcode.CharacterLogOff:
LogoffSeen = true;
Send(new WireWriter().U32(Opcode.CharacterLogOff).ToArray());
Send(new WireWriter().U32(Opcode.CharacterList).U32(0).U32(0).U32(0).U32(11).String16L(Account).U32(1).U32(1).ToArray());
break;
}
}
private static byte[] CreateObject(uint id, string name)
{
var w = new WireWriter().U32(Opcode.ObjectCreate).U32(id);
w.U8(0x11).U8(0).U8(0).U8(0);
w.U32(0x8000).U32(0).U32(0xA9B40029).F32(1).F32(2).F32(3).F32(1).F32(0).F32(0).F32(0);
for (int i = 0; i < 9; i++) w.U16(0);
w.Align4();
w.U32(0).String16L(name).PackedU32(1).PackedU32(0x1000).U32(0x10).U32(0).Align4();
return w.ToArray();
}
private void Send(byte[] message)
{
if (Mute) return;
var frag = new Fragment(++_fragSeq, 0x80000000, 1, 0, MessageQueue.UI, message);
uint seq = ++_seq;
byte[] d = Packet.Build(seq, 0, 0x0B, 0, 1, ReadOnlySpan<byte>.Empty, new[] { frag }, _keys.Next(), out _);
_cache[seq] = d;
if (_drop.Remove(seq)) return; // lost on the way, once
_out.Enqueue(d);
}
private void Emit(byte[] d, bool cache)
{
if (Mute) return;
_out.Enqueue(d);
}
}
// ── helpers ─────────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine($"-- {name}");
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
private static void Eq<T>(T actual, T expected, string what)
{
_checks++;
if (EqualityComparer<T>.Default.Equals(actual, expected)) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}: got {actual}, expected {expected}");
}
}

View file

@ -9,6 +9,8 @@
trip, migration of a plain-text file, undecryptable blobs, nothing leaking into files or notes;
and the crash-dump kill hold (CrashDumpWriterRule.cs): which client a createdump.exe /
WerFault.exe command line names, and how long the launcher's kills wait for it.
Headless accounts (headless-accounts.json, HeadlessAccountModes.cs) under the same rules, the
Headless settings, and the run config / arguments the launcher hands rynth-headless (HeadlessLaunch.cs).
Works in a temp folder, never in %APPDATA%\RynthCore. Windows only (DPAPI).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
@ -25,6 +27,8 @@
<Compile Include="..\..\src\RynthCore.App\AppSettings.cs" Link="App\AppSettings.cs" />
<Compile Include="..\..\src\RynthCore.App\AppSettingsStore.cs" Link="App\AppSettingsStore.cs" />
<Compile Include="..\..\src\RynthCore.App\DecalAccountModes.cs" Link="App\DecalAccountModes.cs" />
<Compile Include="..\..\src\RynthCore.App\HeadlessAccountModes.cs" Link="App\HeadlessAccountModes.cs" />
<Compile Include="..\..\src\RynthCore.App\HeadlessLaunch.cs" Link="App\HeadlessLaunch.cs" />
<Compile Include="..\..\src\RynthCore.App\InjectionMode.cs" Link="App\InjectionMode.cs" />
<Compile Include="..\..\src\RynthCore.App\LaunchAccountProfile.cs" Link="App\LaunchAccountProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" />

View file

@ -149,6 +149,229 @@ internal static class Program
CheckSharedFilesSafe();
});
// ── Headless accounts (headless-accounts.json) ──────────────────────
// Same arrangement as "Decal + RynthCore": appsettings.json says RynthCore, the sidecar
// says which are Headless. "Bridge launcher" = one that knows DecalBridge but not Headless.
Scenario("headless: written as RynthCore, listed in headless-accounts.json", root, () =>
{
AppSettings s = SampleWithHeadless();
AppSettingsStore.Save(s);
AppSettingsStore.Save(s); // second save: a .bak exists too
CheckSharedFilesSafe();
Check(SharedMode("h") == "RynthCore", "h (Headless) is written as RynthCore");
Check(SharedMode("b") == "RynthCore" && SharedMode("c") == "Decal", "the others as before");
Check(HeadlessIds().SequenceEqual(new[] { "h" }), "headless-accounts.json lists only h");
Check(SidecarIds().SequenceEqual(new[] { "b" }), "decal-accounts.json still lists only b");
Check(s.AccountProfiles.First(a => a.Id == "h").InjectionMode == InjectionMode.Headless, "save leaves the in-memory mode alone");
Check(BridgeLauncherCanRead(Main_) && BridgeLauncherCanRead(Bak), "a bridge launcher can read appsettings.json and its .bak");
});
Scenario("headless: round trip", root, () =>
{
AppSettingsStore.Save(SampleWithHeadless());
AppSettings loaded = AppSettingsStore.Load();
Check(Mode(loaded, "h") == InjectionMode.Headless, "load: h Headless");
Check(Mode(loaded, "a") == InjectionMode.RynthCore && Mode(loaded, "b") == InjectionMode.DecalBridge &&
Mode(loaded, "c") == InjectionMode.Decal, "load: the others as saved");
Check(AppSettingsStore.LastLoadDiagnostic == null && AppSettingsStore.LastMigrationNote == null, "load: no diagnostics");
loaded.AccountProfiles.First(a => a.Id == "h").InjectionMode = InjectionMode.RynthCore;
AppSettingsStore.Save(loaded);
Check(!File.Exists(HeadlessSidecar), "headless-accounts.json removed when no account uses the mode");
Check(SidecarIds().SequenceEqual(new[] { "b" }), "decal-accounts.json untouched");
Check(Mode(AppSettingsStore.Load(), "h") == InjectionMode.RynthCore, "load: h RynthCore");
});
Scenario("headless: older launchers still read the file, and their edits win", root, () =>
{
AppSettingsStore.Save(SampleWithHeadless());
Check(OldLauncherCanRead(Main_), "a launcher from before the Decal bridge can read it");
Check(BridgeLauncherCanRead(Main_), "a launcher with the Decal bridge but no Headless can read it");
OldLauncherEdit(_ => { }); // saves without changes (drops what it doesn't know, but not the sidecar)
Check(Mode(AppSettingsStore.Load(), "h") == InjectionMode.Headless, "an old launcher's save keeps h Headless");
OldLauncherEdit(accounts => SetMode(accounts, "h", "Decal"));
AppSettings loaded = AppSettingsStore.Load();
Check(Mode(loaded, "h") == InjectionMode.Decal, "an old launcher switching h to Decal wins");
AppSettingsStore.Save(loaded);
Check(!File.Exists(HeadlessSidecar), "the stale entry is dropped at the next save");
});
Scenario("headless: migrate a file that says Headless itself", root, () =>
{
string legacy = """
{ "EnginePath": "X", "AccountProfiles": [
{ "Id": "a", "AccountName": "A", "InjectionMode": "RynthCore" },
{ "Id": "h", "AccountName": "H", "InjectionMode": "Headless" },
{ "Id": "n", "AccountName": "N", "InjectionMode": 3 },
{ "Id": "b", "AccountName": "B", "InjectionMode": "DecalBridge" } ] }
""";
File.WriteAllText(Main_, legacy);
File.WriteAllText(Bak, legacy);
Check(!BridgeLauncherCanRead(Main_), "negative control: a bridge launcher can't read \"Headless\"");
AppSettings loaded = AppSettingsStore.Load();
Check(Mode(loaded, "h") == InjectionMode.Headless && Mode(loaded, "n") == InjectionMode.Headless, "h and n (numeric 3) kept as Headless");
Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "b kept as Decal + RynthCore");
Check(AppSettingsStore.LastMigrationNote?.Contains("2 Headless account(s)") == true &&
AppSettingsStore.LastMigrationNote.Contains("1 \"Decal + RynthCore\""), "migration note: " + AppSettingsStore.LastMigrationNote);
CheckSharedFilesSafe();
Check(HeadlessIds().SequenceEqual(new[] { "h", "n" }) && SidecarIds().SequenceEqual(new[] { "b" }), "both sidecars written");
AppSettingsStore.Load();
Check(AppSettingsStore.LastMigrationNote == null, "second load: nothing left to migrate");
});
Scenario("headless: unreadable headless-accounts.json, and an id in both sidecars", root, () =>
{
AppSettingsStore.Save(SampleWithHeadless());
File.WriteAllText(HeadlessSidecar, """{ "HeadlessAccountIds": [ 7 ] }""");
AppSettings loaded = AppSettingsStore.Load();
Check(Mode(loaded, "h") == InjectionMode.RynthCore, "h runs as RynthCore");
Check(Mode(loaded, "b") == InjectionMode.DecalBridge, "decal-accounts.json still applies");
Check(AppSettingsStore.LastLoadDiagnostic == null, "appsettings.json not taken for corrupt");
Check(AppSettingsStore.LastMigrationNote?.Contains("headless-accounts.json could not be read") == true, "note: " + AppSettingsStore.LastMigrationNote);
AppSettingsStore.Save(SampleWithHeadless());
File.WriteAllText(HeadlessSidecar, """{ "Version": 1, "HeadlessAccountIds": [ "h", "b" ] }""");
AppSettings both = AppSettingsStore.Load();
Check(Mode(both, "b") == InjectionMode.DecalBridge && Mode(both, "h") == InjectionMode.Headless, "an id in both: Decal + RynthCore wins");
});
Scenario("headless: Clone and CopyFrom keep every field", root, () =>
{
var full = new LaunchAccountProfile
{
Id = "id1", AccountName = "Acct", PasswordProtected = "blob", LegacyPlainPassword = "legacy",
PasswordNeedsReentry = true, CharacterName = "Char", Alias = "Al", ServerId = "srv",
WindowX = 1, WindowY = 2, WindowWidth = 300, WindowHeight = 400, UserPrefsPath = @"C:\p.ini",
InjectionMode = InjectionMode.Headless,
OnLoginCommandsByCharacter = new(StringComparer.OrdinalIgnoreCase) { ["Char"] = ["/say hi"] },
OnLoginWaitMs = 1234,
};
// Every public read/write property must be set to something other than its default here,
// so a field added later without Clone/CopyFrom support fails this check.
var blank = new LaunchAccountProfile();
foreach (var prop in typeof(LaunchAccountProfile).GetProperties().Where(p => p.CanRead && p.CanWrite))
Check(!Equals(Json(prop.GetValue(full)), Json(prop.GetValue(blank))), $"test sets {prop.Name}");
LaunchAccountProfile clone = full.Clone();
var copied = new LaunchAccountProfile();
copied.CopyFrom(full);
foreach (var prop in typeof(LaunchAccountProfile).GetProperties().Where(p => p.CanRead && p.CanWrite))
{
string want = Json(prop.GetValue(full));
Check(Json(prop.GetValue(clone)) == want, $"Clone keeps {prop.Name}");
Check(Json(prop.GetValue(copied)) == want, $"CopyFrom keeps {prop.Name}");
}
Check(clone.InjectionMode == InjectionMode.Headless && copied.InjectionMode == InjectionMode.Headless, "Headless kept");
});
Scenario("headless: the new settings round trip, and default for older files", root, () =>
{
AppSettings fresh = new();
Check(fresh.HeadlessExePath == "" && fresh.HeadlessPluginPaths.Count == 0 &&
fresh.HeadlessSuiteDir == "" && fresh.HeadlessStatusDir == "", "defaults: empty");
File.WriteAllText(Main_, """{ "EnginePath": "Z", "AccountProfiles": [] }""");
AppSettings older = AppSettingsStore.Load();
Check(older.HeadlessExePath == "" && older.HeadlessPluginPaths is { Count: 0 } &&
older.HeadlessSuiteDir == "" && older.HeadlessStatusDir == "", "a file without them reads the defaults");
AppSettings s = SampleWithHeadless();
s.HeadlessExePath = @"D:\Rynth\Headless\rynth-headless.exe";
s.HeadlessPluginPaths = [@"D:\x64\RynthCore.Plugin.RynthAi.dll", @"D:\x64\RynthCore.Plugin.RynthNav.dll"];
s.HeadlessSuiteDir = @"D:\Suite";
s.HeadlessStatusDir = @"D:\Status";
AppSettingsStore.Save(s);
AppSettings loaded = AppSettingsStore.Load();
Check(loaded.HeadlessExePath == s.HeadlessExePath, "HeadlessExePath");
Check(loaded.HeadlessPluginPaths.SequenceEqual(s.HeadlessPluginPaths), "HeadlessPluginPaths");
Check(loaded.HeadlessSuiteDir == s.HeadlessSuiteDir && loaded.HeadlessStatusDir == s.HeadlessStatusDir, "HeadlessSuiteDir, HeadlessStatusDir");
Check(OldLauncherCanRead(Main_) && BridgeLauncherCanRead(Main_), "older launchers still read the file");
});
Scenario("headless: run config, arguments, exe path, stop event", root, () =>
{
const string HeadlessPw = "Headless-Test-Pw-7 \"q\"";
LaunchAccountProfile account = new() { Id = "0123abcd", AccountName = "TestAccount", InjectionMode = InjectionMode.Headless };
account.SetPassword(HeadlessPw);
var spec = new HeadlessRunSpec
{
Host = "127.0.0.1", Port = 9000, ServerName = "Local ACE",
Plugins = [@"C:\x64\RynthCore.Plugin.RynthAi.dll", " ", @"C:\x64\Other.dll"],
Sessions =
{
new HeadlessSessionSpec { LauncherProfileId = account.Id, Account = account.AccountName, Character = "+Test Character",
Commands = ["/ra start", ""], StaySeconds = 0, Reconnect = true },
},
};
string json = HeadlessLaunch.BuildConfigJson(spec);
Check(!json.Contains(HeadlessPw) && !json.Contains(account.PasswordProtected), "no password (plain or encrypted) in the config");
Check(!json.Contains("password", StringComparison.OrdinalIgnoreCase), "no password field at all");
JsonNode cfg = JsonNode.Parse(json)!;
Check((string?)cfg["host"] == "127.0.0.1" && (int?)cfg["port"] == 9000 && (string?)cfg["serverName"] == "Local ACE", "host, port, serverName");
Check(cfg["suiteDir"] == null && cfg["statusDir"] == null, "empty suiteDir/statusDir left out (the CLI's defaults)");
Check(cfg["plugins"]!.AsArray().Select(n => (string)n!).SequenceEqual(new[] { @"C:\x64\RynthCore.Plugin.RynthAi.dll", @"C:\x64\Other.dll" }), "plugins (blank dropped)");
JsonNode session = cfg["sessions"]!.AsArray().Single()!;
Check((string?)session["launcherProfileId"] == "0123abcd" && (string?)session["account"] == "TestAccount" && (string?)session["character"] == "+Test Character",
"session: launcherProfileId, account, character");
Check(session["commands"]!.AsArray().Select(n => (string)n!).SequenceEqual(new[] { "/ra start" }) &&
(int?)session["staySeconds"] == 0 && (bool?)session["reconnect"] == true, "session: commands, staySeconds, reconnect");
// As rynth-headless reads it (RunConfig: case-insensitive).
CliRunConfig? read = JsonSerializer.Deserialize<CliRunConfig>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
Check(read?.Host == "127.0.0.1" && read.Port == 9000 && read.Sessions.Single().LauncherProfileId == "0123abcd" &&
read.Sessions.Single().Character == "+Test Character", "the CLI's shape reads it");
spec.SuiteDir = @"D:\Suite"; spec.StatusDir = @"D:\Status";
spec.Sessions[0].Character = "";
JsonNode cfg2 = JsonNode.Parse(HeadlessLaunch.BuildConfigJson(spec))!;
Check((string?)cfg2["suiteDir"] == @"D:\Suite" && (string?)cfg2["statusDir"] == @"D:\Status", "suiteDir/statusDir when set");
Check(cfg2["sessions"]![0]!.AsObject().ContainsKey("character") && cfg2["sessions"]![0]!["character"] == null, "no character: null");
string path = HeadlessLaunch.ConfigPath(_dir, account.Id);
Check(path == Path.Combine(_dir, "headless", "launch_0123abcd.json"), "config path: " + path);
Check(Path.GetFileName(HeadlessLaunch.ConfigPath(_dir, "a/b:c")) == "launch_a_b_c.json", "unsafe id characters replaced");
HeadlessLaunch.WriteConfig(path, json);
Check(File.ReadAllText(path) == json && !File.Exists(path + ".tmp"), "config written (no temp file left)");
CheckNoPlainText(HeadlessPw);
Check(Same(HeadlessLaunch.BuildArguments(path, @"C:\Turbine\Asheron's Call"),
"run", "--config", path, "--launcher", "--ac-folder", @"C:\Turbine\Asheron's Call"), "arguments with the AC folder");
Check(Same(HeadlessLaunch.BuildArguments(path, null), "run", "--config", path, "--launcher"), "arguments without");
Check(HeadlessLaunch.AcFolderFor(@"C:\Turbine\Asheron's Call\acclient.exe") == @"C:\Turbine\Asheron's Call", "AC folder from the client path");
Check(HeadlessLaunch.AcFolderFor(" ") == null && HeadlessLaunch.AcFolderFor(null) == null, "no client path: no AC folder");
Check(HeadlessLaunch.ResolveExePath("", @"C:\Games\RynthCore") == @"C:\Games\RynthCore\Headless\rynth-headless.exe", "default exe beside the launcher");
Check(HeadlessLaunch.ResolveExePath(" \"D:\\h\\rynth-headless.exe\" ", @"C:\x") == @"D:\h\rynth-headless.exe", "set exe (trimmed, unquoted)");
// HeadlessPluginPaths empty = the x64 plugins the installer ships in <launcher>\Headless\plugins\<Name>\.
string install = Path.Combine(_dir, "install");
Check(HeadlessLaunch.DefaultPluginPaths(install).Count == 0, "no Headless\\plugins folder: no default plugins");
string shipped = Path.Combine(install, "Headless", "plugins");
Directory.CreateDirectory(Path.Combine(shipped, "RynthAi"));
Directory.CreateDirectory(Path.Combine(shipped, "Empty"));
File.WriteAllText(Path.Combine(shipped, "RynthAi", "RynthCore.Plugin.RynthAi.dll"), "x");
File.WriteAllText(Path.Combine(shipped, "RynthAi", "RynthCore.PluginSdk.dll"), "x");
string shippedAi = Path.Combine(shipped, "RynthAi", "RynthCore.Plugin.RynthAi.dll");
Check(Same(HeadlessLaunch.DefaultPluginPaths(install), shippedAi), "default plugins: each folder's RynthCore.Plugin.<folder>.dll, not its dependencies");
Check(Same(HeadlessLaunch.ResolvePluginPaths([], install), shippedAi) &&
Same(HeadlessLaunch.ResolvePluginPaths(null, install), shippedAi) &&
Same(HeadlessLaunch.ResolvePluginPaths([" ", "\"\""], install), shippedAi), "an empty list uses the shipped plugins");
Check(Same(HeadlessLaunch.ResolvePluginPaths([" \"D:\\x64\\RynthCore.Plugin.RynthAi.dll\" "], install), @"D:\x64\RynthCore.Plugin.RynthAi.dll"),
"a set list is used as it is (and nothing shipped is added)");
int pid = Environment.ProcessId;
Check(HeadlessLaunch.StopEventName(pid) == $@"Local\RynthHeadless.Stop.{pid}", "stop event name");
Check(!HeadlessLaunch.TrySignalStop(pid), "no stop event: TrySignalStop is false (the launcher kills instead)");
using (var stop = new EventWaitHandle(false, EventResetMode.ManualReset, HeadlessLaunch.StopEventName(pid)))
{
Check(HeadlessLaunch.TrySignalStop(pid) && stop.WaitOne(0), "TrySignalStop sets the process's stop event");
}
});
// ── saved account passwords (DPAPI) ─────────────────────────────────
// Test-only passwords; nothing here touches the real settings file.
const string Pw = "t3st pw \"quoted\" ü";
@ -753,6 +976,45 @@ internal static class Program
private static InjectionMode Mode(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).InjectionMode;
/// <summary><see cref="Sample"/> plus "h", a Headless account.</summary>
private static AppSettings SampleWithHeadless()
{
AppSettings s = Sample();
s.AccountProfiles.Add(new LaunchAccountProfile { Id = "h", AccountName = "H", InjectionMode = InjectionMode.Headless });
return s;
}
private static string HeadlessSidecar => Path.Combine(_dir, HeadlessAccountModes.FileName);
private static List<string> HeadlessIds()
{
if (!File.Exists(HeadlessSidecar)) return new();
JsonNode node = JsonNode.Parse(File.ReadAllText(HeadlessSidecar))!;
return node["HeadlessAccountIds"]!.AsArray().Select(n => (string)n!).ToList();
}
private static string Json(object? value) => JsonSerializer.Serialize(value);
/// <summary>The run config's shape as rynth-headless declares it (src\RynthCore.Headless.Cli\RunConfig.cs).</summary>
private sealed class CliRunConfig
{
public string Host { get; set; } = "";
public int Port { get; set; }
public string ServerName { get; set; } = "";
public List<string> Plugins { get; set; } = new();
public List<CliSession> Sessions { get; set; } = new();
}
private sealed class CliSession
{
public string LauncherProfileId { get; set; } = "";
public string Account { get; set; } = "";
public string? Character { get; set; }
public List<string> Commands { get; set; } = new();
public int StaySeconds { get; set; }
public bool Reconnect { get; set; }
}
/// <summary>
/// A swap as the launcher leaves it: the failed per-server stash copied over the live file,
/// plus the account's name-only stash (same bytes when <paramref name="legacyMatches"/>).
@ -778,6 +1040,12 @@ internal static class Program
string name = Path.GetFileName(path);
Check(!File.ReadAllText(path).Contains("DecalBridge"), $"{name} has no \"DecalBridge\"");
Check(OldLauncherCanRead(path), $"the old launcher can read {name}");
// Every InjectionMode written is one the oldest launcher knows (never Headless or 3).
foreach (JsonNode? a in JsonNode.Parse(File.ReadAllText(path))!["AccountProfiles"]?.AsArray() ?? new JsonArray())
{
string? mode = a?["InjectionMode"]?.ToString();
Check(mode is null or "RynthCore" or "Decal", $"{name}: account {a?["Id"]} InjectionMode is {mode}");
}
}
}
@ -831,6 +1099,31 @@ internal static class Program
catch (JsonException) { return false; }
}
// A launcher with the Decal bridge but before Headless (its InjectionMode stops at DecalBridge).
private enum BridgeInjectionMode { RynthCore = 0, Decal = 1, DecalBridge = 2 }
private sealed class BridgeAccount
{
public string Id { get; set; } = "";
public BridgeInjectionMode InjectionMode { get; set; }
}
private sealed class BridgeSettings
{
public List<BridgeAccount> AccountProfiles { get; set; } = new();
}
private static bool BridgeLauncherCanRead(string path)
{
try
{
BridgeSettings? s = JsonSerializer.Deserialize<BridgeSettings>(File.ReadAllText(path), OldOptions);
// Strict like the old enum converter: a value it has no name for is "unreadable" too.
return s != null && s.AccountProfiles.All(a => Enum.IsDefined(a.InjectionMode));
}
catch (JsonException) { return false; }
}
private static LaunchServerProfile Server(AcEmulatorKind kind) => new()
{
Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind

View file

@ -34,6 +34,7 @@ internal static class Program
MoveProtocol();
LogRollover();
ServeGuards();
HeadlessClients();
if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas);
if (portal != null) RealSpellTable(portal);
if (cell != null) RealWorldMap(cell, outFile);
@ -43,6 +44,36 @@ internal static class Program
return _failed == 0 ? 0 : 1;
}
// ── headless characters (rynth-headless) ────────────────────────────────
private static void HeadlessClients()
{
Console.WriteLine("headless clients");
var names = new Dictionary<int, string> { [100] = "acclient", [200] = "rynth-headless", [300] = "notepad" };
string? Name(int pid) => names.TryGetValue(pid, out string? n) ? n : null;
Check(ClientLiveness.IsAlive(100, false, 0, Name), "a retail file: its own pid is an acclient");
Check(!ClientLiveness.IsAlive(300, false, 0, Name), "a recycled pid that isn't an acclient is dead");
Check(!ClientLiveness.IsAlive(1_000_000_001, false, 0, Name), "no such process: dead");
Check(ClientLiveness.IsAlive(1_000_000_001, true, 200, Name), "headless: the host process is a rynth-headless");
Check(!ClientLiveness.IsAlive(1_000_000_001, true, 300, Name), "headless: a recycled host pid is dead");
Check(!ClientLiveness.IsAlive(1_000_000_001, true, 0, Name), "headless with no host pid: dead");
Check(!ClientLiveness.IsAlive(200, false, 0, Name), "a retail file never counts a rynth-headless as an acclient");
// What StatusExporter writes (trimmed): the agent's model reads the headless fields.
var m = JsonSerializer.Deserialize("""
{"schema":"rynthcore.client-status/1","ts":"2026-10-28T12:00:00.000Z","host":"PC","pid":1012345600,
"account":"testaccount","character":"+Test Character","server":"ACEmulator","fps":66,"pluginTicksPerSec":66,"inWorld":true,
"bot":null,"enchantments":[{"spellId":2,"secondsRemaining":12.5}],
"opos":{"cell":"01D90108","indoor":true,"wx":100.5,"wy":200.25,"z":-6,"heading":90},
"headless":true,"hostPid":4242,"hostProcess":"rynth-headless"}
""", AgentJsonContext.Default.StatusFileModel)!;
Check(m.Headless && m.HostPid == 4242 && m.HostProcess == "rynth-headless", "headless fields read");
Check(m.Pid == 1012345600 && m.InWorld && m.Fps == 66, "the usual fields still read");
var retail = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":7}""", AgentJsonContext.Default.StatusFileModel)!;
Check(!retail.Headless && retail.HostPid == 0, "a retail file is not headless");
}
// ── serve guards (remote access) ────────────────────────────────────────
private static void ServeGuards()

View file

@ -33,6 +33,7 @@
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\DatDatabase.cs" Link="Agent\Dat\DatDatabase.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\StatusFileCache.cs" Link="Agent\StatusFileCache.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\ServeGuard.cs" Link="Agent\ServeGuard.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\ClientLiveness.cs" Link="Agent\ClientLiveness.cs" />
</ItemGroup>
<ItemGroup>