diff --git a/CLAUDE.md b/CLAUDE.md index d27c9a0..21fcaf7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,14 +26,13 @@ existing libs stand ([COMPLIANCE.md](COMPLIANCE.md)). camera out of the state, versioned structs, shared units, snapshot, event ids, move lockstep code out to inklib-net, measure tick step and input delay. -3. libray3: apply COMPLIANCE.md: DetMath for the 13 platform-maths sites +3. libray3: apply COMPLIANCE.md: DetMathF (copy TEMPLATE/src/Tpl.Core/DetMathF.cs) + for the 13 platform-maths sites, touch tolerance, hooks in ray3_hooks.h, (float32 stays), TickSeconds 0.016, 1-tick input delay, world API, snapshot, events, macOS CI, inklib-replay format. -4. Template: a float32 DetMath variant for float32 libs (spec allows it, - template only has double). -5. Template: an example of a lib-owned store (SPEC.md section 6, "Lib-owned +4. Template: an example of a lib-owned store (SPEC.md section 6, "Lib-owned world state") once the Splatoon lib starts. -6. inklib-net and inklib-arena: spec only; start code when two libs comply. -7. Template: implement the host hooks (SPEC.md section 14) and loadout +5. inklib-net and inklib-arena: spec only; start code when two libs comply. +6. Template: implement the host hooks (SPEC.md section 14) and loadout (section 12) as a reference, with snapshot tests. Spec only so far. -8. COMPLIANCE.md: add an sp2 (Splatoon 2) table once its repo can be read. +7. COMPLIANCE.md: add an sp2 (Splatoon 2) table once its repo can be read. diff --git a/COMPLIANCE.md b/COMPLIANCE.md index 4ec2fa4..21be877 100644 --- a/COMPLIANCE.md +++ b/COMPLIANCE.md @@ -34,6 +34,7 @@ C API v7 only. Every ❔ needs a look in the repo. | 6 State hash | 🟡 A hash exists for the lockstep check (what it covers ❔). | Expose it as `fc_state_hash` = FNV-1a 64 over the snapshot bytes. The hash changes, so old lockstep peers do not match new ones (API v8 anyway). | | 6 Event ids | ❔ | `id` (same on resimulation) and `tick` on every event. | | 6 Input quantisation | ✅ The game reads PS1 pad bytes. | Make the stick handling depend only on `round(stick * 127)` (map it onto the pad byte), so inklib-net can send 4 stick bytes. | +| 4 Touch tolerance | unknown | Add `FC_TOUCH_TOLERANCE`; check that `segment` callers slide along touching walls. | | 12 Loadout | 🟡 Weapons per slot exist (15 VS weapons, 3 slots, `rearm`). List/equip shape unknown. | `fc_loadout_list`, `fc_equip`, `fc_equipped` in the weapons module; equipped weapons in the snapshot. | | 14 Host hooks | unknown | Teleport, impulse, hurt (with `invulnerable_ticks`, HURT event), mount/unmount (libfc's pilot/park may map onto it), action enum, aim offset, in `fc_hooks.h`. | | 13 Netcode out of the lib | ❔ The lockstep 1v1 code: inside libfc or in the host? | If it is inside libfc, move it out: it becomes the first piece of inklib-net (lockstep = the zero-rollback case). libfc keeps only snapshot, hash, events and replays. | @@ -79,6 +80,7 @@ Read from OctoAlgo/libray3 at commit `484385e` (2026-10-31). | 6 Event ids | ❌ No events yet. | Add events with `id` and `tick` from the start. | | 6 Input quantisation | ❌ Stick floats are used as given. | Quantise to `round(stick * 127) / 127` in `ray3_char_input`. | | 13 Netcode out of the lib | ✅ None. | None. | +| 4 Touch tolerance | ❌ `ICollisionWorld` says a cast that starts overlapping returns a hit at distance 0, so a PhysX host blocks sliding along touching floors and walls. | Add `RAY3_TOUCH_TOLERANCE` and the section 4 rule to the contract and to its test geometry, with slide tests. | | 12 Loadout | unknown (power-ups exist in the game: copter, big fist, ...). | `ray3_loadout_list` / `ray3_equip` / `ray3_equipped` for the power-ups. | | 14 Host hooks | 🟡 Built for InkArena as C API 21-26: teleport + add impulse (21) and hurt (22) merged; mount (23), HURT event (24), action (25), aim offset (26) pending merge (libray3 #34-#37). | Check the names and return values against section 14 (hurt: 1 / 0 / -1), add `invulnerable_ticks` to the state, HURT = event type 5, action values from the common core, move the hooks into `ray3_hooks.h` + `ray3_get_hooks_api()`, and put their state in the snapshot. | | 7 Camera | ❌ Out of scope in PLAN.md. MEASURE M6 notes that turning is done by the camera's script. | Ship Rayman 3's third-person camera (`THIRD_PERSON`): research, look input, `ray3_char_camera`. This is the largest piece of new work. | diff --git a/SPEC.md b/SPEC.md index 2b9aee3..d706a62 100644 --- a/SPEC.md +++ b/SPEC.md @@ -185,6 +185,22 @@ material bits). The host sets what it knows; zero is plain solid ground. The character never reports itself: the host leaves the character's own body out of every answer. +### Touch tolerance + +PhysX and most engines report a shape that starts touching the probe as a start overlap. Taken +literally ("starts inside = hit at t 0"), a character could never slide along a floor or a wall it +touches. So every lib states a touch tolerance, `

_TOUCH_TOLERANCE` (native length units, in its +header), and the contract for `sweep` and `segment` is: + +- A shape that starts within the tolerance of a surface (just apart, or overlapping by less than the + tolerance) is **touching**, not blocked. +- A touching surface blocks only when the move goes into it: `dot(move, normal) < 0`. Then the hit is + at `t` = 0 with that surface's normal. Moving along it or away from it is free. +- A shape that starts deeper than the tolerance is a real start overlap: hit at `t` = 0. +- Otherwise the first contact along the move is the hit, as usual. + +The template's test collision world follows this rule and tests it (`CollisionTests`). + ## 5. Determinism **Closeness to the original is the top priority of every inklib.** The rules below serve it. @@ -223,8 +239,9 @@ A lib meets this one of two ways. variable or cast it (`(float)`), so no runtime keeps extra precision. RyuJIT computes `float` in single precision; check other runtimes before relying on them. - Only `+ - * /`, comparisons, `Math.Abs/Min/Max/Floor/Ceiling/Round/Truncate/Sign/Clamp` and the - lib's own `DetMath` (template: `DetMath.cs`, double; a float32 lib keeps a float32 `DetMath`, or - computes in double and rounds once to float, which is also deterministic). IEEE 754 makes + lib's own `DetMath` (template: `DetMath.cs` for double and `DetMathF.cs` for float32, same functions, both checked + bit for bit on three platforms; a float32 lib may also compute in double and round once to + float, which is deterministic too). IEEE 754 makes these the same everywhere. `DetMath.Sqrt` is `Math.Sqrt`, which IEEE 754 requires to be correctly rounded. - No `Math.Sin/Cos/Tan/Asin/Acos/Atan/Atan2/Pow/Exp/Log/Cbrt`, no `MathF`: they come from the diff --git a/TEMPLATE/native/include/tpl.h b/TEMPLATE/native/include/tpl.h index bd86d97..3fab271 100644 --- a/TEMPLATE/native/include/tpl.h +++ b/TEMPLATE/native/include/tpl.h @@ -52,6 +52,7 @@ extern "C" { #define TPL_TICK_RATE 60 /* ticks per real second the host calls (pacing) */ #define TPL_TICK_SECONDS 0.016666666666666666 /* game time one tick simulates, exact */ #define TPL_INPUT_DELAY_TICKS 1 /* ticks before the game reads a new pad */ +#define TPL_TOUCH_TOLERANCE 0.5 /* native length units: closer than this counts as touching (SPEC.md section 4) */ #define TPL_SIM_BITS 64 /* the simulation's reals: 32 = float32, 64 = double, 0 = integer/fixed */ enum { diff --git a/TEMPLATE/src/Tpl.Core/Collision.cs b/TEMPLATE/src/Tpl.Core/Collision.cs index ed2d562..8ed326e 100644 --- a/TEMPLATE/src/Tpl.Core/Collision.cs +++ b/TEMPLATE/src/Tpl.Core/Collision.cs @@ -22,6 +22,16 @@ public enum SurfaceFlags : uint CameraPass = 1u << 9, } + ///

Collision rules shared with the host (SPEC.md section 4). + public static class CollisionRules + { + /// + /// Native length units (cm). A shape closer to a surface than this, or overlapping it by less, + /// is touching: it blocks only a move into the surface. Same as TPL_TOUCH_TOLERANCE. + /// + public const double TouchTolerance = 0.5; + } + /// Flags for . Values match TPL_SEGMENT_*. [Flags] public enum SegmentFlags : uint diff --git a/TEMPLATE/src/Tpl.Core/DetMathF.cs b/TEMPLATE/src/Tpl.Core/DetMathF.cs new file mode 100644 index 0000000..d152b9a --- /dev/null +++ b/TEMPLATE/src/Tpl.Core/DetMathF.cs @@ -0,0 +1,81 @@ +using System; + +namespace Tpl +{ + /// + /// for float32 simulations (TPL_SIM_BITS = 32): the same functions, computed + /// in float only, so they give the same bits on every machine. Every intermediate is a float + /// variable; constants are float literals. A float32 lib copies this file and deletes DetMath.cs. + /// Accuracy is about 1 float ulp (1e-7). Our own code (series expansions); no source copied. + /// + public static class DetMathF + { + public const float Pi = 3.14159265f; + public const float HalfPi = 1.57079633f; + public const float TwoPi = 6.28318531f; + + /// IEEE 754 requires float sqrt to be correctly rounded too: same bits everywhere. + public static float Sqrt(float x) => MathF.Sqrt(x); + + /// Sine of an angle in radians. + public static float Sin(float x) + { + float k = MathF.Round(x / TwoPi); + x = x - TwoPi * k; // -pi..pi + if (x > HalfPi) x = Pi - x; // -pi/2..pi/2, same sine + else if (x < -HalfPi) x = -Pi - x; + float x2 = x * x; + // Taylor series to x^13; the next term is below 1e-9 on this range. + float p = 1f / 6227020800f; // 1/13! + p = p * -x2 + 1f / 39916800f; // 1/11! + p = p * -x2 + 1f / 362880f; // 1/9! + p = p * -x2 + 1f / 5040f; // 1/7! + p = p * -x2 + 1f / 120f; // 1/5! + p = p * -x2 + 1f / 6f; // 1/3! + p = p * -x2 + 1f; + float r = x * p; + return r; + } + + /// Cosine of an angle in radians. + public static float Cos(float x) + { + float y = x + HalfPi; + return Sin(y); + } + + /// Arc tangent, -pi/2..pi/2. + public static float Atan(float x) + { + if (float.IsNaN(x)) return x; + bool negative = x < 0; + if (negative) x = -x; + bool inverted = x > 1; + if (inverted) x = 1f / x; + // atan(x) = 2 atan(x / (1 + sqrt(1 + x^2))), twice: x drops below tan(pi/16) = 0.199. + float s = Sqrt(1f + x * x); + x = x / (1f + s); + s = Sqrt(1f + x * x); + x = x / (1f + s); + float x2 = x * x, p = 0f; + for (int k = 13; k >= 1; k -= 2) p = 1f / k - x2 * p; // 1 - x^2/3 + ... to x^12/13 + float r = 4f * x * p; + if (inverted) r = HalfPi - r; + return negative ? -r : r; + } + + /// Angle of the vector (x, y) in radians, -pi..pi, like MathF.Atan2. + public static float Atan2(float y, float x) + { + if (x > 0) return Atan(y / x); + if (x < 0) + { + float a = Atan(y / x); + return y >= 0 ? a + Pi : a - Pi; + } + if (y > 0) return HalfPi; + if (y < 0) return -HalfPi; + return 0f; + } + } +} diff --git a/TEMPLATE/tests/Tpl.Core.Tests/CollisionTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/CollisionTests.cs new file mode 100644 index 0000000..912c8af --- /dev/null +++ b/TEMPLATE/tests/Tpl.Core.Tests/CollisionTests.cs @@ -0,0 +1,69 @@ +using Xunit; + +namespace Tpl.Tests +{ + /// The touch tolerance rule of SPEC.md section 4, on the test world's box sweep. + public class CollisionTests + { + static readonly Vec3 Half = new Vec3(40, 90, 40); + const double Tol = CollisionRules.TouchTolerance; + + // A wall block from x = 400 (the "step" world's 100 cm wall starts there, the 20 cm step before it). + static TestWorld World() => TestWorld.Make("step"); + + [Theory] + [InlineData(0.0)] // exactly on the floor + [InlineData(0.3)] // just above, within the tolerance + [InlineData(-0.3)] // sunk in by less than the tolerance + public void SlidesAlongTheFloorItTouches(double gap) + { + Assert.False(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(150, 0, 0), out _)); + Assert.False(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(0, 10, 0), out _), "moving away is free"); + } + + [Theory] + [InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)] + public void IsBlockedMovingIntoTheFloor(double gap) + { + Assert.True(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(10, -5, 0), out Hit h)); + Assert.Equal(0, h.T); + Assert.Equal(new Vec3(0, 1, 0), h.Normal); + } + + [Theory] + [InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)] + public void SlidesAlongAWallItTouches(double gap) + { + // Standing on the 20 cm step, touching the wall face at x = 400. + var c = new Vec3(400 - 40 - gap, 20 + 90 + 1, 0); + Assert.False(World().SweepBox(c, Half, new Vec3(0, 0, 200), out _)); + Assert.False(World().SweepBox(c, Half, new Vec3(-50, 0, 0), out _), "moving away is free"); + } + + [Theory] + [InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)] + public void IsBlockedMovingIntoTheWall(double gap) + { + var c = new Vec3(400 - 40 - gap, 20 + 90 + 1, 0); + Assert.True(World().SweepBox(c, Half, new Vec3(10, 0, 50), out Hit h)); + Assert.Equal(0, h.T); + Assert.Equal(new Vec3(-1, 0, 0), h.Normal); + } + + [Fact] + public void DeepStartOverlapIsAHit() + { + Assert.True(World().SweepBox(new Vec3(0, 90 - 2 * Tol, 0), Half, new Vec3(10, 0, 0), out Hit h)); + Assert.Equal(0, h.T); + } + + [Fact] + public void ApartHitsAtFirstContact() + { + Assert.True(World().SweepBox(new Vec3(400 - 40 - 100, 20 + 90 + 1, 0), Half, new Vec3(200, 0, 0), out Hit h)); + Assert.Equal(0.5, h.T, 12); + Assert.Equal(new Vec3(-1, 0, 0), h.Normal); + Assert.False(World().SweepBox(new Vec3(400 - 40 - 100, 20 + 90 + 1, 0), Half, new Vec3(50, 0, 0), out _)); + } + } +} diff --git a/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs index 24c6a8c..5bd15d2 100644 --- a/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs +++ b/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs @@ -37,6 +37,34 @@ public void DetMathGoldenBits() const string Golden = "0x40698e7e61f762cf"; + [Theory] + [InlineData(0f)] [InlineData(0.5f)] [InlineData(-1.2f)] [InlineData(3f)] [InlineData(100.25f)] [InlineData(-1000f)] + public void DetMathFIsCloseToMath(float x) + { + double tol = 2e-6 + System.Math.Abs(x) * 4e-8; // float 2*pi is off by ~2e-7, so big angles drift a little + Assert.True(System.Math.Abs(DetMathF.Sin(x) - System.Math.Sin(x)) < tol, "sin"); + Assert.True(System.Math.Abs(DetMathF.Cos(x) - System.Math.Cos(x)) < tol, "cos"); + Assert.True(System.Math.Abs(DetMathF.Atan(x) - System.Math.Atan(x)) < 1e-6, "atan"); + Assert.True(System.Math.Abs(DetMathF.Atan2(x, 0.7f) - System.Math.Atan2(x, 0.7f)) < 1e-6, "atan2"); + Assert.True(System.Math.Abs(DetMathF.Atan2(0.3f, -x) - System.Math.Atan2(0.3f, -x)) < 1e-6, "atan2 left"); + } + + /// Golden bits for the float32 version: must be the same on every machine. + [Fact] + public void DetMathFGoldenBits() + { + float sum = 0; + for (int i = -500; i <= 500; i++) + { + float x = i * 0.0173f; + float term = DetMathF.Sin(x) + DetMathF.Cos(x) * 0.5f + DetMathF.Atan2(x, 1.5f - x) * 0.25f; + sum = sum + term; + } + Assert.Equal(GoldenF, "0x" + System.BitConverter.SingleToInt32Bits(sum).ToString("x8")); + } + + const string GoldenF = "0x434c73eb"; + /// Platform maths and other sources of difference must not appear in Core (outside DetMath.cs). [Fact] public void CoreUsesNoPlatformMaths() @@ -46,7 +74,7 @@ public void CoreUsesNoPlatformMaths() string dir = Path.Combine(Repo.Root(), "src", "Tpl.Core"); foreach (string file in Directory.GetFiles(dir, "*.cs")) { - if (Path.GetFileName(file) == "DetMath.cs") continue; + if (Path.GetFileName(file) == "DetMath.cs" || Path.GetFileName(file) == "DetMathF.cs") continue; string[] lines = File.ReadAllLines(file); for (int i = 0; i < lines.Length; i++) { diff --git a/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs index e13b547..1bf8f2c 100644 --- a/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs +++ b/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs @@ -33,6 +33,7 @@ public void NativeUnitsMatchCore() Assert.Equal(new Tuning().TickSeconds, double.Parse(Macro("TPL_TICK_SECONDS"), CultureInfo.InvariantCulture)); Assert.Equal(new Tuning().InputDelayTicks, int.Parse(Macro("TPL_INPUT_DELAY_TICKS"))); Assert.Equal(Units.SimBits, int.Parse(Macro("TPL_SIM_BITS"))); + Assert.Equal(CollisionRules.TouchTolerance, double.Parse(Macro("TPL_TOUCH_TOLERANCE"), CultureInfo.InvariantCulture)); } [Fact] diff --git a/TEMPLATE/tests/Tpl.Core.Tests/TestWorlds.cs b/TEMPLATE/tests/Tpl.Core.Tests/TestWorlds.cs index 9f67064..49247f5 100644 --- a/TEMPLATE/tests/Tpl.Core.Tests/TestWorlds.cs +++ b/TEMPLATE/tests/Tpl.Core.Tests/TestWorlds.cs @@ -13,6 +13,9 @@ public struct Block { public double MinX, MaxX, MinZ, MaxZ, Top; public SurfaceF readonly Block[] _blocks; public int Queries; + /// The optional sweep callback for a box, with the touch tolerance rule. + public bool SweepBox(Vec3 centre, Vec3 half, Vec3 move, out Hit hit) => TestSweep.Box(_blocks, centre, half, move, out hit); + public TestWorld(params Block[] blocks) { _blocks = blocks; } public static TestWorld Make(string name) @@ -77,6 +80,78 @@ public bool Overlap(in Shape shape, out Hit hit) } } + /// + /// Box sweep for the test world (the optional sweep callback), with the touch tolerance of + /// SPEC.md section 4: a box touching a surface slides along it and is blocked only moving into it. + /// + static class TestSweep + { + const double Far = 1e9; + + /// Axis-aligned box (centre, half extents) moved by . First blocking hit, or false. + public static bool Box(TestWorld.Block[] blocks, Vec3 centre, Vec3 half, Vec3 move, out Hit hit) + { + hit = default; + bool any = false; + double best = double.MaxValue; + // The floor is a huge box below y = 0; each block is solid from y = 0 to its top. + if (One(new Vec3(-Far, -Far, -Far), new Vec3(Far, 0, Far), centre, half, move, out Hit h) && h.T < best) { best = h.T; hit = h; any = true; } + foreach (TestWorld.Block b in blocks) + if (One(new Vec3(b.MinX, 0, b.MinZ), new Vec3(b.MaxX, b.Top, b.MaxZ), centre, half, move, out h) && h.T < best) + { best = h.T; h.Surface = b.Surface; hit = h; any = true; } + return any; + } + + static double Get(Vec3 v, int i) => i == 0 ? v.X : i == 1 ? v.Y : v.Z; + + static Vec3 Axis(int i, double sign) => new Vec3(i == 0 ? sign : 0, i == 1 ? sign : 0, i == 2 ? sign : 0); + + static bool One(Vec3 lo, Vec3 hi, Vec3 c, Vec3 h, Vec3 m, out Hit hit) + { + hit = default; + double tol = CollisionRules.TouchTolerance; + // Separation on each of the six faces of the box grown by the half extents; the largest is how far apart. + double sep = double.MinValue; + Vec3 normal = Vec3.Zero; + for (int i = 0; i < 3; i++) + { + double below = (Get(lo, i) - Get(h, i)) - Get(c, i); // > 0: c is outside on the low side + double above = Get(c, i) - (Get(hi, i) + Get(h, i)); // > 0: c is outside on the high side + if (below > sep) { sep = below; normal = Axis(i, -1); } + if (above > sep) { sep = above; normal = Axis(i, 1); } + } + double into = m.X * normal.X + m.Y * normal.Y + m.Z * normal.Z; + if (sep < -tol) { hit = new Hit { Point = c, Normal = normal, T = 0 }; return true; } // really inside + if (sep <= tol) // touching + { + if (into >= 0) return false; + hit = new Hit { Point = c, Normal = normal, T = 0 }; + return true; + } + // Apart: slab test on the grown box. + double enter = 0, exit = 1; + Vec3 n = Vec3.Zero; + for (int i = 0; i < 3; i++) + { + double ci = Get(c, i), mi = Get(m, i), l = Get(lo, i) - Get(h, i), u = Get(hi, i) + Get(h, i); + if (mi == 0) + { + if (ci <= l || ci >= u) return false; + continue; + } + double t0 = (l - ci) / mi, t1 = (u - ci) / mi; + double sign = -1; + if (t0 > t1) { double t = t0; t0 = t1; t1 = t; sign = 1; } + if (t0 > enter) { enter = t0; n = Axis(i, sign); } + if (t1 < exit) exit = t1; + if (enter > exit) return false; + } + if (n.Equals(Vec3.Zero)) return false; + hit = new Hit { Point = c + m * enter, Normal = n, T = enter }; + return true; + } + } + /// The same world for a host that speaks shared units (m, Z up): converts and forwards. sealed class SharedHost : ICollisionWorld {