using System.Globalization; using System.Numerics; using System.Text.RegularExpressions; using GamePort.Assets; using GamePort.Game; var groups = 0; void Check(bool value, string message) { if (!value) throw new Exception(message); } void Near(float actual, float expected, float tolerance, string message) => Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: {actual} != {expected}"); void Test(string name, Action action) { action(); groups++; Console.WriteLine($"PASS {name}"); } DynamicBoxCollider Box() => new(4, Vector3.Zero, new(-5), new(5), Matrix4x4.Identity); DynamicSphereMotion Sphere(float x = 0) => new(new(x, 0, -1), new(x, 0, 0), 60); Test("door constructor defaults and HasCollision sentinel", () => { Check(DynamicSceneCollision.DoorRadius == 40 && DynamicSceneCollision.DoorMode == 2, "door dimensions/mode"); Check(DynamicSceneCollision.DoorCollisionFlags(-1) == (true, false), "-1 must preserve pair on/integration off"); Check(DynamicSceneCollision.DoorCollisionFlags(0) == (false, false), "explicit collision off"); Check(DynamicSceneCollision.DoorCollisionFlags(1) == (true, true), "explicit collision on"); }); Test("inclusive quantized-root broadphase and large-cube quirk", () => { Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(140)), "140 boundary rejected"); Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(140.01f)), "outside 140 accepted"); var large = Box() with { LocalMin = new(-1000), LocalMax = new(1000) }; Check(!DynamicSceneCollision.BroadPhase(large, Sphere(200)), "cube extents silently enlarged root broadphase"); Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(100) with { Mode = 2 }), "box/box boundary"); Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(100.01f) with { Mode = 2 }), "box/box sum radius exceeded"); }); Test("pair, entity and sphere-geometry gates avoid narrowphase", () => { DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("disabled narrowphase invoked"); Check(!DynamicSceneCollision.Resolve(Box() with { CollisionEnabled = false }, Sphere(), Fail).Contact, "box gate"); Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { CollisionEnabled = false }, Fail).Contact, "sphere gate"); Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { GeometryCollisionEnabled = false }, Fail).Contact, "geometry gate"); Check(!DynamicSceneCollision.Resolve(Box(), Sphere(), Fail, false).Contact, "mutual exclusion gate"); }); Test("oriented source-local corners and current translation", () => { var local = Box() with { LocalMin = new(-1, -2, -3), LocalMax = new(4, 5, 6) }; var corners = DynamicSceneCollision.Corners(local); Check(corners[0] == local.LocalMin && corners[7] == local.LocalMax, "min/max corners"); Check(corners[1] == new Vector3(-1, -2, 6) && corners[6] == new Vector3(4, 5, -3), "corner bit order"); var transform = Matrix4x4.CreateRotationY(MathF.PI / 2) * Matrix4x4.CreateTranslation(100, 500, -80); var moved = DynamicSceneCollision.Corners(local with { Root = new(100, 500, -80), LocalToWorld = transform }); for (var i = 0; i < 8; i++) Check(moved[i] == Vector3.Transform(corners[i], transform), "oriented transform"); }); Test("twelve source triangle order, normals and closed surface", () => { var box = Box(); var corners = DynamicSceneCollision.Corners(box); var triangles = DynamicSceneCollision.Triangles(box); Check(triangles.Length == 12, "cube triangle count"); Check(triangles[0] == new SupportTriangle(corners[0], corners[1], corners[2], 4, 0), "first original face"); Check(triangles[11] == new SupportTriangle(corners[7], corners[6], corners[2], 4, 11), "last original face"); var edges = new Dictionary<(int, int), int>(); foreach (var triangle in triangles) { var normal = Vector3.Cross(triangle.B - triangle.A, triangle.C - triangle.A); Check(Vector3.Dot(normal, (triangle.A + triangle.B + triangle.C) / 3) > 0, "face winding is not outward"); var ids = new[] { Array.IndexOf(corners, triangle.A), Array.IndexOf(corners, triangle.B), Array.IndexOf(corners, triangle.C) }; for (var i = 0; i < 3; i++) { var a = ids[i]; var b = ids[(i + 1) % 3]; var key = (Math.Min(a, b), Math.Max(a, b)); edges[key] = edges.GetValueOrDefault(key) + 1; } } Check(edges.Count == 18 && edges.Values.All(n => n == 2), "cube surface has a gap/duplicate"); }); Test("injected narrowphase and response-inhibition semantics", () => { var calls = 0; DynamicCollisionResponse Query(DynamicBoxSweep sweep) { calls++; Check(sweep.Triangles.Count == 12 && sweep.Box.Identity == 4 && sweep.Sphere == Sphere(), "sweep contract"); return new(true, new(1, 2, 3)); } Check(DynamicSceneCollision.Resolve(Box(), Sphere(), Query) == new DynamicCollisionResponse(true, new(1, 2, 3)), "response lost"); Check(DynamicSceneCollision.Resolve(Box() with { InhibitResponse = true }, Sphere(), Query) == new DynamicCollisionResponse(true, Sphere().Position), "inhibited response moved body"); Check(calls == 2, "response inhibition incorrectly suppressed contact query"); var noContact = DynamicSceneCollision.Resolve(Box(), Sphere(), _ => new(false, new(10))); Check(!noContact.Contact && noContact.Position == Sphere().Position, "failed query moved body"); }); Test("mode2 second actor bypasses triangle response", () => { DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("box/box shortcut swept triangles"); var body = Sphere(80) with { Mode = 2 }; Check(DynamicSceneCollision.Resolve(Box(), body, Fail) == new DynamicCollisionResponse(true, body.Position), "box/box shortcut"); }); Test("source motion changes geometry without a closed-position residue", () => { var box = Box(); var closed = DynamicSceneCollision.Corners(box); var open = DynamicSceneCollision.Corners(box with { Root = new(0, 500, 0), LocalToWorld = Matrix4x4.CreateTranslation(0, 500, 0) }); for (var i = 0; i < closed.Length; i++) Check(open[i] - closed[i] == new Vector3(0, 500, 0), "door corner did not move"); }); Test("invalid source cube and transform rejected", () => { foreach (var box in new[] { Box() with { LocalMin = new(10) }, Box() with { Radius = float.NaN }, Box() with { LocalToWorld = new Matrix4x4() }, Box() with { Root = new(float.PositiveInfinity) } }) { var threw = false; try { DynamicSceneCollision.BroadPhase(box, Sphere()); } catch (ArgumentOutOfRangeException) { threw = true; } Check(threw, "malformed collider accepted"); } }); Test("actual lab bars bounds, closed/open passage with provisional sphere adapter", () => { var original = Path.GetFullPath("../Original"); var level = GamLevel.Load(Path.Combine(original, "gam/level1b.gam")); var bars = level.Entities.Single(e => e.Kind == "3DUD" && e.Tag == "bars"); Check(bars.Integer("HasCollision") == -1 && bars.Integer("CanMove") == 1 && bars.Rotation == Vector3.Zero, "lab authored flags"); var asePath = Directory.EnumerateFiles(Path.Combine(original, "ASE")).Single(p => Path.GetFileName(p).Equals("bars.ase", StringComparison.OrdinalIgnoreCase)); var text = File.ReadAllText(asePath); var count = int.Parse(Regex.Match(text, @"\*MESH_NUMVERTEX\s+(\d+)").Groups[1].Value, CultureInfo.InvariantCulture); var points = Regex.Matches(text, @"\*MESH_VERTEX\s+\d+\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)") .Take(count).Select(m => new Vector3(float.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), float.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture), float.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture))).ToArray(); Check(points.Length == 42, "source bars vertex count"); var min = points.Aggregate(Vector3.Min); var max = points.Aggregate(Vector3.Max); Near(min.X, -223.8069f, .0001f, "source xmin"); Near(min.Y, -18.7273f, .0001f, "source ymin"); Near(max.Y, 391.2706f, .0001f, "source ymax"); Near(max.Z, 16.8051f, .0001f, "source zmax"); var box = new DynamicBoxCollider(bars.Offset, bars.Position, min, max, Matrix4x4.CreateTranslation(bars.Position)); var body = new DynamicSphereMotion(bars.Position + new Vector3(0, 76, -100), bars.Position + new Vector3(0, 76, -20), 60); // This adapter verifies integration/blocked passage only. SceneCollision's // sweep/slide remains the explicitly provisional consumer, not original47BD80. var calls = 0; DynamicCollisionResponse Provisional(DynamicBoxSweep sweep) { calls++; var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C }) .Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(); var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray()); var radius = sweep.Sphere.Radius; var result = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius, sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2); var position = result.Position + Vector3.UnitY * radius; return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position); } var closed = DynamicSceneCollision.Resolve(box, body, Provisional); Check(closed.Contact && closed.Position.Z < bars.Position.Z - 76, "closed bars did not block source-sized sphere"); var raised = bars.Position + Vector3.UnitY * bars.Number("OpenAmount"); var open = DynamicSceneCollision.Resolve(box with { Root = raised, LocalToWorld = Matrix4x4.CreateTranslation(raised) }, body, Provisional); Check(!open.Contact && open.Position == body.Position && calls == 1, "raised bars still block closed location"); }); Console.WriteLine($"{groups} dynamic collision groups passed; injected narrowphase/runtime fidelity remain unverified.");