Files

300 lines
16 KiB
C#

using System.Diagnostics;
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
var tests = new (string Name, Action Check)[]
{
("flat support and ground-height interval", FlatFloor),
("continuous high-speed floor and wall collision", HighSpeed),
("wall sliding, departure and corner", Walls),
("ceiling and underside", Ceiling),
("sloped floor and landing", Slope),
("walking over an edge releases support", Edge),
("triangle edge and vertex sweep", TriangleEdges),
("camera sphere sweep", Camera),
("original-scale translated room and repeated seam crossings", TranslatedRoom),
("invisible source triangles and invalid input", SourcePolicy),
("original lab spawn, traversal, jump and deterministic replay", OriginalLab),
};
foreach (var (name, check) in tests)
{
check();
Console.WriteLine($"PASS {name}");
}
Console.WriteLine($"Collision checks: {tests.Length} passed");
static void FlatFloor()
{
var mesh = new Builder().Floor(0, -100, 100, -100, 100).Floor(10, -100, 100, -100, 100).Build();
var scene = new SceneCollision(mesh);
Near(scene.GroundHeight(new Vector3(0, 5, 0), 20)!.Value, 0, .0001f, "floor below queried point");
Near(scene.GroundHeight(new Vector3(0, 5, 0), 20, 6)!.Value, 10, .0001f, "highest permitted surface");
Check(scene.GroundHeight(new Vector3(0, 5, 0), 4) is null, "floor outside drop interval");
var standing = scene.Move(Vector3.Zero, Vector3.Zero, 1, 4);
Check(standing.Grounded, "stationary support");
Near(standing.Position.Y, SceneCollision.Skin, .01f, "surface skin");
var moved = scene.Move(standing.Position, new Vector3(30, 0, 20), 1, 4);
Check(moved.Grounded && !moved.HitWall && !moved.HitCeiling, "tangent floor motion");
Near(moved.Position.X, 30, .01f, "free horizontal x");
Near(moved.Position.Z, 20, .01f, "free horizontal z");
}
static void HighSpeed()
{
var scene = new SceneCollision(new Builder().Floor(0, -20000, 20000, -20000, 20000)
.WallX(5, 0, 100, -100, 100).Build());
var landing = scene.Move(new Vector3(0, 1000, 0), new Vector3(0, -10000, 0), 1, 4);
Check(landing.Grounded, "fast fall lands");
Near(landing.Position.Y, SceneCollision.Skin, .01f, "no floor tunneling");
var wall = scene.Move(new Vector3(0, 1, 0), new Vector3(10000, 0, 0), 1, 4);
Check(wall.HitWall, "fast horizontal hit");
Near(wall.Position.X, 4 - SceneCollision.Skin, .02f, "no wall tunneling");
var diagonal = scene.Move(new Vector3(-100, 100, 0), new Vector3(10000, -10000, 20), 1, 4);
Check(diagonal.Grounded && diagonal.HitWall, $"fast diagonal hits floor and wall: {diagonal}");
Check(diagonal.Position.X <= 4 && diagonal.Position.Y >= -.01f, "diagonal safe position");
}
static void Walls()
{
var scene = new SceneCollision(new Builder().Floor(0, -100, 100, -100, 100)
.WallX(5, 0, 20, -100, 100).WallZ(5, 0, 20, -100, 100).Build());
var slide = scene.Move(new Vector3(0, .1f, -10), new Vector3(10, 0, 10), 1, 4);
Near(slide.Position.X, 4 - SceneCollision.Skin, .02f, "wall x limit");
Near(slide.Position.Z, 0, .02f, "wall preserves tangent travel");
var leave = scene.Move(slide.Position, new Vector3(-3, 0, 0), 1, 4);
Near(leave.Position.X, slide.Position.X - 3, .02f, "depart contact freely");
var corner = scene.Move(new Vector3(0, .1f, 0), new Vector3(100, 0, 100), 1, 4);
Near(corner.Position.X, 4 - SceneCollision.Skin, .02f, "corner x");
Near(corner.Position.Z, 4 - SceneCollision.Skin, .02f, "corner z");
var resting = corner.Position;
for (var i = 0; i < 100; i++) resting = scene.Move(resting, new Vector3(1, -.2f, 1), 1, 4).Position;
Check(Vector3.Distance(resting, new Vector3(4 - SceneCollision.Skin, SceneCollision.Skin, 4 - SceneCollision.Skin)) < .03f,
"corner remains stable under sustained input");
}
static void Ceiling()
{
var scene = new SceneCollision(new Builder().Floor(0, -100, 100, -100, 100)
.Floor(6, -100, 100, -100, 100).Build());
var rise = scene.Move(new Vector3(0, .1f, 0), new Vector3(0, 100, 0), 1, 4);
Check(rise.HitCeiling && !rise.Grounded, "ceiling hit classification");
Near(rise.Position.Y, 2 - SceneCollision.Skin, .02f, "head stops below underside");
var descend = scene.Move(rise.Position, new Vector3(0, -20, 0), 1, 4);
Check(descend.Grounded, "leaves underside and lands");
Near(descend.Position.Y, SceneCollision.Skin, .02f, "underside does not trap actor");
}
static void Slope()
{
var builder = new Builder().Quad(new(-30, -15, -30), new(-30, -15, 30), new(30, 15, 30), new(30, 15, -30));
var scene = new SceneCollision(builder.Build());
Near(scene.GroundHeight(new Vector3(4, 10, 0), 100)!.Value, 2, .0001f, "slope height");
var landed = scene.Move(new Vector3(0, 20, 0), new Vector3(0, -30, 0), 1, 4);
Check(landed.Grounded, "sloped landing");
// Sliding projects the remaining downward displacement onto the slope.
Check(landed.Position.Y >= landed.Position.X * .5f - .01f, "slope cannot penetrate");
var position = scene.Move(Vector3.Zero, Vector3.Zero, 1, 4).Position;
for (var i = 0; i < 20; i++)
{
var move = scene.Move(position, new Vector3(.25f, -.01f, 0), 1, 4);
Check(move.Grounded, "slope support while climbing");
Check(move.Position.Y >= move.Position.X * .5f, "climb above plane");
position = move.Position;
}
Check(position.X > 3 && position.Y > 1.5f, "walk uphill");
}
static void Edge()
{
var scene = new SceneCollision(new Builder().Floor(0, -10, 0, -10, 10).Build());
var standing = scene.Move(new Vector3(-2, 0, 0), Vector3.Zero, 1, 4);
var moved = scene.Move(standing.Position, new Vector3(5, 0, 0), 1, 4);
Check(!moved.Grounded, "support is evaluated at final position");
var falling = scene.Move(moved.Position, new Vector3(0, -5, 0), 1, 4);
Check(!falling.Grounded && falling.Position.Y < -4, "fall beyond ledge");
}
static void TriangleEdges()
{
var scene = new SceneCollision(new Builder().Triangle(new(5, 0, 0), new(5, 8, 0), new(5, 0, 8)).Build());
var edge = scene.Move(new Vector3(0, 0, -.5f), new Vector3(1000, 0, 0), 1, 4);
Check(edge.HitWall && edge.Position.Z < -.5f, $"capsule catches and slides around triangle edge with center outside face: {edge}");
var miss = scene.Move(new Vector3(0, 0, -2), new Vector3(10, 0, 0), 1, 4);
Near(miss.Position.X, 10, .0001f, "clears isolated edge");
var camera = scene.ClipCamera(new Vector3(0, -.5f, -.5f), new Vector3(10, -.5f, -.5f), 1);
Check(camera.X < 5, "sphere catches triangle vertex");
}
static void Camera()
{
var scene = new SceneCollision(new Builder().WallX(5, -10, 10, -10, 10).Build());
var clipped = scene.ClipCamera(Vector3.Zero, new Vector3(1000, 0, 0), .5f);
Near(clipped.X, 4.5f - SceneCollision.Skin, .02f, "camera clips wall");
var free = scene.ClipCamera(Vector3.Zero, new Vector3(-100, 0, 0), .5f);
Near(free.X, -100, .001f, "camera clear path");
}
static void TranslatedRoom()
{
var scene = new SceneCollision(new Builder().Floor(.5486332f, 4000, 6000, -2000, 3000)
.WallX(5430, .5486332f, 1000, -2000, 3000)
.WallZ(2433, .5486332f, 1000, 4000, 6000).Build());
var start = new Vector3(5071.933f, .5486332f, 824.10394f);
var fast = scene.Move(start, new Vector3(100000, -100000, 100000), 34.7f, 209.4361f);
Check(fast.Grounded && fast.HitWall, $"translated room fast collision: {fast}");
Check(fast.Position.X <= 5430 - 34.7f + .02f && fast.Position.Z <= 2433 - 34.7f + .02f, "translated room walls");
Near(fast.Position.Y, .5486332f + SceneCollision.Skin, .02f, "translated room floor");
var position = scene.Move(start, Vector3.Zero, 34.7f, 209.4361f).Position;
for (var i = 0; i < 2000; i++)
{
var movement = new Vector3(i % 400 < 200 ? 2 : -2, -.3f, i % 200 < 100 ? 2 : -2);
var moved = scene.Move(position, movement, 34.7f, 209.4361f);
Check(moved.Grounded, "translated floor repeated support");
Near(moved.Position.Y, .5486332f + SceneCollision.Skin, .02f, "translated floor repeated height");
position = moved.Position;
}
}
static void SourcePolicy()
{
var mesh = new Builder().WallX(5, 0, 20, -20, 20).Build() with { HasExplicitDraws = true, Draws = [] };
var scene = new SceneCollision(mesh);
Check(scene.TriangleCount == 2, "unrendered source proxy retained");
Check(scene.Move(Vector3.Zero, new Vector3(100, 0, 0), 1, 4).HitWall, "proxy blocks under provisional policy");
var source = mesh with { CollisionPolygons = [new(1, 0, Vector3.UnitX, "wall", "NcWater"), new(1, 1, Vector3.UnitX, "wall", "NcWater")] };
var excluded = new SceneCollision(source);
Check(excluded.TriangleCount == 0 && !excluded.Move(Vector3.Zero, new(100, 0, 0), 1, 4).HitWall,
"NC shape is drawn separately but omitted from terrain registration");
var materialOnly = source with { CollisionPolygons = source.CollisionPolygons.Select(p => p with { ShapeName = "wall", MaterialName = "ncwater" }).ToArray() };
Check(new SceneCollision(materialOnly).TriangleCount == 2, "NC material name alone does not disable collision");
var degenerate = new SceneCollision(new Builder().Triangle(Vector3.Zero, Vector3.One, Vector3.One).Build());
Check(degenerate.TriangleCount == 0, "degenerate triangles skipped");
Throws<ArgumentOutOfRangeException>(() => scene.Move(Vector3.Zero, Vector3.Zero, 0, 4));
Throws<ArgumentOutOfRangeException>(() => scene.Move(Vector3.Zero, Vector3.Zero, 3, 4));
Throws<ArgumentOutOfRangeException>(() => scene.Move(new Vector3(float.NaN, 0, 0), Vector3.Zero, 1, 4));
Throws<ArgumentException>(() => new SceneCollision(new Mesh([], [0, 1, 2])));
Throws<ArgumentException>(() => new SceneCollision(new Builder().Triangle(Vector3.Zero,
new Vector3(float.PositiveInfinity, 0, 0), Vector3.One).Build()));
Throws<ArgumentException>(() => new SceneCollision(new Builder().Triangle(Vector3.Zero,
new Vector3(1e30f, 0, 0), new Vector3(0, 1e30f, 0)).Build()));
}
static void OriginalLab()
{
var root = FindRoot();
var file = Path.Combine(root, "artifacts/extracted/level1b/scene.json");
Check(File.Exists(file), "prepared original lab required (run extractors/prepare.py)");
var mesh = Mesh.LoadSceneJson(file);
var scene = new SceneCollision(mesh);
Check(mesh.Indices.Length / 3 == 2869 && mesh.CollisionPolygons.Count(p => !p.TerrainCollision) == 18,
"NC registration exclusion preserves all render/source polygons");
Check(mesh.CollisionPolygons.Where(p => !p.TerrainCollision).All(p => p.ShapeId == 94 && p.ShapeName == "ncwater"),
"Actual shape names are recovered from prepared mesh records");
Check(scene.TriangleCount == 2851, "source terrain registration excludes18 NC-shape triangles while retaining proxies");
var originalRoot = new Vector3(5071.933105f, 26.661896f, 824.103943f);
var floor = scene.GroundHeight(originalRoot, 100)!.Value;
Near(floor, .5486332f, .001f, "actual lab floor below GAM root");
var stopwatch = Stopwatch.StartNew();
foreach (var radius in new[] { 24f, 34.7f })
{
var feet = new Vector3(originalRoot.X, floor, originalRoot.Z);
var standing = scene.Move(feet, Vector3.Zero, radius, 209.4361f);
Check(standing.Grounded, $"actual lab standing radius {radius}");
Check(Vector3.Distance(standing.Position, feet) < .2f, $"lab spawn does not need horizontal relocation radius {radius}");
var first = Traverse(scene, standing.Position, radius);
var second = Traverse(scene, standing.Position, radius);
Check(first == second, "same input stream replays identically");
Check(Vector3.Distance(first, standing.Position) > 100, $"actual lab traversal radius {radius}");
// This direction reaches original geometry near the east side of the
// room, rather than an invented room-sized bounding box.
var east = standing.Position;
var hitOriginalWall = false;
for (var i = 0; i < 600; i++)
{
var moved = scene.Move(east, new Vector3(3, -.3f, 0), radius, 209.4361f);
hitOriginalWall |= moved.HitWall;
Check(Finite(moved.Position), "original wall traversal finite");
Check(moved.Position.Y > floor - .05f, "original wall traversal above lab floor");
east = moved.Position;
}
Check(hitOriginalWall && east.X < standing.Position.X + 1750, $"original east wall blocks radius {radius}");
var position = standing.Position;
var velocity = 550f;
var reachedAir = false;
var landed = false;
for (var i = 0; i < 180; i++)
{
velocity -= 1064f / 60f;
var moved = scene.Move(position, new Vector3(0, velocity / 60f, 0), radius, 209.4361f);
Check(Finite(moved.Position), "lab jump finite");
if (moved.HitCeiling && velocity > 0) velocity = 0;
if (!moved.Grounded) reachedAir = true;
if (reachedAir && moved.Grounded && velocity < 0) { landed = true; position = moved.Position; break; }
position = moved.Position;
}
Check(reachedAir && landed, $"lab jump rises and lands radius {radius}");
Near(position.Y, floor + SceneCollision.Skin, .03f, "lab landing above floor");
Console.WriteLine($" lab radius={radius}: start={standing.Position}, traverse={first}, eastWall={east}, jumpLand={position}");
}
Console.WriteLine($" lab replay and jump checks {stopwatch.ElapsedMilliseconds} ms");
}
static Vector3 Traverse(SceneCollision scene, Vector3 position, float radius)
{
var angle = 155f * MathF.PI / 180;
var forward = new Vector3(-MathF.Sin(angle), 0, MathF.Cos(angle));
for (var i = 0; i < 240; i++)
{
var moved = scene.Move(position, forward * (180f / 60) - Vector3.UnitY * .3f, radius, 209.4361f);
Check(Finite(moved.Position), "lab traversal finite");
var below = scene.GroundHeight(moved.Position + Vector3.UnitY * .01f, 1000);
if (below.HasValue) Check(moved.Position.Y >= below.Value - .02f, "lab traverse stays above nearby floor");
position = moved.Position;
}
return position;
}
static string FindRoot()
{
var directory = new DirectoryInfo(Environment.CurrentDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "GamePort.slnx"))) return directory.FullName;
directory = directory.Parent;
}
throw new InvalidOperationException("Run from within GamePort");
}
static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
static void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: actual={actual}, expected={expected}, tolerance={tolerance}");
static void Throws<T>(Action check) where T : Exception
{
try { check(); } catch (T) { return; }
throw new Exception($"Expected {typeof(T).Name}");
}
sealed class Builder
{
private readonly List<MeshVertex> vertices = [];
private readonly List<uint> indices = [];
public Builder Triangle(Vector3 a, Vector3 b, Vector3 c)
{
var offset = (uint)vertices.Count;
vertices.Add(new(a, Vector2.Zero, Vector3.One));
vertices.Add(new(b, Vector2.Zero, Vector3.One));
vertices.Add(new(c, Vector2.Zero, Vector3.One));
indices.AddRange([offset, offset + 1, offset + 2]);
return this;
}
public Builder Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d) => Triangle(a, b, c).Triangle(a, c, d);
public Builder Floor(float y, float left, float right, float back, float front) =>
Quad(new(left, y, back), new(left, y, front), new(right, y, front), new(right, y, back));
public Builder WallX(float x, float bottom, float top, float back, float front) =>
Quad(new(x, bottom, back), new(x, top, back), new(x, top, front), new(x, bottom, front));
public Builder WallZ(float z, float bottom, float top, float left, float right) =>
Quad(new(left, bottom, z), new(left, top, z), new(right, top, z), new(right, bottom, z));
public Mesh Build() => new(vertices.ToArray(), indices.ToArray());
}