Add controllable lab walking checkpoint with collision and chase camera

This commit is contained in:
UnixNight committed 2026-10-23 23:29:40 -04:00
1 parent 37fa18094f
commit 58424120bb
26 files changed
+1848 -110

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
namespace GamePort.Game;
/// <summary>Explicit port policy: 60 simulation calls/second, independent of presentation.</summary>
public sealed class FixedStepClock
{
public const float Step = 1f / 60;
private double accumulated;
public int Advance(double elapsed)
{
if (!double.IsFinite(elapsed) || elapsed < 0) throw new ArgumentOutOfRangeException(nameof(elapsed));
accumulated += Math.Min(elapsed, 0.25);
var steps = (int)Math.Floor((accumulated + 1e-10) * 60);
accumulated -= steps / 60.0;
return steps;
}
public void Reset() => accumulated = 0;
}
+145
View File
@@ -0,0 +1,145 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall }
/// <summary>
/// No-gadget walking checkpoint. Recovered input/arithmetic is described in
/// movement-checkpoint.md. Capsule, floor-derived pivot and 60Hz are port policies;
/// original collision, intro, object interactions and animation timing remain open.
/// </summary>
public sealed class LabSimulation
{
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision;
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight;
private float targetYaw, jumpHeldTime;
private int jumpState;
public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; }
public float Yaw { get; private set; }
public float Speed { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; }
public int Jumps { get; private set; }
public int Landings { get; private set; }
public int WallHits { get; private set; }
public float Travel { get; private set; }
public float MaximumRise { get; private set; }
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw)
{
this.collision = collision;
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
modelMinimumY = bounds.Min.Y;
BodyHeight = bounds.Max.Y - bounds.Min.Y;
var floor = collision.GroundHeight(start, 2500)
?? throw new InvalidDataException("No support below GAM startpoint");
rootHeight = start.Y - floor;
Reset();
}
public void Reset()
{
var floor = collision.GroundHeight(sourceStart, 2500)!.Value;
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z);
Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw;
Speed = jumpHeldTime = 0;
jumpState = 0;
Grounded = true;
Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0;
CameraEye = DesiredEye();
}
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
// Table generated with modern trig; x87 bit-identical table recovery is pending.
public static (float Sin, float Cos) Trig(float degrees)
{
var index = (int)(degrees * 45.5111122f) & 0x3fff;
var radians = index * (Math.Tau / 16384);
return ((float)Math.Sin(radians), (float)Math.Cos(radians));
}
public void Step(PlayerInput input)
{
const float dt = FixedStepClock.Step;
var wasGrounded = Grounded;
float lateral = 0;
if (Grounded)
{
if (!input.Jump) jumpState = 0;
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
else if (!input.Forward) Speed = RecoveredMotion.ReleaseSpeed(Speed);
}
var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 360;
var (sin, cos) = Trig(Yaw);
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt);
var impulse = Vector3.Zero;
if (Grounded && input.Jump && jumpState == 0)
{
impulse.Y = RecoveredMotion.JumpImpulse;
jumpState = 1;
jumpHeldTime = 0;
Grounded = false;
Jumps++;
}
if (!Grounded && jumpState == 1)
{
if (!input.Jump) jumpState = 2;
else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL.
}
else if (!Grounded && jumpState == 2 && input.Jump)
jumpState = 0; // Renewed hold enters the same disabled-gadget reset path.
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
RecoveredMotion.Gravity * 0.33f, RecoveredMotion.Gravity, dt);
var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
Position = result.Position;
Grounded = result.Grounded && velocity.Y <= 0;
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
Velocity = velocity;
if (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - sourceStart.Y + rootHeight);
Steps++;
var desired = DesiredEye();
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
CameraEye = collision.ClipCamera(CameraTarget, CameraEye + delta);
}
private Vector3 DesiredEye()
{
var (sin, cos) = Trig(Yaw);
return collision.ClipCamera(CameraTarget, ActorRoot + new Vector3(sin * 350, 180, -cos * 350));
}
public static PlayerInput SmokeInput(int step) => new(step < 120, false, false,
step >= 120 && step < 180, step >= 72 && step < 84);
public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded;
public string Report => $"Walk checkpoint: steps={Steps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, grounded={Grounded}, feet={Position}.";
}
+316
View File
@@ -0,0 +1,316 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Provisional geometric reconstruction for the controllable-scene checkpoint.
/// Uses source triangles, including invisible proxies, without claiming the
/// original game's unrecovered collision-mask/state rules or solver tolerances.
/// Positions are the bottom of a vertical capsule in original Y-up world units.
/// </summary>
public sealed class SceneCollision
{
public const float Skin = 0.05f;
public const float MinimumGroundNormal = 0.65f;
private const float Tolerance = 0.005f;
private readonly Triangle[] triangles;
public int TriangleCount => triangles.Length;
private readonly record struct Triangle(Vector3 A, Vector3 B, Vector3 C,
Vector3 Normal, Vector3 Min, Vector3 Max);
private readonly record struct Hit(float Time, Vector3 Normal);
private readonly record struct Pair(Vector3 Capsule, Vector3 Surface)
{
public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface);
}
public SceneCollision(Mesh mesh)
{
if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh));
var result = new List<Triangle>();
// Render visibility is not a proven collision mask. Original null-material
// proxies remain present and block movement in this provisional policy.
for (var i = 0; i < mesh.Indices.Length; i += 3)
{
if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length
|| mesh.Indices[i + 2] >= mesh.Vertices.Length)
throw new ArgumentException("Collision index outside vertex table", nameof(mesh));
var a = mesh.Vertices[mesh.Indices[i]].Position;
var b = mesh.Vertices[mesh.Indices[i + 1]].Position;
var c = mesh.Vertices[mesh.Indices[i + 2]].Position;
if (!Finite(a) || !Finite(b) || !Finite(c)) throw new ArgumentException("Nonfinite collision coordinate", nameof(mesh));
var normal = Vector3.Cross(b - a, c - a);
var normalLengthSquared = normal.LengthSquared();
if (!float.IsFinite(normalLengthSquared)) throw new ArgumentException("Collision triangle exceeds finite arithmetic range", nameof(mesh));
if (normalLengthSquared < 0.000001f) continue;
result.Add(new Triangle(a, b, c, Vector3.Normalize(normal),
Vector3.Min(a, Vector3.Min(b, c)), Vector3.Max(a, Vector3.Max(b, c))));
}
triangles = result.ToArray();
}
/// <summary>Highest walkable surface in the requested vertical interval.</summary>
public float? GroundHeight(Vector3 point, float maxDrop, float maxRise = 0)
{
if (!Finite(point) || !float.IsFinite(maxDrop) || !float.IsFinite(maxRise) || maxDrop < 0 || maxRise < 0)
throw new ArgumentOutOfRangeException(nameof(point));
float? highest = null;
var low = point.Y - maxDrop;
var high = point.Y + maxRise;
foreach (var triangle in triangles)
{
if (MathF.Abs(triangle.Normal.Y) < MinimumGroundNormal || point.X < triangle.Min.X - Tolerance
|| point.X > triangle.Max.X + Tolerance || point.Z < triangle.Min.Z - Tolerance
|| point.Z > triangle.Max.Z + Tolerance || triangle.Min.Y > high || triangle.Max.Y < low) continue;
var t = triangle;
var denominator = (t.B.Z - t.C.Z) * (t.A.X - t.C.X) + (t.C.X - t.B.X) * (t.A.Z - t.C.Z);
if (MathF.Abs(denominator) < 0.000001f) continue;
var u = ((t.B.Z - t.C.Z) * (point.X - t.C.X) + (t.C.X - t.B.X) * (point.Z - t.C.Z)) / denominator;
var v = ((t.C.Z - t.A.Z) * (point.X - t.C.X) + (t.A.X - t.C.X) * (point.Z - t.C.Z)) / denominator;
if (u < -0.00001f || v < -0.00001f || u + v > 1.00001f) continue;
var y = u * t.A.Y + v * t.B.Y + (1 - u - v) * t.C.Y;
if (y < low - Tolerance || y > high + Tolerance || highest.HasValue && y <= highest.Value) continue;
highest = y;
}
return highest;
}
/// <summary>Resolve initial overlaps and sweep/slide a capsule continuously.</summary>
public CollisionMove Move(Vector3 feetPosition, Vector3 displacement, float radius, float height)
{
Validate(feetPosition, displacement, radius, height);
var position = feetPosition;
var grounded = false;
var ceiling = false;
var wall = false;
// Recover gently from a spawn touching/intersecting source triangles. A
// finite iteration bound also handles impossible narrow-gap input safely.
for (var iteration = 0; iteration < 12; iteration++)
{
var bestDepth = Tolerance;
var bestNormal = Vector3.Zero;
CapsuleBounds(position, radius + Skin, height, out var min, out var max);
foreach (var triangle in triangles)
{
if (!Overlaps(min, max, triangle)) continue;
var pair = Closest(position, radius, height, triangle);
var distance = MathF.Sqrt(pair.DistanceSquared);
var depth = radius + Skin - distance;
if (depth <= bestDepth) continue;
bestDepth = depth;
bestNormal = ContactNormal(pair, triangle, position, height, displacement);
}
if (bestNormal == Vector3.Zero) break;
position += bestNormal * bestDepth;
Classify(bestNormal, ref grounded, ref ceiling, ref wall);
}
var remaining = displacement;
for (var iteration = 0; iteration < 8 && remaining.LengthSquared() > 0.00000001f; iteration++)
{
var hit = Sweep(position, remaining, radius, height);
if (!hit.HasValue) { position += remaining; remaining = Vector3.Zero; break; }
position += remaining * Math.Clamp(hit.Value.Time, 0, 1);
Classify(hit.Value.Normal, ref grounded, ref ceiling, ref wall);
remaining *= 1 - Math.Clamp(hit.Value.Time, 0, 1);
var into = Vector3.Dot(remaining, hit.Value.Normal);
if (into < 0) remaining -= hit.Value.Normal * into;
else break;
}
// Contact persistence matters for a stationary character and tangential
// motion. This query does not snap a falling or jumping actor to a floor.
// Grounded describes support at the final position, not a floor crossed
// earlier in this move (for example after walking over a ledge).
grounded = false;
CapsuleBounds(position, radius + Skin + Tolerance, height, out var contactMin, out var contactMax);
foreach (var triangle in triangles)
{
if (!Overlaps(contactMin, contactMax, triangle)) continue;
var pair = Closest(position, radius, height, triangle);
if (pair.DistanceSquared <= (radius + Skin + Tolerance) * (radius + Skin + Tolerance))
Classify(ContactNormal(pair, triangle, position, height, displacement), ref grounded, ref ceiling, ref wall);
}
if (!Finite(position)) throw new InvalidOperationException("Collision produced nonfinite position");
return new CollisionMove(position, grounded, ceiling, wall);
}
/// <summary>Sphere sweep for a follow camera; stops before source geometry.</summary>
public Vector3 ClipCamera(Vector3 target, Vector3 desiredEye, float radius = 8)
{
Validate(target - Vector3.UnitY * radius, desiredEye - target, radius, radius * 2);
var movement = desiredEye - target;
var hit = Sweep(target - Vector3.UnitY * radius, movement, radius, radius * 2);
return hit.HasValue ? target + movement * Math.Clamp(hit.Value.Time, 0, 1) : desiredEye;
}
private Hit? Sweep(Vector3 position, Vector3 movement, float radius, float height)
{
CapsuleBounds(position, radius + Skin, height, out var startMin, out var startMax);
CapsuleBounds(position + movement, radius + Skin, height, out var endMin, out var endMax);
var min = Vector3.Min(startMin, endMin);
var max = Vector3.Max(startMax, endMax);
Hit? closest = null;
foreach (var triangle in triangles)
{
if (!Overlaps(min, max, triangle)) continue;
var limit = closest?.Time ?? 1f;
var time = 0f;
for (var iteration = 0; iteration < 40; iteration++)
{
var current = position + movement * time;
var pair = Closest(current, radius, height, triangle);
var distance = MathF.Sqrt(pair.DistanceSquared);
var normal = ContactNormal(pair, triangle, current, height, movement);
var closing = -Vector3.Dot(movement, normal);
if (distance <= radius + Skin + Tolerance)
{
// A tangent or departing contact must not lock movement.
if (closing > 0.000001f || distance < radius - Tolerance)
closest = new Hit(time, normal);
break;
}
if (closing <= 0.000001f) break;
// The closest-pair plane separates two convex shapes. Advancing
// to where that plane's gap closes is conservative even when the
// closest feature later changes, unlike endpoint-only sampling.
var advance = (distance - radius - Skin) / closing;
if (advance <= 0.0000001f)
{
closest = new Hit(time, normal);
break;
}
time += advance;
if (time > limit || time > 1) break;
if (iteration == 39) closest = new Hit(time, normal);
}
}
return closest;
}
private static Pair Closest(Vector3 feet, float radius, float height, Triangle triangle)
{
var p = feet + Vector3.UnitY * radius;
var q = feet + Vector3.UnitY * (height - radius);
var denominator = Vector3.Dot(triangle.Normal, q - p);
if (MathF.Abs(denominator) > 0.000001f)
{
var time = Vector3.Dot(triangle.Normal, triangle.A - p) / denominator;
if (time is >= 0 and <= 1)
{
var intersection = p + (q - p) * time;
if (Vector3.DistanceSquared(intersection, ClosestPoint(intersection, triangle)) < 0.000001f)
return new Pair(intersection, intersection);
}
}
var best = new Pair(p, ClosestPoint(p, triangle));
var candidate = new Pair(q, ClosestPoint(q, triangle));
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.A, triangle.B);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.B, triangle.C);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.C, triangle.A);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
return best;
}
private static Vector3 ClosestPoint(Vector3 p, Triangle t)
{
var ab = t.B - t.A;
var ac = t.C - t.A;
var ap = p - t.A;
var d1 = Vector3.Dot(ab, ap);
var d2 = Vector3.Dot(ac, ap);
if (d1 <= 0 && d2 <= 0) return t.A;
var bp = p - t.B;
var d3 = Vector3.Dot(ab, bp);
var d4 = Vector3.Dot(ac, bp);
if (d3 >= 0 && d4 <= d3) return t.B;
var vc = d1 * d4 - d3 * d2;
if (vc <= 0 && d1 >= 0 && d3 <= 0) return t.A + ab * (d1 / (d1 - d3));
var cp = p - t.C;
var d5 = Vector3.Dot(ab, cp);
var d6 = Vector3.Dot(ac, cp);
if (d6 >= 0 && d5 <= d6) return t.C;
var vb = d5 * d2 - d1 * d6;
if (vb <= 0 && d2 >= 0 && d6 <= 0) return t.A + ac * (d2 / (d2 - d6));
var va = d3 * d6 - d5 * d4;
if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
return t.B + (t.C - t.B) * ((d4 - d3) / (d4 - d3 + d5 - d6));
// Once the face region is known, project onto its plane directly. A
// barycentric sum of far-apart vertices loses enough precision to give
// an axis-aligned floor a false horizontal normal at original scales.
return p - t.Normal * Vector3.Dot(p - t.A, t.Normal);
}
private static Pair ClosestSegments(Vector3 p, Vector3 q, Vector3 a, Vector3 b)
{
var d1 = q - p;
var d2 = b - a;
var r = p - a;
var aa = Vector3.Dot(d1, d1);
var ee = Vector3.Dot(d2, d2);
var f = Vector3.Dot(d2, r);
float s, t;
if (aa <= 0.00000001f && ee <= 0.00000001f) return new Pair(p, a);
if (aa <= 0.00000001f) { s = 0; t = Math.Clamp(f / ee, 0, 1); }
else
{
var c = Vector3.Dot(d1, r);
if (ee <= 0.00000001f) { t = 0; s = Math.Clamp(-c / aa, 0, 1); }
else
{
var dot = Vector3.Dot(d1, d2);
var denominator = aa * ee - dot * dot;
s = MathF.Abs(denominator) > 0.00000001f ? Math.Clamp((dot * f - c * ee) / denominator, 0, 1) : 0;
t = (dot * s + f) / ee;
if (t < 0) { t = 0; s = Math.Clamp(-c / aa, 0, 1); }
else if (t > 1) { t = 1; s = Math.Clamp((dot - c) / aa, 0, 1); }
}
}
return new Pair(p + d1 * s, a + d2 * t);
}
private static Vector3 ContactNormal(Pair pair, Triangle triangle, Vector3 feet, float height, Vector3 movement)
{
var difference = pair.Capsule - pair.Surface;
if (difference.LengthSquared() > 0.00000001f)
{
var distance = difference.Length();
var planeDistance = Vector3.Dot(pair.Capsule - triangle.A, triangle.Normal);
// A contact indistinguishable from the face plane at our world-unit
// tolerance uses its exact normal. Otherwise tiny closest-edge
// rounding on a coplanar triangle seam can turn a tangent sweep into
// a large sideways/upward correction at high velocity.
if (MathF.Abs(planeDistance) >= distance - Tolerance && MathF.Abs(planeDistance) > Tolerance)
return planeDistance > 0 ? triangle.Normal : -triangle.Normal;
return difference / distance;
}
var side = Vector3.Dot(feet + Vector3.UnitY * (height * 0.5f) - triangle.A, triangle.Normal);
if (MathF.Abs(side) > 0.0001f) return side > 0 ? triangle.Normal : -triangle.Normal;
return Vector3.Dot(movement, triangle.Normal) > 0 ? -triangle.Normal : triangle.Normal;
}
private static void CapsuleBounds(Vector3 feet, float radius, float height, out Vector3 min, out Vector3 max)
{
min = feet - new Vector3(radius, Skin + Tolerance, radius);
max = feet + new Vector3(radius, height + Skin + Tolerance, radius);
}
private static bool Overlaps(Vector3 min, Vector3 max, Triangle t) =>
min.X <= t.Max.X && max.X >= t.Min.X && min.Y <= t.Max.Y && max.Y >= t.Min.Y && min.Z <= t.Max.Z && max.Z >= t.Min.Z;
private static void Classify(Vector3 normal, ref bool ground, ref bool ceiling, ref bool wall)
{
if (normal.Y >= MinimumGroundNormal) ground = true;
else if (normal.Y <= -MinimumGroundNormal) ceiling = true;
else wall = true;
}
private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
private static void Validate(Vector3 position, Vector3 movement, float radius, float height)
{
if (!Finite(position) || !Finite(movement) || !float.IsFinite(radius) || !float.IsFinite(height)
|| radius <= 0 || height < radius * 2)
throw new ArgumentOutOfRangeException(nameof(radius), "Finite capsule coordinates, positive radius and height >= diameter are required");
}
}
public readonly record struct CollisionMove(Vector3 Position, bool Grounded, bool HitCeiling, bool HitWall);