diff --git a/.github/workflows/template.yml b/.github/workflows/template.yml
new file mode 100644
index 0000000..110c2f4
--- /dev/null
+++ b/.github/workflows/template.yml
@@ -0,0 +1,70 @@
+# Builds and tests TEMPLATE/ in this repo. TEMPLATE/.github/workflows/ci.yml is the same set of
+# jobs for a lib made from the template; keep the two in step.
+name: Template
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+defaults:
+ run:
+ working-directory: TEMPLATE
+ shell: bash
+
+jobs:
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - run: dotnet build --configuration Release
+ - run: dotnet test --configuration Release --no-build
+
+ native:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: ubuntu-latest, rid: linux-x64 }
+ - { os: windows-latest, rid: win-x64 }
+ - { os: macos-latest, rid: osx-arm64 }
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - if: runner.os == 'Linux'
+ run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev
+ - run: native/build_and_test.sh ${{ matrix.rid }}
+
+ checks:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: tools/check-no-game-data.sh
+ - run: unity/pack.sh
+
+ # A lib made from the template must build and pass too.
+ copy-and-rename:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev
+ - run: |
+ cp -r . "$RUNNER_TEMP/inklib-demo"
+ cd "$RUNNER_TEMP/inklib-demo"
+ ./rename.sh demo Demo
+ if grep -rIl -e tpl -e TPL -e Tpl . --exclude=rename.sh; then echo "template names left after rename"; exit 1; fi
+ dotnet test
+ native/build_and_test.sh linux-x64
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..30d8c4f
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,36 @@
+# CLAUDE.md
+
+Rules for anyone (human or AI) working in this repo.
+
+## What this is
+
+The inklib standard ([SPEC.md](SPEC.md)), the copyable template
+([TEMPLATE/](TEMPLATE/), its own rules in TEMPLATE/CLAUDE.md) and where the
+existing libs stand ([COMPLIANCE.md](COMPLIANCE.md)).
+
+## Rules
+
+- Closeness to the original game is the top priority of every inklib.
+- Keep SPEC.md, the template and COMPLIANCE.md in step: a rule in the spec
+ gets template code and a test, and a row per lib in COMPLIANCE.md.
+- The template must build and pass CI (`.github/workflows/template.yml`,
+ including copy-and-rename). Recording replays again changes their hash;
+ update `TEMPLATE/native/tests/test_tpl.c` too.
+- No game data, no copied code, no licence chosen (TODO for octo).
+- Small PRs. Push after every finished step. Keep "Next" below current.
+
+## Next
+
+1. Licence: octo decides (README, TEMPLATE/LICENSE, unity/package.json).
+2. libfc: apply COMPLIANCE.md (API v8): optional parts into modules,
+ 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
+ (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
+ world state") once the Splatoon lib starts.
+6. inklib-net and inklib-arena: spec only; start code when two libs comply.
diff --git a/COMPLIANCE.md b/COMPLIANCE.md
new file mode 100644
index 0000000..4bb3e58
--- /dev/null
+++ b/COMPLIANCE.md
@@ -0,0 +1,92 @@
+# Compliance
+
+Where each existing lib stands against [SPEC.md](SPEC.md) version 1, and what has to change before
+it is published under its inklib name. Written 2026-10-31; rollback rows (sections 5, 6, 13) added
+the same day.
+
+Legend: ✅ matches, 🟡 partly, ❌ missing or different, ❔ not known.
+
+## inklib-fc (today libfc, Future Cop: L.A.P.D., X1-Alpha mech)
+
+The repo is on a private server and could not be read. This table comes from the description of
+C API v7 only. Every ❔ needs a look in the repo.
+
+| Spec | libfc v7 today | Change before publish |
+|---|---|---|
+| 1 Naming | Repo `libfc`, prefix `fc_`. Character functions use `mech`. | Rename the repo to `inklib-fc`. Add the standard `fc_char_*` names; `fc_mech_*` may stay as aliases. |
+| 2 Version, last error | ✅ `fc_api_version`, `fc_last_error(buf, size)`. | Check that it returns the full length and accepts `buf = NULL`. |
+| 2 Units query | ❌ | Add `fc_units()` and the `FC_NATIVE_*` macros. |
+| 2 Create / destroy | 🟡 `fc_world_create(data_path, level, const fc_collision*)`. | Take `const fc_world_config*` (`size`, `units`, `data_path`, then `level` as a lib field). |
+| 2 Add / remove | 🟡 `fc_mech_add(world, config)` with x, y, z, yaw, hover, team, health, max_health, no_camera. Remove ❔. | `fc_char_config`: `size`, `flags` (`NO_CAMERA`), `position`, `yaw`, `variant`, then `hover` as a lib field. Team and health move to the `damage` module. Add `fc_char_remove` if it is missing. |
+| 2 Input | 🟡 `fc_mech_input(world, mech, pad, analog, stick_x, stick_y)`. | `fc_input` struct: `size`, `buttons` (PS1 pad bits), `move_x/y`, `look_x/y` as -1..1; lib quantises to PS1 pad bytes. `analog` becomes a lib field. |
+| 2 Tick | ✅ `fc_world_tick(world, ticks)`, 30 Hz. | None. |
+| 2 State | 🟡 `fc_mech_state`: position, velocity, state, anim, health, plus the camera. | `fc_state`: `size`, `state`, `anim`, `grounded`, `tick`, `position`, `velocity`, `yaw`, `ground_surface`. Health moves to `damage`; camera moves to `fc_char_camera`. |
+| 2 Events | ✅ `fc_events(world, out, max)` + `fc_events_dropped`. | Check the event struct (`id`, `tick`, `type`, `char_id`, `a`, `b`, `position`) and renumber: standard types 1..4, libfc's own from 256. |
+| 2 Function table | 🟡 `fc_api` exists. | Start it with `size`, `api_version`, `prefix`, then the standard order. Module functions leave the core table (see 12). |
+| 2 ABI | ❔ | Check: fixed-size ints only, `size` first in every versioned struct, no callbacks except collision. Reals become `double` (exact for 16.16). This is API v8, a breaking change. |
+| 3 Units | 🟡 Native PS1 integers, y up, angles 0..4095, 16.16. Not declared as macros; no shared mode. | Declare them (`FC_NATIVE_RADIANS_PER_UNIT` = 2π / 4096; metres per unit: a MEASURE item; up sign and handedness: check, PS1 games are often y-down). Add `FC_UNITS_SHARED` through a small conversion layer; the simulation keeps its integers and rounds host answers back. |
+| 4 Collision | 🟡 `ground(x,y,z -> height + normal)`, `segment(a, b -> hit + normal, skip floors)`, `overlap_actor(box)`. | Same three, standard signatures: `ground(from, max_drop, hit)`, `segment(a, b, flags, hit)`, `overlap(shape, hit)` (box shape; `hit.actor` names the actor). Add `size`, `user`, and surface flags (game materials in bits 16..31). |
+| 5 Determinism | ✅ Fixed 30 Hz tick, game-integer maths (by design). Wall clock and random sources ❔. | Check for `DateTime`, `Random`, threads. Reimplement the game RNG if the mech uses one. |
+| 5 Tick step, input delay | ❔ 30 Hz is known; the real step per tick and the pad delay are not recorded here. | Measure both in the game; add `FC_TICK_SECONDS`, `FC_INPUT_DELAY_TICKS` (delay on by default), `FC_SIM_BITS` = 0 (integer). |
+| 5 Same bits on every machine | ✅ Integer PS1 maths (16.16, 4096-step angles), already proven by lockstep online 1v1 with a hash check. | Check that no float or platform maths feeds the simulation (floats only in outputs such as the camera rows or the HUD). Add the scan test and run `dotnet test` on macOS arm64 in CI. |
+| 5 Replay format | 🟡 libfc has replays (format ❔). | Convert to `inklib-replay 1` with a `hash:` line per file; the C test repeats one hash. |
+| 6 Snapshot (`fc_state_size`, `fc_save_state`, `fc_load_state`) | ❔ Probably missing: lockstep never rolls back, so it does not need one. | Add them: every mech, its camera, timers, the game RNG, the tick and id counters, in the fixed little-endian layout with magic, format and tuning hash. Add the save/step/load/step test. With the arena modules, their state (health, shots, targets) goes into their own module snapshot. |
+| 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. |
+| 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. |
+| 7 Camera | 🟡 The game's chase camera is in the state: position, pitch/yaw/roll, rotation rows. | `fc_char_camera`: `style` (`CHASE` / `TOP_DOWN`), `position`, `target`, `up`, `fov_y`. Pitch/yaw/roll and rows may stay as fields after the standard ones. Look input through `look_x/y`. |
+| 8 Provenance | ❔ | `[Verified]` / `[Unverified]` on every tuning number, the tests, MEASURE.md. |
+| 9 Data rules | 🟡 Mesh, atlas and HUD art come from `data_path` (the user's disc). | Check the repo history for game files and copied decomp code; add the CI data check. |
+| 10 Packaging | ❔ | NativeAOT win-x64, linux-x64, osx-arm64; Unity UPM package; C example host; CI on Linux and Windows. |
+| 11 Docs | ❔ | CLAUDE.md, Docs/PLAN, RESEARCH, MEASURE, REPLAY. |
+| 12 Optional modules | ❌ In the core API since v5: mesh/look/atlas, lights, pilot/park, damage, targets, weapons/rearm, shots in flight, HUD as data. | Move each into its own header and table: `fc_look.h` (mesh, look, atlas, lights), and the arena set `fc_damage.h`, `fc_targets.h`, `fc_weapons.h`, `fc_shots.h`, `fc_hud.h`, `fc_vehicle.h`. The core must work with none of them used. These shapes seed the inklib-arena add-on. |
+| Licence | ❔ | TODO (octo). |
+
+**Biggest gaps for libfc:** the optional parts live in the core API; no shared-unit mode; camera is
+inside the state; create/add/input take loose arguments instead of versioned structs; snapshots
+(save/load) for rollback; the online code may have to move out to inklib-net. Together these are one
+breaking release (API v8). Cross-machine determinism is already there, thanks to the integer maths.
+
+## inklib-ray3 (today libray3, Rayman 3: Hoodlum Havoc, PC)
+
+Read from OctoAlgo/libray3 at commit `484385e` (2026-10-31).
+
+| Spec | libray3 today | Change before publish |
+|---|---|---|
+| 1 Naming | Repo `libray3`, prefix `ray3_` ✅, `libray3.dll` ✅, header `native/include/ray3.h` ✅. C# `LibRay3.*`. | Rename the repo to `inklib-ray3`. C# names `Ray3.Core` etc. (optional). |
+| 2 Version, last error | ❌ Neither. `ray3_create` returns NULL without a reason. | Add `ray3_api_version`, `ray3_last_error`. |
+| 2 Units query | ❌ | Add `ray3_units()` and the `RAY3_NATIVE_*` macros (all 1.0, Z up). |
+| 2 Create / destroy | 🟡 `ray3_create(world, config, feet, yaw)` makes one controller. | Split into `ray3_world_create(config, collision)` and `ray3_char_add`. The tuning (`ray3_config`) becomes a lib field in `ray3_char_config` (pointer, NULL = defaults); `ray3_default_config` stays as a lib extra. |
+| 2 Add / remove | ❌ One character per create. | `ray3_char_add`, `ray3_char_remove`; several characters per world. |
+| 2 Input | 🟡 `ray3_set_input`: world-space stick, `jump` and `target` as int32. | `ray3_input`: `size`, `buttons` (`JUMP`, `TARGET`), `move_x/y`, `look_x/y` as the player holds them. Camera-relative movement comes with the camera. |
+| 2 Tick | 🟡 `ray3_step(c)` = one tick. | `ray3_world_tick(world, n)`. |
+| 2 State | 🟡 `ray3_get_state`: floats, no `size`, no `anim`. | `ray3_state` per spec: doubles, `size`, `anim` (-1 until animations are known), `ground_surface` ✅, `tick` ✅. |
+| 2 Events | ❌ | Add the buffer: `STATE`, `LAND`, `LEAVE_GROUND` at least; `SOUND` when sound ids are known. |
+| 2 Function table | ❌ | Add `ray3_api` + `ray3_get_api`. |
+| 2 ABI | 🟡 Plain C, fixed-size ints, booleans as int32 ✅. No `size` fields; floats. | `size` first in every versioned struct; reals as double. |
+| 3 Units | ✅ Metres, seconds, radians, Z up, right-handed: native already equals shared. | Declare it in the header; accept both `units` values (no conversion needed). |
+| 4 Collision | 🟡 `raycast`, `sphere_cast`, `capsule_cast` (origin + unit direction + max distance). | Required `ground`, `segment`, `overlap` (host provides; ray3 may build its ray on `segment`), plus optional `sweep` (sphere/capsule), which ray3 needs and says so in its header. |
+| 4 Surface flags | ❌ Game bit positions in bits 0..15 (slide = 0, trampoline = 1, ledge = 2, ...). | Standard bits 0..15 (`SLIDE`, `BOUNCE`, `LEDGE`, `HANG`, `CLIMB`, `HURT`, `DEATH`, `WATER`, `NO_COLLISION`); the game's own bits move to 16..31 (wall, fall trigger, electric, ...). |
+| 5 Determinism | ✅ Fixed 60 Hz (`Tuning.TickRate`), no clock, no random, no threads (CLAUDE.md rule 2). | None. |
+| 5 Tick step | 🟡 Measured in the real PC game: 16 ms of game time per frame at 60 Hz (the game runs at 96 % of real time; its dt is clamped and averaged). | Add `Tuning.TickSeconds` = 0.016 (VERIFIED, with the recording as source) and `RAY3_TICK_SECONDS`; every per-second number uses it instead of 1 / 60. |
+| 5 Input delay | 🟡 Measured: the game reads the pad 1 frame late. | Reproduce it by default (`RAY3_INPUT_DELAY_TICKS` = 1, delayed inputs in the snapshot); `RAY3_CHAR_NO_INPUT_DELAY` turns it off. |
+| 5 Same bits on every machine | ❌ The simulation is float32, which matches the game (keep it: `RAY3_SIM_BITS` = 32). But at `79f17a3` it calls platform maths at 13 sites: 4 Sin/Cos (`RaymanController.cs:66`, `:75`, `RaymanCamera.cs:177`), 6 `MathF.Atan2` (`RaymanController.cs:395`, `:441`, `RaymanController.V2.cs:93`, `:132`, `:232`, `:249`), 3 `MathF.Pow` (`RaymanController.cs:540`, `:543`, `RaymanCamera.cs:188`). `MathF.Sqrt` (`Vec3.cs:31`) is fine: IEEE rounds it correctly. CI tests Linux and Windows x64 only. | Replace the 10 Sin/Cos/Atan2 calls with a float32 `DetMath` (or the template's double one, rounded once to float). The Pow calls are per-frame blends with exponent `dt * 60`; at the fixed 16 ms step that exponent is a constant (0.96), so compute it once per world with `DetMath` (exp/log series) or keep it as a tuning number. Keep every float intermediate in a float variable. Add the scan test, `hash:` lines, and `dotnet test` on macOS arm64. |
+| 5 Replay format | 🟡 `libray3-replay 1`, columns `ticks move_x move_y jump target x y z state`, 6 replays. | Convert to `inklib-replay 1` (`lib: ray3 1`, buttons column, look columns, `|`, yaw, `start` with yaw, `hash:`). Mechanical; the runner keeps `origin`, `tolerance`, `tuning`. |
+| 6 Snapshot and hash | ❌ None. The controller keeps private state (`_jumpWasHeld`, `_targetWasHeld`, `_lockedYaw`, `_regrabTimer`, `_jumpTick`, `_offGround`, `_offGroundTime`, `_coyote`, `_airTime`, `_hangPos`, `_climbTopPos`) next to the public state. | Add `ray3_state_size/save_state/load_state/state_hash`. Every one of those fields, the public state, the input and (later) the camera goes into the snapshot. Add the save/step/load/step test. |
+| 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. |
+| 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. |
+| 8 Provenance | ✅ `[Verified]` / `[Unverified]` on every tuning field, `ProvenanceTests`, header comments checked by `HeaderTests`. | Add the "every UNVERIFIED field is in MEASURE.md" test. Today `CoyoteGroundGravity` and `LedgeGrabAllSides` are not named as `Tuning.X` there. |
+| 9 Data rules | ✅ No game files, no copied code (CLAUDE.md rules 3-4), `.gitignore` backstop. | Add the CI data check. |
+| 10 Packaging | 🟡 NativeAOT linux-x64 and win-x64 ✅, `.def` ✅, CI on Linux and Windows ✅. No macOS ("No macOS" in CLAUDE.md), no Unity package, C test only. | Add osx-arm64, the UPM package (`unity/`), `native/example/host.c`, release artifacts. |
+| 11 Docs | ✅ CLAUDE.md, Docs/PLAN, RESEARCH, MEASURE, REPLAY. | Point CLAUDE.md at the standard. |
+| 12 Optional modules | ✅ None in the core. | None. |
+| Licence | MIT LICENSE in the repo. | Octo to confirm (the standard leaves it TODO). |
+
+**Biggest gaps for libray3:** 13 platform-maths calls mean replays can differ between machines, so it
+cannot do rollback until they go through `DetMath` (float32 stays); no snapshot or hash;
+the camera does not exist yet; the API is one controller instead of a world with characters; no
+version, last error, events or function table; surface bits use the game's positions instead of the
+standard ones.
diff --git a/README.md b/README.md
index 95e7040..eb1548f 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,24 @@
# inklib
-A standard and a template for small libraries that move one character from a game exactly like the original, for any engine.
+A standard and a template for small libraries that move one character from a
+game exactly like the original, for any engine. Each lib reads the player's
+own game data and reverse-engineered rules. [libsm64](https://github.com/libsm64/libsm64)
+is the model.
+
+- [SPEC.md](SPEC.md): the standard. Naming, C API shape, units, collision,
+ determinism (same bits on every machine) and replays, rollback support
+ (snapshots, state hash, event ids), camera, provenance, data rules,
+ packaging, optional modules, and the planned inklib-net add-on.
+- [TEMPLATE/](TEMPLATE/): copy this to start a new lib (`rename.sh`). It
+ builds and its tests pass in CI.
+- [COMPLIANCE.md](COMPLIANCE.md): where the existing libs stand.
+
+There is no inklib runtime package. Users copy the template; nothing
+depends on this repo at run time.
+
+Libs: inklib-fc (Future Cop: L.A.P.D., today libfc), inklib-ray3
+(Rayman 3, today libray3). Planned: a first-person Project Zero lib.
+
+This repo contains no game data and no code from any game.
+
+Licence: TODO (octo).
diff --git a/SPEC.md b/SPEC.md
new file mode 100644
index 0000000..9812c74
--- /dev/null
+++ b/SPEC.md
@@ -0,0 +1,452 @@
+# The inklib standard
+
+Version 1 (draft). Status: written 2026-10-31, not yet adopted by any lib.
+
+An inklib is a small library that moves ONE character from ONE game exactly like the original.
+The rules come from reverse engineering. Data comes from the player's own disc. Any engine can host it.
+[libsm64](https://github.com/libsm64/libsm64) is the model.
+
+Each inklib is useful on its own. A host can drop in one lib and get the character, its controls and
+its camera. Nothing here assumes that several libs meet in one game. That is the later "inklib-arena"
+add-on (section 12). It must not leak into the core.
+Online play is the optional "inklib-net" add-on (section 13); every lib is ready for it (section 6).
+
+Users never depend on an inklib runtime package. There is no shared `inklib.dll` and no shared header.
+A new lib copies [TEMPLATE/](TEMPLATE/) and renames it. Everything shared is a convention written here.
+
+The words MUST, MUST NOT and MAY mean what they say. `
` is the lib's C prefix (`fc`, `ray3`, `tpl`).
+`
` is the same in capitals.
+
+## 1. Naming
+
+- Repo: `inklib-`, lower case, short. Examples: `inklib-fc`, `inklib-ray3`, `inklib-pz`.
+- C prefix: `
_` on every function and type, `
_` on every macro and enum value. The prefix is
+ short and fixed for the life of the lib.
+- Shared library file: `lib
.dll` / `lib
.so` / `lib
.dylib`. Header: `native/include/
.h`.
+- C# namespace and project names: `.Core`, `.Native`, `.Core.Tests`
+ (for example `Ray3.Core`).
+- Character functions use the noun `char` (`
_char_add`). A lib MAY add aliases with the game's own
+ word (`fc_mech_add`), but the standard names MUST exist and MUST be the ones in the function table.
+
+## 2. The C API
+
+The core API is the list below. A lib MUST export all of it, with these names, argument orders and
+return rules. [TEMPLATE/native/include/tpl.h](TEMPLATE/native/include/tpl.h) is the reference header;
+it documents every field.
+
+| Function | What it does |
+|---|---|
+| `int32_t
_api_version(void)` | Returns `
_API_VERSION` of the built lib. |
+| `int32_t
_last_error(char *buf, int32_t size)` | Copies the last error of this thread as UTF-8 with a NUL, cut to `size`. Returns the full length without the NUL, 0 if there is none. `buf` MAY be NULL to ask for the length. |
+| `int32_t
_units(
_units_info *out)` | Says the native units and axes (section 3). |
+| `
_world *
_world_create(const
_world_config *config, const
_collision *collision)` | Makes a world. NULL on error. |
+| `void
_world_destroy(
_world *world)` | Frees it. NULL is fine. |
+| `int32_t
_char_add(
_world *world, const
_char_config *config)` | Adds the character. Returns its id (1 or more), 0 on error. |
+| `int32_t
_char_remove(
_world *world, int32_t id)` | Removes it. Its id is never reused in this world. |
+| `int32_t
_char_input(
_world *world, int32_t id, const
_input *input)` | Sets the pad for the next ticks. Input stays until the next call. |
+| `int32_t
_camera *out)` | The game's own camera (section 7). |
+| `int32_t
_events(
_world *world,
_event *out, int32_t max)` | Moves up to `max` events out of the buffer, oldest first. Returns how many. |
+| `int64_t
_events_dropped(const
_world *world)` | Events lost because the buffer was full, since create. |
+| `int32_t
_state_size(const
_world *world)` | Bytes a snapshot of the world needs now (section 6). |
+| `int32_t
_save_state(const
_world *world, void *buf, int32_t size)` | Writes a complete snapshot. Returns the bytes written, 0 if `size` is too small. |
+| `int32_t
_load_state(
_world *world, const void *buf, int32_t size)` | Puts the world back to a snapshot. On error the world is unchanged. |
+| `uint64_t
_state_hash(const
_world *world)` | 64-bit hash of the snapshot, for desync checks. 0 only on error. |
+| `const
_api *
_get_api(void)` | The function table. Never NULL. |
+
+Return rule: functions that return `int32_t` return 1 (or an id) on success and 0 on error, and set the
+last error. A bad pointer or unknown id is an error, never a crash. `
_events` returns 0 when the
+buffer is empty; that is not an error.
+
+### Structs
+
+- `
_world_config`: `size`, `units` (`
_UNITS_NATIVE` or `
_UNITS_SHARED`), `data_path`
+ (UTF-8 path to the user's own game data, MAY be NULL if the lib needs none). Libs add their own
+ fields at the end (for example `level`).
+- `
_char_config`: `size`, `flags` (`
_CHAR_NO_CAMERA` = 1 skips the camera), `position`, `yaw`,
+ `variant` (lib-defined: skin, suit, character in a cast; 0 = default).
+- `
_input`: `size`, `buttons` (bitmask, bits defined by the lib as the game's pad), `move_x`,
+ `move_y`, `look_x`, `look_y` (floats -1..1, raw sticks as the player holds them, +y = up/forward).
+ The lib turns these into movement the way the game does: camera-relative, tank controls,
+ whatever the original did. The lib quantises sticks the way the game's pad driver does.
+ A game without analog sticks ignores them.
+- `
_event`: `id`, `tick`, `type`, `char_id`, `a`, `b`, `position`. `id` and `tick` are for
+ rollback hosts (section 6). Types 1..255 are standard:
+ `STATE` (a = old, b = new), `LAND`, `LEAVE_GROUND`, `SOUND` (a = the game's sound id; the host
+ plays it). Types 256 and up are the lib's own.
+- `
_units_info`, `
_camera`, `
_hit`, `
_shape`, `
_collision`: sections 3, 4 and 7.
+- `
_api`: `size`, `api_version`, `prefix` (string, for example `"fc"`), then one pointer per
+ function above in table order, `get_api` excluded. A lib MAY append its own functions after the
+ standard ones. Because every lib's table starts the same way, a host can load any inklib with
+ `dlopen` + `dlsym("
_get_api")` and drive it through one struct of its own.
+
+### ABI rules
+
+- Plain C99 structs. Fixed-size ints only (`int32_t`, `uint32_t`, `int64_t`). Reals are `double`,
+ except the stick floats in `
_input`. No `bool`, no `enum` types in structs (enum values are
+ macros or anonymous enums, fields are `int32_t`), no `long`, no `size_t`.
+- `cdecl`, `extern "C"`. No C++ in the header. No variadic functions.
+- Versioned structs: every struct the host passes in or gets back, except the small fixed ones
+ (`
_vec3`, `
_hit`, `
_shape`, `
_event`), starts with `uint32_t size`. The host sets it to
+ `sizeof` from the header it compiled with. The lib reads only `min(size, its own size)` bytes and
+ treats missing fields as zero. It writes only `min(size, its own size)` bytes back. A size smaller
+ than the first version of the struct is an error. New fields go at the end, and zero MUST mean
+ "old behaviour".
+- The small fixed structs only change with a new `
_API_VERSION`.
+- `
_API_VERSION` goes up by one on every change a host could notice. Old fields are never moved.
+- No callbacks into the host except the collision callbacks. Events are polled. Logging goes to
+ `
_last_error`, never to stdout.
+- No global state that two worlds could share. One world is used from one thread at a time.
+ Different worlds MAY run on different threads.
+- Strings in are UTF-8 and only read during the call. Pointers in structs (`data_path`) are only read
+ during the call that receives them. `collision->user` stays valid until `
_world_destroy`.
+
+## 3. Units and axes
+
+Each lib has native units: the game's own. libfc keeps PS1 integers, 16.16 fixed point and angles
+0..4095. libray3's native units are already metres.
+
+**The header MUST say them** as macros, and `
_units` returns the same at run time:
+
+```c
+#define TPL_NATIVE_METRES_PER_UNIT 0.01 /* one native length unit in metres */
+#define TPL_NATIVE_RADIANS_PER_UNIT 1.0 /* one native angle unit in radians */
+#define TPL_NATIVE_UP_AXIS 1 /* 0 = X, 1 = Y, 2 = Z */
+#define TPL_NATIVE_UP_SIGN 1 /* +1 or -1 */
+#define TPL_NATIVE_HANDEDNESS 1 /* +1 right-handed, -1 left-handed */
+#define TPL_NATIVE_VELOCITY_PER_TICK 1 /* 1: native velocity is units per tick, 0: per second */
+#define TPL_TICK_RATE 60 /* ticks per second */
+```
+
+**The shared convention** is metres, seconds, radians, Z up, right-handed, yaw 0 = +X, positive yaw
+turns from +X towards +Y. Velocity is metres per second.
+
+A host picks one with `
_world_config.units`. Every position, direction, velocity and angle that
+crosses the API (state, camera, events, and the collision callbacks) is then in that convention.
+Field of view is always radians (section 7). Sticks are always -1..1.
+
+- `
_UNITS_NATIVE` = 0: the game's numbers, unchanged. libfc returns 16.16 values as exact doubles.
+ This is what replays compare against when they are game logs.
+- `
_UNITS_SHARED` = 1: converted at the boundary by a small layer (`Units.cs` in the template).
+
+The simulation inside MUST run in native units, so the game-exact rules never see a converted
+number. The conversion layer converts host answers back to native units before the simulation uses
+them; it rounds the way the game would (to the nearest native integer for integer games).
+
+## 4. Collision
+
+The lib never sees meshes. The host answers queries through callbacks in `
_collision`:
+`size`, `user`, then the pointers. All coordinates are in the world's unit convention.
+Every callback returns 1 and fills `*out` on a hit, else 0.
+
+Required: every host MUST provide these three, so a host written for one inklib has what any other
+needs at minimum.
+
+| Callback | Question |
+|---|---|
+| `ground(user, from, max_drop, out)` | First walkable ground straight down (along -up) from `from`, within `max_drop`. `out->point` is on the ground. |
+| `segment(user, a, b, flags, out)` | First hit on the line from `a` to `b`. `flags`: `SEGMENT_SKIP_FLOORS` ignores surfaces facing up; `SEGMENT_CAMERA` ignores `CAMERA_PASS` surfaces. |
+| `overlap(user, shape, out)` | Does this shape (sphere, capsule or axis-aligned box) touch solid geometry? `out` is one of the touches; its normal points out of the geometry. |
+
+Optional: NULL unless the lib needs it. A lib uses only what its game really asked. If it needs an
+optional callback, its header says so at the top and `
_world_create` fails with a clear error when
+it is NULL.
+
+| Callback | Question |
+|---|---|
+| `sweep(user, shape, move, out)` | First hit while moving `shape` by `move`. Needed by libs whose game sweeps its body (libray3). |
+
+A lib MAY append its own callbacks after `sweep`. It MUST document each one and MUST NOT require one
+that the game did not really need.
+
+`
_hit` is `point`, `normal` (unit, pointing back at the query), `t` (0..1, how far along the query),
+`surface` (flags), `actor` (host id of what was hit, 0 for level geometry).
+
+Surface flags: bits 0..15 mean the same in every lib. Bits 16..31 are the lib's own (its game's
+material bits). The host sets what it knows; zero is plain solid ground.
+
+| Bit | Name | Meaning |
+|---|---|---|
+| 0 | `NO_COLLISION` | Ignore it for movement. |
+| 1 | `WATER` | Water surface or volume. |
+| 2 | `HURT` | Hurts on touch. |
+| 3 | `DEATH` | Kills or resets on touch (pits, lava). |
+| 4 | `SLIDE` | Slippery or a slide. |
+| 5 | `LEDGE` | Edge that can be grabbed. |
+| 6 | `CLIMB` | Wall that can be climbed. |
+| 7 | `HANG` | Ceiling that can be hung from. |
+| 8 | `BOUNCE` | Trampoline or bumper. |
+| 9 | `CAMERA_PASS` | The camera passes through it. |
+| 10..15 | reserved | Zero. |
+
+The character never reports itself: the host leaves the character's own body out of every answer.
+
+## 5. Determinism
+
+**Closeness to the original is the top priority of every inklib.** The rules below serve it.
+
+- Each lib has its own fixed tick. Two numbers describe it, and the header gives both:
+ - `
_TICK_RATE`: how many ticks per real second the host calls (30 for libfc, 60 for libray3).
+ - `
_TICK_SECONDS`: the exact game time one tick simulates. A lib reproduces its game's real
+ step, which need not be 1 / rate. Rayman 3 PC steps in whole milliseconds: 16 ms per frame at
+ 60 Hz, so the game runs at 96 % of real time (its dt is clamped and averaged; at a steady 60 Hz
+ that settles on 16 ms). The lib uses the step the game really takes at its nominal rate,
+ measured, and never a step taken from the host's clock.
+- `
_world_tick(world, n)` steps exactly n ticks. The host keeps its own accumulator against
+ `
_TICK_RATE`. Shared-unit velocities are per second of game time (`
_TICK_SECONDS`).
+- **Input delay.** If the game reads the pad late (Rayman 3: 1 frame), the lib does the same by
+ default: `
_INPUT_DELAY_TICKS` in the header, measured. The flag `
_CHAR_NO_INPUT_DELAY`
+ in `
_char_config` MAY turn it off for hosts that add their own latency. Inputs set but not
+ yet read are part of the snapshot.
+- No wall clock (`DateTime`, `Stopwatch`, `Environment.TickCount`), no `System.Random`, no
+ `HashCode.Combine`, no threads, no dictionary order in the simulation. A game RNG is reimplemented
+ and seeded from the world config.
+- Same lib build, same inputs, same collision answers: the same state, bit for bit, tick for tick,
+ **on every machine** (Windows, Linux, macOS; x64 and arm64). Rollback netcode depends on it.
+
+### Same bits on every machine
+
+A lib meets this one of two ways.
+
+1. **Integer or fixed-point maths**, as the game did (libfc: PS1 integers, 16.16, angle tables).
+ Integer maths is the same everywhere. Use the game's own tables, read from the user's data or
+ rebuilt from a formula; never a platform function.
+2. **Strict float rules**, for games that used floats (libray3):
+ - The simulation computes in the game's own precision: float32 if the game did (closer to the
+ original), else double. The header says which: `
_SIM_BITS` = 32, 64, or 0 for integer or
+ fixed point. The API structs still carry `double`, which holds float32 values exactly.
+ - float32 is just as deterministic under these rules. Store every intermediate in a `float`
+ 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
+ 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
+ platform and differ in the last bit. Use `DetMath` (own series) or tables.
+ - No fused multiply-add: no `Math.FusedMultiplyAdd`, no SIMD (`System.Numerics`,
+ `System.Runtime.Intrinsics`), no platform-dependent code paths. RyuJIT (NativeAOT and .NET) does
+ not fuse on its own.
+ - No float-to-int conversion of NaN, infinity or out-of-range values (x64 and arm64 give different
+ results). Clamp first.
+ - Hosts that compile Core themselves (Unity IL2CPP, Burst) must turn off fused maths
+ (Burst: `FloatMode.Deterministic`; IL2CPP: no guarantee, so use the native library for online play).
+- A test scans Core for forbidden calls (`DeterminismTests` in the template), and every replay
+ stores the expected state hash after its last row (`hash:`). CI runs the replays on Linux x64,
+ Windows x64 and macOS arm64, and the C test checks the same hash through the native library.
+
+### Replay format
+
+All libs share one text format. A replay is one character's inputs per tick plus expected state at
+checkpoints. Every `*.replay` file under `tests/*/Replays/` runs as a test.
+[TEMPLATE/Docs/REPLAY.md](TEMPLATE/Docs/REPLAY.md) is the full description; in short:
+
+```
+format: inklib-replay 1
+lib: tpl 1
+name: walk forward, jump, land
+source: UNVERIFIED: regression, recorded from the template itself
+units: native
+world: flat
+start: 0 0 0 0
+tolerance: 0.01
+
+ticks buttons move_x move_y look_x look_y | x y z yaw state
+10 0 0 0 0 0 | 0 0 0 0 Idle
+30 0 0 1 0 0 | 150 0 0 0 Walk
+1 jump 0 1 0 0 | 155 8 0 0 Jump
+40 0 0 1 0 0 | 355 123 0 0 Fall
+30 0 1 0 0 0 | 355 0 150 -1.570796 Walk
+```
+
+- Header lines `key: value`; `#` starts a comment. `format`, `lib` and `source` are required.
+ `hash: 0x<16 hex digits>` is the `
_state_hash` after the last row; every replay in a lib has one.
+- `source` starts with `VERIFIED:` (where and how it was measured) or `UNVERIFIED:` (why it exists).
+- `units`: `native` or `shared`. `world`: a test world defined in the lib's tests (never game geometry).
+ `start: x y z yaw`. `origin: x y z` (optional) means the checkpoints are game coordinates.
+ `tuning: Field value` overrides one tuning number for this file.
+- Table: input columns, `|`, check columns. `buttons` is `0`, a hex mask `0x..`, or button names
+ joined with `+`. `-` in a check column means "do not check". `state` is the state name.
+- A lib MAY add columns after `state`, named in the table header.
+
+## 6. Rollback support
+
+Every inklib is ready for rollback netcode, and it costs nothing for hosts that do not use it:
+the functions below exist in every lib but do no work unless called, and the lib keeps no history.
+
+- **Snapshot.** `
_save_state` writes the whole world: every character, the camera, inputs, RNG
+ state, timers, the tick, the id counters. `
_load_state` makes the world exactly that again.
+ After `save; tick N; load; tick N` with the same inputs the world is bit for bit the same as
+ after the first `tick N`. The template tests this (`RollbackTests`).
+- **Fast.** Plain bytes, no allocations while saving, no pointers inside. A host saves every tick and
+ keeps a ring of them; a few hundred bytes per character is normal.
+- **Portable.** The snapshot layout is fixed little-endian, so the same world gives the same bytes on
+ every machine. It starts with a magic number, a format number and a hash of the tuning;
+ `
_load_state` refuses a snapshot from another lib, format or tuning.
+- **Not in the snapshot:** the event buffer (load empties it) and anything the host owns (collision
+ geometry, moving platforms): the host rolls those back itself.
+
+### Lib-owned world state
+
+Some characters change the world as part of their rules: a Splatoon lib's ink coverage, objects a
+character places. A lib MAY keep such state when it belongs to its character's rules.
+
+- The rules stay in the lib. The storage sits behind a store interface: a struct of host callbacks
+ (`
_store`: `size`, `user`, then lib-defined read/write calls, for example per surface chunk),
+ passed in `
_world_config` like the collision callbacks. NULL selects the built-in default store.
+- **Default store:** the state lives in the lib and is part of the snapshot and the hash. The host
+ does nothing extra.
+- **Host store:** the host owns the data (to draw it, or to share it with other systems) and rolls it
+ back itself. The lib says so in its header, and the snapshot and hash then leave that state out.
+- **Big state as deltas.** A snapshot MAY store big world state as changes instead of a full copy:
+ for example the lib keeps an undo journal of changed chunks for the last
+ `
_world_config.rollback_window` ticks (0 = no journal: free unless used), and a snapshot holds
+ its journal position. Any snapshot in the window MUST still load, in any order, and the hash still
+ covers the full state.
+- A lib without world state says so in its header (the template does).
+- **Hash.** `
_state_hash` is FNV-1a 64 over the snapshot bytes. Two machines that agree on the
+ hash at a tick have the same world.
+- **Input.** Sticks are quantised to `round(stick * 127) / 127` when they are set. The simulation
+ depends only on that integer and on `buttons`, so a netcode host sends 4 bytes of sticks plus the
+ buttons per character per tick.
+- **Events.** Every event has `id` and `tick`. `id` is unique in the world and the same when its tick
+ is simulated again with the same inputs (template: `tick * 65536 + place in that tick`). A rollback
+ host plays an event once, when it first sees its id. After a rollback, an event that comes again
+ with the same `id`, `type`, `char_id`, `a` and `b` is the same event (do not play it again); an
+ event the host played that does not come again by the time its tick is re-simulated was wrong
+ (stop or undo it, for example cut a looping sound).
+
+The netcode itself is never part of a lib (section 13).
+
+## 7. Camera
+
+Every lib ships its character's camera, because the camera is part of how the character feels.
+This is where libs differ most.
+
+- Input: `look_x` / `look_y` in `
_input` plus whatever camera buttons the game had (in `buttons`).
+- Output: `
_char_camera` fills `
_camera`: `size`, `style`, `position`, `target`, `up`, `fov_y`
+ (vertical field of view, radians, always). `up` carries the roll. Position and target are in the
+ world's units.
+- Style tags: `FIRST_PERSON` = 1, `THIRD_PERSON` = 2, `CHASE` = 3, `TOP_DOWN` = 4, `FIXED` = 5.
+ `style` can change at run time (Project Zero switches between fixed views and the viewfinder).
+ libfc is `CHASE` / `TOP_DOWN`, libray3 is `THIRD_PERSON`, a Project Zero lib is `FIRST_PERSON`
+ in the viewfinder.
+- The camera uses `segment` with `SEGMENT_CAMERA` for its own collision.
+- With `
_CHAR_NO_CAMERA` the lib skips the camera and `
_char_camera` returns 0.
+- A lib MAY add its own camera fields (the game's rotation matrix, for example) at the end.
+
+## 8. Provenance
+
+Every gameplay number is VERIFIED (with its source) or UNVERIFIED (with the reason it was picked).
+
+- In code: each tuning field carries `[Verified("source")]` or `[Unverified("reason")]`, exactly one.
+- A unit test fails if a field has neither, both, or an empty text (`ProvenanceTests`).
+- Every `[Unverified]` field is named in `Docs/MEASURE.md` with how to verify it. A test checks this.
+- If the header exposes tuning, each field's comment says VERIFIED or UNVERIFIED; a test compares it
+ with the attribute (`HeaderTests`).
+- In docs: write VERIFIED (source) or UNVERIFIED next to every number. RESEARCH.md keeps facts and
+ pointers, and says which are our reading.
+- A source is specific: game version, level, method, date, or a document and section.
+- Replays carry the same tag in `source:`. A VERIFIED replay is never re-recorded; if it fails, the
+ lib is wrong.
+- Every PR lists what it made VERIFIED and what is still UNVERIFIED.
+
+## 9. Data rules
+
+- No game data in any shipped or committed file: no levels, meshes, textures, sounds, scripts,
+ executables, ELF or ISO files, raw or converted, not even "for a test". `.gitignore` blocks common
+ extensions and CI fails on them; that is a backstop, not permission.
+- Game data reaches a lib only at run time, from the user's own disc or install, through
+ `data_path`. Asset tools in a lib read the user's copy and write to the user's disk, never to the repo.
+- Single numbers with a source note are fine. Tables of numbers read from the game are fine if the lib
+ reads them from the user's data at run time instead of shipping them.
+- No copied code from decompilations, disassembly or game executables. Read them to understand; write
+ your own code. No translated functions, structs or tables.
+- Code from other open projects only with a fitting licence (MIT, BSD, Apache-2.0, zlib, public
+ domain), named at the top of the file. Never GPL, LGPL, AGPL or unlicensed code.
+- Each README says it is a fan project and that the user needs their own copy of the game.
+
+## 10. Packaging
+
+- Core: C#, `netstandard2.1`, C# 9, no NuGet dependencies, no engine references.
+- Native: NativeAOT shared library for `win-x64`, `linux-x64` and `osx-arm64`, from `.Native`.
+ Windows also ships `
.def` and an import library.
+- Unity: a UPM package (`unity/`) with Core as C# source in an asmdef with `noEngineReferences`.
+ Unity uses Core directly; it does not need the native library.
+- A minimal C example host (`native/example/host.c`): a flat floor, one character, prints its state.
+- CI on every PR: `dotnet test` on Linux x64, Windows x64 and macOS arm64 (replay hashes must match on
+ all three); native build plus C test on linux-x64, win-x64 and
+ osx-arm64; the data check.
+- A release attaches the three native libraries, the header, the `.def` and the Unity package.
+- Licence: TODO (octo decides; the standard does not pick one).
+
+## 11. Docs every lib has
+
+- `CLAUDE.md`: hard rules for anyone, human or AI, working in the repo.
+- `Docs/PLAN.md`: stages; only one is built at a time.
+- `Docs/RESEARCH.md`: what is known about the game and where it came from.
+- `Docs/MEASURE.md`: how to verify each UNVERIFIED number in the real game.
+- `Docs/REPLAY.md`: the replay format and this lib's test worlds.
+
+## 12. Optional modules (not core)
+
+Some hosts want more than movement. These parts are optional and are kept out of the core API so a
+lib stays useful on its own. Each module:
+
+- lives in its own header `
_.h` and its own table from `
_get__api()`,
+ which returns NULL if the lib does not have the module;
+- MUST NOT add fields to core structs or change core behaviour when it is not used;
+- follows the same ABI, units and provenance rules.
+
+Presentation (any host): `look` (draw the character the game's way: mesh, atlas, animation frame read
+from the user's data), `lights`.
+
+The arena set, from libfc's v5-v7 shape. Together they form the later **inklib-arena** add-on, which
+gets its own standard when it starts:
+
+| Module | Shape |
+|---|---|
+| `damage` | Health and max health per character, team, `damage(id, amount, source)`, `DIED` event. |
+| `targets` | The host registers things the character can aim at (id, position, box, team). |
+| `weapons` | Weapon slots, ammo, `rearm`; firing comes from `buttons`. |
+| `shots` | Shots in flight as polled data (position, velocity, owner, kind); hits as events. |
+| `hud` | The game's HUD as data: quads plus atlas, aim point, lock-on mark. The host draws it. |
+| `vehicle` | `pilot` / `park`: a character enters or leaves something it drives. |
+
+Arena rules (meeting characters, scoring, unit scale between games) MUST NOT appear in a core lib.
+
+## 13. inklib-net (optional add-on, planned)
+
+inklib-net is a later, separate add-on for online play. It is described here so every lib is built
+for it; there is no code yet. No lib depends on it, and it holds no game rules.
+
+It is GGPO-style rollback over any inklib (or several), through the function tables:
+
+- **Input exchange.** Each player's input per tick (`buttons` + 4 quantised stick bytes) goes to every
+ peer, tagged with the tick, sent a few times to survive loss.
+- **Prediction.** When a remote input has not arrived, the host predicts it (repeat the last one) and
+ ticks on at once. It saves a snapshot every tick, keeping a ring of the last N (N = the rollback window, for
+ example 8 ticks at 60 Hz).
+- **Resimulation.** When a remote input arrives and differs from the prediction, the host loads the
+ snapshot of that tick, sets the real inputs, and ticks again to the present in one frame. Events
+ are reconciled by id (section 6).
+- **Desync detection.** Peers exchange `
_state_hash` for confirmed ticks (every tick or every few).
+ A mismatch is a desync: stop, report the tick, and save both sides' snapshots and inputs as a replay
+ for the bug report.
+- **Mixed tick rates.** All libs in a session hang off one host clock (for example 60 Hz). A lib with
+ rate R steps when `floor(frame * R / host_rate)` grows: a 30 Hz lib (libfc) steps every second frame
+ of a 60 Hz clock, a 60 Hz lib (libray3) every frame. Inputs, snapshots, hashes and rollbacks are
+ kept per lib tick and mapped through the same formula. Rates that do not divide the host rate work
+ the same way.
+- **Lockstep** (wait for all inputs, never predict) is the simple special case: N = 0, hashes still
+ checked. It suits games whose lib is too slow to resimulate.
+- **Spectating and replays** reuse the same input stream; a recorded session is an inklib replay per
+ character plus the hashes.
+
+What inklib-net does not do: matchmaking, NAT punch-through, accounts, voice. Those belong to the host.
+
diff --git a/TEMPLATE/.github/workflows/ci.yml b/TEMPLATE/.github/workflows/ci.yml
new file mode 100644
index 0000000..8b478c1
--- /dev/null
+++ b/TEMPLATE/.github/workflows/ci.yml
@@ -0,0 +1,55 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - run: dotnet build --configuration Release
+ - run: dotnet test --configuration Release --no-build
+
+ native:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: ubuntu-latest, rid: linux-x64 }
+ - { os: windows-latest, rid: win-x64 }
+ - { os: macos-latest, rid: osx-arm64 }
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: 8.0.x
+ - if: runner.os == 'Linux'
+ run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev
+ - run: native/build_and_test.sh ${{ matrix.rid }}
+ shell: bash
+ - uses: actions/upload-artifact@v4
+ with:
+ name: libtpl-${{ matrix.rid }}
+ path: |
+ native/build/${{ matrix.rid }}/libtpl.*
+ native/build/${{ matrix.rid }}/tpl.lib
+ native/include/tpl.h
+ native/tpl.def
+
+ checks:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: tools/check-no-game-data.sh
+ - run: unity/pack.sh
diff --git a/TEMPLATE/.gitignore b/TEMPLATE/.gitignore
new file mode 100644
index 0000000..d64e18c
--- /dev/null
+++ b/TEMPLATE/.gitignore
@@ -0,0 +1,33 @@
+bin/
+obj/
+*.user
+.vs/
+.idea/
+TestResults/
+native/build/
+unity/Runtime/Core/
+
+# Never commit game files (see CLAUDE.md). CI checks these too (tools/check-no-game-data.sh).
+*.iso
+*.bin
+*.cue
+*.img
+*.mdf
+*.chd
+*.exe
+*.elf
+*.dll
+*.so
+*.dylib
+*.wad
+*.pak
+*.cnt
+*.lvl
+*.sna
+*.str
+*.xa
+*.vag
+*.tim
+*.vh
+*.vb
+unity/README.md
diff --git a/TEMPLATE/CLAUDE.md b/TEMPLATE/CLAUDE.md
new file mode 100644
index 0000000..21e86eb
--- /dev/null
+++ b/TEMPLATE/CLAUDE.md
@@ -0,0 +1,93 @@
+# CLAUDE.md
+
+Rules for anyone (human or AI) working in this repo.
+
+## What this is
+
+libtpl is an inklib: a small library that moves ONE character from ONE game
+exactly like the original, for any engine. It follows the inklib standard
+(SPEC.md in the inklib repo; API version in `native/include/tpl.h`). It is
+useful on its own. It does not draw or play sound; it tells the host what to
+draw and play.
+
+## Hard rules
+
+1. **Core is plain C#.** `src/Tpl.Core` targets netstandard2.1, C# 9. No
+ Unity, Godot or other engine references. No NuGet dependencies in Core.
+2. **Deterministic fixed tick, same bits on every machine.** Core steps in
+ fixed ticks (`Tuning.TickRate`, the game's logic rate). No `System.Random`,
+ no `DateTime`, no `Stopwatch`, no `Environment.TickCount`, no
+ `HashCode.Combine`, no threads, no dictionary order. Compute in the game's
+ precision (`TPL_SIM_BITS`: float32 if the game did, else double); no
+ `Math.Sin/Cos/Atan2/Pow/...`, no `MathF`, no SIMD, no fused multiply-add:
+ use `DetMath`. Reproduce the game's real tick step (`Tuning.TickSeconds`)
+ and input delay (`Tuning.InputDelayTicks`): closeness to the original
+ comes first. `DeterminismTests` scans for these. Every replay stores a
+ state hash, and CI checks it on Linux, Windows and macOS arm64.
+ Recording a replay again changes its hash: also update the hash in
+ `native/tests/test_tpl.c`.
+3. **Rollback-ready.** All simulation state goes into the snapshot
+ (`Character.Save`/`Load`, `World.SaveState`). New state without a snapshot
+ field is caught by `RollbackTests` when it changes later ticks. Events keep
+ their `Id` and `Tick`. Netcode itself never goes into the lib.
+4. **Native units inside.** The simulation runs in the game's own units.
+ Shared units (metres, seconds, radians, Z up) exist only at the API
+ boundary, in `Units.cs`. Keep `Units.cs` and the `TPL_NATIVE_*` macros equal.
+5. **No game files, ever.** No levels, meshes, textures, sounds, scripts,
+ executables, ELF or ISO files, raw or converted, not even for a test. Game
+ data reaches the lib only at run time from the user's own copy
+ (`data_path`). `.gitignore` and CI block common extensions; that is a
+ backstop, not permission.
+6. **No copied code.** Decompilations, disassembly and tools may be read to
+ understand the game. Write our own code. Do not paste or translate their
+ functions, structs or tables. Single numbers with a source note are fine.
+ Code from open projects only under MIT, BSD, Apache-2.0, zlib or public
+ domain, named at the top of the file. Never GPL, LGPL, AGPL or unlicensed.
+7. **Every gameplay number is tagged.** Each `Tuning` field has exactly one of
+ `[Verified("source")]` or `[Unverified("reason")]`, and every UNVERIFIED one
+ is named in `Docs/MEASURE.md`. Tests fail otherwise. In docs, write VERIFIED
+ (with source) or UNVERIFIED next to every number.
+8. **Collision only through the host.** Core never sees meshes. The host
+ answers ground, segment and overlap (`ICollisionWorld`, `tpl_collision`).
+ Test geometry lives in the test project and is never game geometry.
+9. **C API rules.** Prefix `tpl_`. Plain C structs, fixed-size ints, versioned
+ structs start with `size`, no callbacks except collision, errors through
+ `tpl_last_error`, never a crash on a bad argument. `tpl.h`, `tpl.def` and
+ Core stay in step (`HeaderTests`). Bump `TPL_API_VERSION` on any change a
+ host could notice.
+10. **The camera is part of the character.** Ship the game's camera.
+11. **Core stays core.** Damage, targets, weapons, shots, HUD and vehicles are
+ optional modules in their own header and table (SPEC.md section 12).
+ Netcode is never in a lib (SPEC.md section 13: inklib-net).
+ Nothing about other games or an arena goes into this lib.
+12. **Keep it small. Plain docs.** Short sentences. Say what the code does.
+ Add a feature only when its stage in `Docs/PLAN.md` starts.
+
+## Commands
+
+```
+dotnet build
+dotnet test
+native/build_and_test.sh # NativeAOT build + C test + example host
+```
+
+Linux needs clang and zlib headers for NativeAOT; Windows (Git Bash) needs the
+Visual Studio C++ tools and clang; macOS needs the Xcode command line tools.
+
+## Layout
+
+```
+src/Tpl.Core/ the simulation (netstandard2.1)
+src/Tpl.Native/ C API exports (NativeAOT, net8.0)
+tests/Tpl.Core.Tests/ xunit tests, test worlds, Replays/
+native/ tpl.h, tpl.def, C test, example host, build script
+unity/ UPM package (Core as source)
+Docs/ PLAN, RESEARCH, MEASURE, REPLAY
+```
+
+## Workflow
+
+- One PR per task. The PR description lists what became VERIFIED and what is
+ still UNVERIFIED.
+- CI must pass: `dotnet test` (Linux, Windows, macOS arm64), native build and C test
+ (linux-x64, win-x64, osx-arm64), data check.
diff --git a/TEMPLATE/Docs/MEASURE.md b/TEMPLATE/Docs/MEASURE.md
new file mode 100644
index 0000000..0e87b68
--- /dev/null
+++ b/TEMPLATE/Docs/MEASURE.md
@@ -0,0 +1,68 @@
+# Measurement wishlist
+
+Numbers to measure in the real game. Each one turns an UNVERIFIED field in
+`src/Tpl.Core/Tuning.cs` into a VERIFIED one. `ProvenanceTests` fails if an
+UNVERIFIED field is not named here.
+
+Nothing measured goes into the repo except the numbers and a note on how
+they were taken: no screenshots, no videos, no game files.
+
+## How to measure
+
+Write down the method for this game. The usual three:
+
+- **A. Memory log.** Run the game, find the character's position in memory,
+ log it every frame. Most accurate. A log can go straight into a replay
+ file ([REPLAY.md](REPLAY.md)).
+- **B. Video.** Record at the game's frame rate, constant frame rate, step
+ frame by frame.
+- **C. Data.** Read the value from your own copy of the game's data with a
+ viewer. Write the number down; do not export or commit the data.
+
+Do each item three times. Write down all three values, the game version,
+the place and the method.
+
+## M0. Tick rate, tick step and input delay
+
+- **What:** (a) How many logic steps per real second. (b) How much game time
+ one step really simulates: games often step in whole milliseconds or clamp
+ and average dt, so the step need not be 1 / rate (Rayman 3 PC: 16 ms at
+ 60 Hz, so the game runs at 96 % of real time). (c) How many steps pass
+ between a button press and the game reacting.
+- **How:** A: log position and the game's own timer every frame; the timer
+ delta is the step. Compare a stopwatch over a long run with the game's
+ timer. For (c), log the pad state next to the position and count frames
+ from press to the first change.
+- **Pins:** `Tuning.TickRate`, `Tuning.TickSeconds`, `Tuning.InputDelayTicks`.
+- **Status:** open (template placeholders).
+
+## M1. Walk speed
+
+- **What:** Speed on flat ground at full stick, and the dead zone.
+- **How:** A: positions over one second at full speed. Stick tilts near zero for the dead zone.
+- **Pins:** `Tuning.WalkSpeed`, `Tuning.StickDeadzone`.
+- **Status:** open (template placeholder).
+
+## M2. Jump and gravity
+
+- **What:** Take-off speed, apex height, time to apex, gravity while falling.
+- **How:** A: log the height every frame from take-off to landing.
+- **Pins:** `Tuning.JumpSpeed`, `Tuning.Gravity`.
+- **Status:** open (template placeholder).
+
+## M3. Body and steps
+
+- **What:** Body radius and height; tallest step walked up without a jump.
+- **How:** C: collision shape in the data. A/B: steps of known height.
+- **Pins:** `Tuning.BodyRadius`, `Tuning.BodyHeight`, `Tuning.StepHeight`.
+- **Status:** open (template placeholder).
+
+## M4. Camera
+
+- **What:** Distance and height behind the character, turn speed at full
+ look stick, vertical field of view.
+- **How:** A: camera position next to the character's. C: projection
+ settings in the data.
+- **Pins:** `Tuning.CameraDistance`, `Tuning.CameraHeight`,
+ `Tuning.CameraTurnSpeed`, `Tuning.CameraFovY`.
+- **Status:** open (template placeholder).
diff --git a/TEMPLATE/Docs/PLAN.md b/TEMPLATE/Docs/PLAN.md
new file mode 100644
index 0000000..465b88b
--- /dev/null
+++ b/TEMPLATE/Docs/PLAN.md
@@ -0,0 +1,35 @@
+# Plan
+
+libtpl grows in stages. Only one stage is built at a time. A stage is done
+when its tests pass and every number in it is VERIFIED or listed in
+[MEASURE.md](MEASURE.md).
+
+## Ground rules for every stage
+
+- The inklib standard (SPEC.md in the inklib repo), API version in `tpl.h`.
+- Core is netstandard2.1, C# 9, no engine, fixed tick, deterministic.
+- Simulation in native units; shared units only at the API boundary.
+- Collision only through the host callbacks.
+- Every gameplay number is VERIFIED (with source) or UNVERIFIED.
+
+## v1: basic movement (now)
+
+| Feature | What it means here |
+|---|---|
+| Idle / walk | Stick moves the character camera-relative. |
+| Jump / fall | Jump button on the ground; gravity in the air. |
+| Steps | Small rises are walked up. |
+| Camera | The game's camera, with its own collision. |
+
+Deliverables: Core, C API, C test, example host, replays, RESEARCH.md,
+MEASURE.md.
+
+## v2 (later)
+
+Write the next stage here when v1 is done.
+
+## Out of scope
+
+- Rendering, animation playback, sound playback (events tell the host).
+- Shipping any game data.
+- Optional modules (SPEC.md section 12) until the core is done.
diff --git a/TEMPLATE/Docs/REPLAY.md b/TEMPLATE/Docs/REPLAY.md
new file mode 100644
index 0000000..54e3a70
--- /dev/null
+++ b/TEMPLATE/Docs/REPLAY.md
@@ -0,0 +1,87 @@
+# Replay files
+
+A replay is one character's inputs per tick plus where it should be. Every
+`*.replay` in `tests/Tpl.Core.Tests/Replays/` runs as a test
+(`ReplayTests.ReplayMatches`). The format is the same in every inklib
+(SPEC.md section 5); only the button names, state names and test worlds
+are this lib's.
+
+## Example
+
+```
+format: inklib-replay 1
+lib: tpl 1
+name: standing jump
+source: VERIFIED: game v1.0, memory log (MEASURE.md A), level 1 start, 2026-11-02
+units: native
+world: flat
+start: 0 0 0 0
+origin: 1234 56 -789
+tolerance: 0.5
+
+ticks buttons move_x move_y look_x look_y | x y z yaw state
+10 0 0 0 0 0 | 1234 56 -789 - Idle
+1 jump 0 0 0 0 | - 64 - - Jump
+```
+
+The numbers above only show the format; they are not a measurement.
+
+## Header lines
+
+One `key: value` per line, before the table. `#` starts a comment.
+
+| Key | Required | Meaning |
+|---|---|---|
+| `format` | yes, first | `inklib-replay 1`. |
+| `lib` | yes | Prefix and API version the file was written for: `tpl 1`. |
+| `source` | yes | `VERIFIED: ...` (where, how, when) or `UNVERIFIED: ...` (why). |
+| `name` | no | Shown in failures. Defaults to the file name. |
+| `units` | no (`native`) | `native` or `shared` (metres, Z up). All numbers in the file use it. |
+| `world` | no (`flat`) | A test world (below). |
+| `start` | no (`0 0 0 0`) | Feet `x y z` and `yaw` at tick 0. |
+| `origin` | no | The character's position in the game at tick 0. If given, x y z are game coordinates: the runner subtracts `origin` and adds `start`. |
+| `tolerance` | no (0.01) | Allowed difference per column, in the file's units. |
+| `tuning` | no, repeatable | `tuning: Field value` overrides one `Tuning` field. |
+| `hash` | yes in this lib | `hash: 0x` + 16 hex digits: `tpl_state_hash` after the last row. Positions within tolerance but a different hash means the bits differ: a determinism bug, or a deliberate change. |
+
+## Table
+
+The header line is exactly:
+
+```
+ticks buttons move_x move_y look_x look_y | x y z yaw state
+```
+
+| Column | Meaning |
+|---|---|
+| `ticks` | How many ticks this input is held (1 or more). |
+| `buttons` | `0`, a hex mask `0x..`, or names joined by `+` (`jump`). |
+| `move_x move_y look_x look_y` | Sticks, -1..1, as the player holds them. |
+| `x y z yaw` | Expected after the last tick of the row. `-` = do not check. |
+| `state` | Expected state name (`Idle`, `Walk`, `Jump`, `Fall`), or `-`. |
+
+A game log at the logic rate becomes one row per tick with `ticks` = 1.
+
+## Worlds
+
+In `tests/Tpl.Core.Tests/TestWorlds.cs` (`TestWorld.Make`). Never game geometry.
+
+| Name | Geometry (native units) |
+|---|---|
+| `flat` | Floor at y = 0. |
+| `step` | Floor; a 20 cm step from x = 200; a 100 cm wall from x = 400. |
+
+## Regression replays
+
+`UNVERIFIED` replays recorded from the lib itself catch accidental changes.
+After a deliberate change, record them again:
+
+```
+INKLIB_RECORD_REPLAYS=$PWD/tests/Tpl.Core.Tests/Replays dotnet test --filter RecordRegressionReplays
+```
+
+Recording rewrites the `hash:` lines too. `native/tests/test_tpl.c` repeats
+the hash of `walk-and-jump.replay` to check the native library; update it there.
+
+Measured (`VERIFIED`) replays are never re-recorded. If one fails, the lib
+is wrong.
diff --git a/TEMPLATE/Docs/RESEARCH.md b/TEMPLATE/Docs/RESEARCH.md
new file mode 100644
index 0000000..09e4d5a
--- /dev/null
+++ b/TEMPLATE/Docs/RESEARCH.md
@@ -0,0 +1,42 @@
+# Research
+
+What we know about how the character moves in the game, gathered from
+public sources and the user's own copy. Facts and pointers only: no code
+from the game, a decompilation or a tool. Where a line says "we think",
+it is our reading, not a confirmed fact.
+
+## Sources
+
+List each source with a link, the version or commit read, the date, and
+its licence. A source without a licence may be read, never copied.
+
+| # | Source | Version / date | Licence |
+|---|---|---|---|
+| 1 | (e.g. a decompilation) | commit, date | none: read only |
+
+## 1. Engine and tick
+
+- Logic rate, frame timing, fixed or variable step. UNVERIFIED until M0.
+
+## 2. Units and axes
+
+- Native length unit, angle unit, up axis, handedness, fixed point format.
+ Keep `Units.cs` and the `TPL_NATIVE_*` macros in `tpl.h` in step with this.
+
+## 3. Movement rules
+
+- One subsection per state. Name the source of every number.
+
+## 4. Collision
+
+- What the game asks its collision system, and how that maps onto
+ ground, segment, overlap (and sweep if needed). Material flags and how
+ they map onto the standard surface bits.
+
+## 5. Camera
+
+- Camera style(s), how input turns it, its collision.
+
+## 6. Open questions
+
+- What we do not know yet, and which MEASURE.md item would settle it.
diff --git a/TEMPLATE/LICENSE b/TEMPLATE/LICENSE
new file mode 100644
index 0000000..795af2e
--- /dev/null
+++ b/TEMPLATE/LICENSE
@@ -0,0 +1 @@
+TODO (octo): choose a licence before publishing. Until then, all rights reserved.
diff --git a/TEMPLATE/README.md b/TEMPLATE/README.md
new file mode 100644
index 0000000..5a34775
--- /dev/null
+++ b/TEMPLATE/README.md
@@ -0,0 +1,68 @@
+# libtpl
+
+TODO: one sentence. "'s movement from (), for any engine."
+
+This is a fan project. It contains no game files and no code from the game
+or any decompilation. You need your own copy of the game.
+
+It is an [inklib](https://github.com/OctoAlgo/inklib): it moves one
+character exactly like the original, with the game's own camera. You give it
+pad input once per tick and answer its collision questions. It gives back a
+position, a velocity, a facing, a state, the camera, and events (landed,
+play this sound, ...). Drawing and sound are yours.
+
+## Start a new lib from this template
+
+```
+cp -r TEMPLATE ../inklib-
+cd ../inklib-
+./rename.sh # e.g. ./rename.sh pz Pz
+git init
+```
+
+Then replace the template's numbers and rules: `Units.cs` (+ the
+`TPL_NATIVE_*` macros), `Tuning.cs`, `Character.cs`, the header enums,
+and the Docs.
+
+## Build and test
+
+Needs the .NET 8 SDK.
+
+```
+dotnet test
+native/build_and_test.sh
+```
+
+## C API
+
+Header: [native/include/tpl.h](native/include/tpl.h). Smallest host:
+[native/example/host.c](native/example/host.c).
+
+```c
+tpl_world_config wc = { sizeof wc, TPL_UNITS_SHARED, NULL }; /* metres, Z up */
+tpl_world *w = tpl_world_create(&wc, &collision); /* your callbacks */
+tpl_char_config cc = { sizeof cc };
+int32_t id = tpl_char_add(w, &cc);
+/* every tick: */
+tpl_char_input(w, id, &input);
+tpl_world_tick(w, 1);
+tpl_char_state(w, id, &state);
+tpl_char_camera(w, id, &camera);
+n = tpl_events(w, events, 32);
+/* rollback hosts: snapshot, hash, restore (free unless called) */
+int32_t size = tpl_state_size(w);
+tpl_save_state(w, buf, size);
+uint64_t h = tpl_state_hash(w);
+tpl_load_state(w, buf, size);
+/* at the end: */
+tpl_world_destroy(w);
+```
+
+## Unity
+
+`unity/` is a UPM package with Core as C# source. Run `unity/pack.sh`, then
+add the folder in the Package Manager ("Add package from disk").
+
+## Licence
+
+TODO (octo): pick a licence before the first publish. See LICENSE.
diff --git a/TEMPLATE/native/build_and_test.sh b/TEMPLATE/native/build_and_test.sh
new file mode 100755
index 0000000..9903023
--- /dev/null
+++ b/TEMPLATE/native/build_and_test.sh
@@ -0,0 +1,48 @@
+#!/bin/sh
+# Builds the C API with NativeAOT, runs the C test and the example host.
+# Usage: native/build_and_test.sh [linux-x64|win-x64|osx-arm64] (default: this machine)
+# Linux needs: .NET 8 SDK, cc, clang and zlib headers. macOS needs: .NET 8 SDK, Xcode tools.
+# Windows (Git Bash) needs: .NET 8 SDK, Visual Studio C++ tools, clang.
+set -eu
+cd "$(dirname "$0")/.."
+
+case "$(uname -s)" in
+ MINGW*|MSYS*|CYGWIN*) default_rid=win-x64 ;;
+ Darwin) default_rid=osx-arm64 ;;
+ *) default_rid=linux-x64 ;;
+esac
+rid=${1:-$default_rid}
+out=native/build/$rid
+cflags="-std=c99 -Wall -Wextra -Werror -Wno-unused-function -I native/include"
+
+dotnet publish src/Tpl.Native/Tpl.Native.csproj -c Release -r "$rid" -o "$out" --nologo -v quiet
+
+case "$rid" in
+ win-*)
+ # Import library from native/tpl.def (llvm-lib comes with LLVM/clang).
+ llvm-lib /nologo /machine:x64 /def:native/tpl.def /out:"$out/tpl.lib"
+ for prog in tests/test_tpl example/host; do
+ name=$(basename "$prog")
+ clang $cflags -D_CRT_SECURE_NO_WARNINGS "native/$prog.c" "$out/tpl.lib" -o "$out/$name.exe"
+ "$out/$name.exe"
+ done
+ ;;
+ osx-*)
+ # NativeAOT leaves a relative install name; make it @rpath so hosts can find the dylib,
+ # then re-sign (arm64 refuses to load a dylib whose signature no longer matches).
+ install_name_tool -id @rpath/libtpl.dylib "$out/libtpl.dylib"
+ codesign --force --sign - "$out/libtpl.dylib"
+ for prog in tests/test_tpl example/host; do
+ name=$(basename "$prog")
+ cc $cflags "native/$prog.c" -L "$out" -ltpl -Wl,-rpath,@executable_path -o "$out/$name"
+ "$out/$name"
+ done
+ ;;
+ *)
+ for prog in tests/test_tpl example/host; do
+ name=$(basename "$prog")
+ cc $cflags "native/$prog.c" -L "$out" -ltpl -lm -Wl,-rpath,'$ORIGIN' -o "$out/$name"
+ "$out/$name"
+ done
+ ;;
+esac
diff --git a/TEMPLATE/native/example/host.c b/TEMPLATE/native/example/host.c
new file mode 100644
index 0000000..ce7c8c4
--- /dev/null
+++ b/TEMPLATE/native/example/host.c
@@ -0,0 +1,59 @@
+/* The smallest inklib host: a flat floor, one character, two seconds of walking and a jump.
+ Prints the character's state and the camera, and the events, in shared units (metres, Z up). */
+#include
+#include
+#include "tpl.h"
+#include "../flat_floor.h"
+
+int main(void)
+{
+ int up = 2; /* shared units: Z up */
+ tpl_collision col = flat_floor(&up);
+ tpl_world_config wc = { sizeof(tpl_world_config), TPL_UNITS_SHARED, NULL };
+ tpl_char_config cc;
+ tpl_input in;
+ tpl_state s;
+ tpl_camera cam;
+ tpl_event ev[32];
+ int32_t id, tick, n, i;
+ char err[256];
+
+ tpl_world *w = tpl_world_create(&wc, &col);
+ if (!w) {
+ tpl_last_error(err, sizeof err);
+ printf("tpl_world_create failed: %s\n", err);
+ return 1;
+ }
+
+ memset(&cc, 0, sizeof cc);
+ cc.size = sizeof cc;
+ id = tpl_char_add(w, &cc);
+
+ memset(&in, 0, sizeof in);
+ in.size = sizeof in;
+ memset(&s, 0, sizeof s);
+ s.size = sizeof s;
+ memset(&cam, 0, sizeof cam);
+ cam.size = sizeof cam;
+
+ for (tick = 0; tick < 2 * TPL_TICK_RATE; tick++) {
+ in.move_y = 1.0f; /* stick up */
+ in.buttons = tick == TPL_TICK_RATE ? TPL_BUTTON_JUMP : 0;
+ tpl_char_input(w, id, &in);
+ tpl_world_tick(w, 1); /* one fixed tick */
+
+ n = tpl_events(w, ev, 32);
+ for (i = 0; i < n; i++)
+ printf(" event %d at tick %lld (a=%d b=%d)\n", ev[i].type, (long long)ev[i].tick, ev[i].a, ev[i].b);
+
+ if ((tick + 1) % 15 == 0) {
+ tpl_char_state(w, id, &s);
+ tpl_char_camera(w, id, &cam);
+ printf("tick %3lld state %d pos %.3f %.3f %.3f camera %.2f %.2f %.2f\n", (long long)s.tick, s.state,
+ s.position.x, s.position.y, s.position.z, cam.position.x, cam.position.y, cam.position.z);
+ }
+ }
+
+ tpl_world_destroy(w);
+ return 0;
+}
diff --git a/TEMPLATE/native/flat_floor.h b/TEMPLATE/native/flat_floor.h
new file mode 100644
index 0000000..12e1ce7
--- /dev/null
+++ b/TEMPLATE/native/flat_floor.h
@@ -0,0 +1,71 @@
+/* A flat floor at height 0 as tpl_collision callbacks, shared by the C test and the example host.
+ user points to an int: the up axis (1 = Y for native units, 2 = Z for shared units). */
+#ifndef TPL_FLAT_FLOOR_H
+#define TPL_FLAT_FLOOR_H
+
+#include "tpl.h"
+
+static double *axis_of(tpl_vec3 *v, int axis) { return axis == 0 ? &v->x : axis == 1 ? &v->y : &v->z; }
+static double up_of(const tpl_vec3 *v, int axis) { return axis == 0 ? v->x : axis == 1 ? v->y : v->z; }
+
+static void floor_hit(int axis, tpl_vec3 at, double t, tpl_hit *out)
+{
+ tpl_vec3 n = { 0.0, 0.0, 0.0 };
+ *axis_of(&at, axis) = 0.0;
+ *axis_of(&n, axis) = 1.0;
+ out->point = at;
+ out->normal = n;
+ out->t = t;
+ out->surface = 0;
+ out->actor = 0;
+}
+
+static int32_t floor_ground(void *user, const tpl_vec3 *from, double max_drop, tpl_hit *out)
+{
+ int axis = *(const int *)user;
+ double h = up_of(from, axis);
+ if (h < 0.0 || h > max_drop) return 0;
+ floor_hit(axis, *from, max_drop > 0.0 ? h / max_drop : 0.0, out);
+ return 1;
+}
+
+static int32_t floor_segment(void *user, const tpl_vec3 *a, const tpl_vec3 *b, uint32_t flags, tpl_hit *out)
+{
+ int axis = *(const int *)user;
+ double ha = up_of(a, axis), hb = up_of(b, axis), t;
+ tpl_vec3 p;
+ if ((flags & TPL_SEGMENT_SKIP_FLOORS) || ha < 0.0 || hb >= 0.0) return 0;
+ t = ha / (ha - hb);
+ p.x = a->x + (b->x - a->x) * t;
+ p.y = a->y + (b->y - a->y) * t;
+ p.z = a->z + (b->z - a->z) * t;
+ floor_hit(axis, p, t, out);
+ return 1;
+}
+
+static int32_t floor_overlap(void *user, const tpl_shape *s, tpl_hit *out)
+{
+ int axis = *(const int *)user;
+ double bottom;
+ switch (s->kind) {
+ case TPL_SHAPE_SPHERE: bottom = up_of(&s->a, axis) - s->radius; break;
+ case TPL_SHAPE_CAPSULE: {
+ double ha = up_of(&s->a, axis), hb = up_of(&s->b, axis);
+ bottom = (ha < hb ? ha : hb) - s->radius;
+ break;
+ }
+ default: bottom = up_of(&s->a, axis) - up_of(&s->half_extents, axis); break;
+ }
+ if (bottom >= 0.0) return 0;
+ floor_hit(axis, s->a, 0.0, out);
+ return 1;
+}
+
+/* *up_axis must stay valid while the world lives. */
+static tpl_collision flat_floor(int *up_axis)
+{
+ tpl_collision c = { sizeof(tpl_collision), up_axis, floor_ground, floor_segment, floor_overlap, 0 };
+ return c;
+}
+
+#endif
diff --git a/TEMPLATE/native/include/tpl.h b/TEMPLATE/native/include/tpl.h
new file mode 100644
index 0000000..bd86d97
--- /dev/null
+++ b/TEMPLATE/native/include/tpl.h
@@ -0,0 +1,305 @@
+/*
+ * tpl.h - C API of libtpl, an inklib (see the inklib SPEC.md).
+ *
+ * Native units (the game's own; this template's are an example):
+ * length 1 unit = 1 cm, angles in radians, Y up, right-handed,
+ * velocity in units per tick, yaw 0 = +X, forward = (cos yaw, 0, -sin yaw).
+ * Shared units (TPL_UNITS_SHARED): metres, seconds, radians, Z up, right-handed,
+ * yaw 0 = +X turning towards +Y, velocity in metres per second.
+ * The world config picks one. Every position, direction, velocity and angle that
+ * crosses this API, including the collision callbacks, is then in that convention.
+ * Field of view is always radians. Sticks are always -1..1.
+ *
+ * Time: the host calls tpl_world_tick TPL_TICK_RATE times per real second. Each tick simulates
+ * exactly TPL_TICK_SECONDS of game time: the game's real step, which need not be 1 / rate
+ * (Rayman 3 PC: 60 Hz, 0.016 s, so the game runs at 96 % of real time). Shared-unit
+ * velocities are per second of game time. tpl_world_tick(w, n) steps n ticks.
+ * Input: the game reads the pad TPL_INPUT_DELAY_TICKS ticks after tpl_char_input sets it,
+ * like the original. TPL_CHAR_NO_INPUT_DELAY turns that off for one character.
+ * The simulation computes in TPL_SIM_BITS reals, as the game did; the API always uses double.
+ * One world is used from one thread at a time. Worlds share nothing.
+ * Functions returning int32_t return 1 (or an id) on success, 0 on error;
+ * tpl_last_error() then says why.
+ *
+ * Versioned structs start with uint32_t size: set it to sizeof(the struct).
+ * The lib reads and writes only min(size, its own size) bytes; missing fields are zero.
+ *
+ * Collision callbacks needed: ground, segment, overlap. sweep is not used (may be NULL).
+ *
+ * Rollback: tpl_save_state / tpl_load_state snapshot the whole world (characters, cameras,
+ * inputs including the delayed ones, tick). libtpl keeps no world state of its own (no store). tpl_state_hash checks two machines agree. The lib keeps no history and these
+ * cost nothing unless called. The simulation gives the same bits on every machine (no platform
+ * maths), and sticks are quantised to steps of 1/127.
+ */
+#ifndef TPL_H
+#define TPL_H
+
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define TPL_API_VERSION 1
+
+/* Native units. Same as tpl_units() and Tpl.Units. */
+#define TPL_NATIVE_METRES_PER_UNIT 0.01
+#define TPL_NATIVE_RADIANS_PER_UNIT 1.0
+#define TPL_NATIVE_UP_AXIS 1 /* 0 = X, 1 = Y, 2 = Z */
+#define TPL_NATIVE_UP_SIGN 1 /* +1 or -1 */
+#define TPL_NATIVE_HANDEDNESS 1 /* +1 right-handed, -1 left-handed */
+#define TPL_NATIVE_VELOCITY_PER_TICK 1 /* 1: units per tick, 0: units per second */
+#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_SIM_BITS 64 /* the simulation's reals: 32 = float32, 64 = double, 0 = integer/fixed */
+
+enum {
+ TPL_UNITS_NATIVE = 0,
+ TPL_UNITS_SHARED = 1,
+};
+
+/* Surface flags. Bits 0..15 are the same in every inklib; 16..31 are this lib's own. */
+enum {
+ TPL_SURFACE_NO_COLLISION = 1u << 0,
+ TPL_SURFACE_WATER = 1u << 1,
+ TPL_SURFACE_HURT = 1u << 2,
+ TPL_SURFACE_DEATH = 1u << 3,
+ TPL_SURFACE_SLIDE = 1u << 4,
+ TPL_SURFACE_LEDGE = 1u << 5,
+ TPL_SURFACE_CLIMB = 1u << 6,
+ TPL_SURFACE_HANG = 1u << 7,
+ TPL_SURFACE_BOUNCE = 1u << 8,
+ TPL_SURFACE_CAMERA_PASS = 1u << 9,
+};
+
+/* tpl_collision.segment flags. */
+enum {
+ TPL_SEGMENT_SKIP_FLOORS = 1u << 0, /* ignore surfaces facing up */
+ TPL_SEGMENT_CAMERA = 1u << 1, /* the camera asks: ignore TPL_SURFACE_CAMERA_PASS */
+};
+
+/* tpl_shape.kind */
+enum {
+ TPL_SHAPE_SPHERE = 1, /* a = centre, radius */
+ TPL_SHAPE_CAPSULE = 2, /* a, b = ends of the core segment, radius */
+ TPL_SHAPE_BOX = 3, /* a = centre, half_extents along the world axes */
+};
+
+/* Pad buttons: the game's pad. */
+enum {
+ TPL_BUTTON_JUMP = 1u << 0,
+};
+
+/* Movement states (Tpl.MoveState). */
+enum {
+ TPL_STATE_IDLE = 0,
+ TPL_STATE_WALK = 1,
+ TPL_STATE_JUMP = 2,
+ TPL_STATE_FALL = 3,
+};
+
+/* Camera styles. */
+enum {
+ TPL_CAMERA_FIRST_PERSON = 1,
+ TPL_CAMERA_THIRD_PERSON = 2,
+ TPL_CAMERA_CHASE = 3,
+ TPL_CAMERA_TOP_DOWN = 4,
+ TPL_CAMERA_FIXED = 5,
+};
+
+/* Event types. 1..255 are the same in every inklib; 256 and up are this lib's own. */
+enum {
+ TPL_EVENT_STATE = 1, /* a = old state, b = new state */
+ TPL_EVENT_LAND = 2,
+ TPL_EVENT_LEAVE_GROUND = 3,
+ TPL_EVENT_SOUND = 4, /* a = sound id; the host plays it */
+};
+
+/* Sound ids (TPL_EVENT_SOUND.a). */
+enum {
+ TPL_SOUND_JUMP = 1,
+};
+
+/* tpl_char_config.flags */
+enum {
+ TPL_CHAR_NO_CAMERA = 1u << 0,
+ TPL_CHAR_NO_INPUT_DELAY = 1u << 1, /* read the pad on the next tick, not the game's delay */
+};
+
+/* ---- small fixed structs (change only with TPL_API_VERSION) ---- */
+
+typedef struct tpl_vec3 { double x, y, z; } tpl_vec3;
+
+typedef struct tpl_hit {
+ tpl_vec3 point; /* contact point */
+ tpl_vec3 normal; /* unit, pointing back at the query */
+ double t; /* 0..1, how far along the query */
+ uint32_t surface; /* TPL_SURFACE_* */
+ int32_t actor; /* host id of what was hit, 0 = level geometry */
+} tpl_hit;
+
+typedef struct tpl_shape {
+ int32_t kind; /* TPL_SHAPE_* */
+ uint32_t reserved;
+ tpl_vec3 a;
+ tpl_vec3 b;
+ double radius;
+ tpl_vec3 half_extents;
+} tpl_shape;
+
+typedef struct tpl_event {
+ int64_t id; /* unique in the world; the same when the tick is simulated again (rollback) */
+ int64_t tick; /* the tick the event belongs to */
+ int32_t type; /* TPL_EVENT_* */
+ int32_t char_id;
+ int32_t a, b;
+ tpl_vec3 position;
+} tpl_event;
+
+/* ---- versioned structs (start with size) ---- */
+
+typedef struct tpl_units_info {
+ uint32_t size;
+ int32_t up_axis;
+ int32_t up_sign;
+ int32_t handedness;
+ int32_t velocity_per_tick;
+ int32_t tick_rate;
+ double metres_per_unit;
+ double radians_per_unit;
+ double tick_seconds; /* TPL_TICK_SECONDS */
+ int32_t input_delay_ticks; /* TPL_INPUT_DELAY_TICKS */
+ int32_t sim_bits; /* TPL_SIM_BITS */
+} tpl_units_info;
+
+/*
+ * Collision. The host answers in the world's unit convention, never reports the
+ * character's own body, and returns 1 and fills *out on a hit, else 0.
+ * user must stay valid until tpl_world_destroy.
+ */
+typedef struct tpl_collision {
+ uint32_t size;
+ void *user;
+ /* First walkable ground straight down from *from, within max_drop. */
+ int32_t (*ground)(void *user, const tpl_vec3 *from, double max_drop, tpl_hit *out);
+ /* First hit on the line a -> b. flags: TPL_SEGMENT_*. */
+ int32_t (*segment)(void *user, const tpl_vec3 *a, const tpl_vec3 *b, uint32_t flags, tpl_hit *out);
+ /* Does *shape touch solid geometry? out->normal points out of the geometry. */
+ int32_t (*overlap)(void *user, const tpl_shape *shape, tpl_hit *out);
+ /* Optional: first hit while moving *shape by *move. Not used by libtpl. */
+ int32_t (*sweep)(void *user, const tpl_shape *shape, const tpl_vec3 *move, tpl_hit *out);
+} tpl_collision;
+
+typedef struct tpl_world_config {
+ uint32_t size;
+ int32_t units; /* TPL_UNITS_* */
+ const char *data_path; /* UTF-8 path to the user's own game data; libtpl needs none (NULL) */
+} tpl_world_config;
+
+typedef struct tpl_char_config {
+ uint32_t size;
+ uint32_t flags; /* TPL_CHAR_* */
+ tpl_vec3 position; /* feet */
+ double yaw;
+ int32_t variant; /* 0 = default */
+ int32_t reserved;
+} tpl_char_config;
+
+typedef struct tpl_input {
+ uint32_t size;
+ uint32_t buttons; /* TPL_BUTTON_* held */
+ float move_x, move_y; /* move stick, -1..1, +y = up; camera-relative like the game */
+ float look_x, look_y; /* look stick, -1..1; +x turns the camera right */
+} tpl_input;
+
+typedef struct tpl_state {
+ uint32_t size;
+ int32_t state; /* TPL_STATE_* */
+ int32_t anim; /* the game's animation id, -1 = none */
+ int32_t grounded; /* 1 on walkable ground */
+ int64_t tick; /* ticks stepped by the world */
+ tpl_vec3 position; /* feet */
+ tpl_vec3 velocity;
+ double yaw; /* facing */
+ uint32_t ground_surface;/* TPL_SURFACE_* of the ground, 0 in the air */
+ uint32_t reserved;
+} tpl_state;
+
+typedef struct tpl_camera {
+ uint32_t size;
+ int32_t style; /* TPL_CAMERA_* */
+ tpl_vec3 position;
+ tpl_vec3 target; /* a point the camera looks at */
+ tpl_vec3 up; /* unit; carries the roll */
+ double fov_y; /* vertical field of view, radians, in both unit modes */
+} tpl_camera;
+
+typedef struct tpl_world tpl_world;
+
+/* Function table, for hosts that load the library at run time. */
+typedef struct tpl_api {
+ uint32_t size;
+ int32_t api_version;
+ const char *prefix; /* "tpl" */
+ int32_t (*api_version_fn)(void);
+ int32_t (*last_error)(char *buf, int32_t size);
+ int32_t (*units)(tpl_units_info *out);
+ tpl_world *(*world_create)(const tpl_world_config *config, const tpl_collision *collision);
+ void (*world_destroy)(tpl_world *world);
+ int32_t (*char_add)(tpl_world *world, const tpl_char_config *config);
+ int32_t (*char_remove)(tpl_world *world, int32_t id);
+ int32_t (*char_input)(tpl_world *world, int32_t id, const tpl_input *input);
+ int32_t (*world_tick)(tpl_world *world, int32_t ticks);
+ int32_t (*char_state)(const tpl_world *world, int32_t id, tpl_state *out);
+ int32_t (*char_camera)(const tpl_world *world, int32_t id, tpl_camera *out);
+ int32_t (*events)(tpl_world *world, tpl_event *out, int32_t max);
+ int64_t (*events_dropped)(const tpl_world *world);
+ int32_t (*state_size)(const tpl_world *world);
+ int32_t (*save_state)(const tpl_world *world, void *buf, int32_t size);
+ int32_t (*load_state)(tpl_world *world, const void *buf, int32_t size);
+ uint64_t (*state_hash)(const tpl_world *world);
+} tpl_api;
+
+/* Returns TPL_API_VERSION of the built library. */
+int32_t tpl_api_version(void);
+/* Copies this thread's last error (UTF-8, NUL-terminated, cut to size). Returns its full
+ length without the NUL, 0 if none. buf may be NULL to ask for the length. */
+int32_t tpl_last_error(char *buf, int32_t size);
+/* Fills the native units. */
+int32_t tpl_units(tpl_units_info *out);
+/* Makes a world. config may be NULL for native units. collision is copied. NULL on error. */
+tpl_world *tpl_world_create(const tpl_world_config *config, const tpl_collision *collision);
+void tpl_world_destroy(tpl_world *world);
+/* Adds the character. Returns its id (1 or more), 0 on error. Ids are never reused. */
+int32_t tpl_char_add(tpl_world *world, const tpl_char_config *config);
+int32_t tpl_char_remove(tpl_world *world, int32_t id);
+/* Sets the pad. It stays until the next call. */
+int32_t tpl_char_input(tpl_world *world, int32_t id, const tpl_input *input);
+/* Steps ticks fixed ticks (0 or more). */
+int32_t tpl_world_tick(tpl_world *world, int32_t ticks);
+int32_t tpl_char_state(const tpl_world *world, int32_t id, tpl_state *out);
+/* Returns 0 if the character was added with TPL_CHAR_NO_CAMERA. */
+int32_t tpl_char_camera(const tpl_world *world, int32_t id, tpl_camera *out);
+/* Moves up to max events out of the buffer, oldest first. Returns how many (0 if empty). */
+int32_t tpl_events(tpl_world *world, tpl_event *out, int32_t max);
+/* Events lost because the buffer (256) was full, since create. */
+int64_t tpl_events_dropped(const tpl_world *world);
+/* Bytes tpl_save_state needs now (changes when characters are added or removed). 0 on error. */
+int32_t tpl_state_size(const tpl_world *world);
+/* Writes a snapshot of the whole world into buf. Returns the bytes written, 0 if size is too small.
+ The event buffer is not included. The snapshot only loads into a world of the same lib build. */
+int32_t tpl_save_state(const tpl_world *world, void *buf, int32_t size);
+/* Puts the world back to a snapshot. Pending events are dropped; ticks simulated again send their
+ events again with the same ids. On error the world is unchanged. */
+int32_t tpl_load_state(tpl_world *world, const void *buf, int32_t size);
+/* 64-bit hash of the snapshot (FNV-1a). Equal on two machines = same world. 0 on error. */
+uint64_t tpl_state_hash(const tpl_world *world);
+/* The function table. Never NULL. */
+const tpl_api *tpl_get_api(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* TPL_H */
diff --git a/TEMPLATE/native/tests/test_tpl.c b/TEMPLATE/native/tests/test_tpl.c
new file mode 100644
index 0000000..d62048e
--- /dev/null
+++ b/TEMPLATE/native/tests/test_tpl.c
@@ -0,0 +1,216 @@
+/* C test of the tpl_* API against a flat floor, in plain C99. */
+#include
+#include
+#include
+#include "tpl.h"
+#include "../flat_floor.h"
+
+static int failures = 0;
+#define CHECK(cond) do { if (!(cond)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); failures++; } } while (0)
+
+static tpl_input pad(uint32_t buttons, float mx, float my)
+{
+ tpl_input in;
+ memset(&in, 0, sizeof in);
+ in.size = sizeof in;
+ in.buttons = buttons;
+ in.move_x = mx;
+ in.move_y = my;
+ return in;
+}
+
+int main(void)
+{
+ char err[256];
+ int native_up = TPL_NATIVE_UP_AXIS, shared_up = 2;
+ tpl_collision col = flat_floor(&native_up);
+ tpl_world_config wc = { sizeof(tpl_world_config), TPL_UNITS_NATIVE, NULL };
+ tpl_char_config cc;
+ tpl_state s;
+ tpl_camera cam;
+ tpl_event ev[64];
+ tpl_input in;
+ tpl_units_info u;
+ int32_t id, n, i, saw_land = 0;
+
+ CHECK(tpl_api_version() == TPL_API_VERSION);
+
+ /* Units say what the header says. */
+ memset(&u, 0, sizeof u);
+ u.size = sizeof u;
+ CHECK(tpl_units(&u) == 1);
+ CHECK(u.size == sizeof u);
+ CHECK(u.up_axis == TPL_NATIVE_UP_AXIS && u.tick_rate == TPL_TICK_RATE);
+ CHECK(u.metres_per_unit == TPL_NATIVE_METRES_PER_UNIT);
+ CHECK(u.tick_seconds == TPL_TICK_SECONDS && u.input_delay_ticks == TPL_INPUT_DELAY_TICKS && u.sim_bits == TPL_SIM_BITS);
+
+ /* Errors are errors, not crashes, and they say why. */
+ CHECK(tpl_world_create(&wc, NULL) == NULL);
+ CHECK(tpl_last_error(NULL, 0) > 0);
+ CHECK(tpl_last_error(err, sizeof err) > 0 && strlen(err) > 0);
+ {
+ tpl_world_config small = wc;
+ small.size = 4;
+ CHECK(tpl_world_create(&small, &col) == NULL);
+ }
+ CHECK(tpl_char_add(NULL, NULL) == 0);
+ CHECK(tpl_world_tick(NULL, 1) == 0);
+
+ tpl_world *w = tpl_world_create(&wc, &col);
+ CHECK(w != NULL);
+ if (!w) return 1;
+
+ memset(&cc, 0, sizeof cc);
+ cc.size = sizeof cc;
+ cc.position.y = 100.0; /* 1 m above the floor */
+ id = tpl_char_add(w, &cc);
+ CHECK(id == 1);
+ CHECK(tpl_char_state(w, 99, &s) == 0);
+
+ /* Falls and lands. */
+ memset(&s, 0, sizeof s);
+ s.size = sizeof s;
+ CHECK(tpl_world_tick(w, 60) == 1);
+ CHECK(tpl_char_state(w, id, &s) == 1);
+ CHECK(s.size == sizeof s);
+ CHECK(s.grounded == 1 && s.state == TPL_STATE_IDLE);
+ CHECK(fabs(s.position.y) < 1e-9);
+ CHECK(s.tick == 60);
+
+ n = tpl_events(w, ev, 64);
+ CHECK(n > 0);
+ for (i = 0; i < n; i++) if (ev[i].type == TPL_EVENT_LAND) saw_land = 1;
+ CHECK(saw_land);
+ CHECK(tpl_events(w, ev, 64) == 0);
+ CHECK(tpl_events_dropped(w) == 0);
+
+ /* Stick up walks the way the camera looks (+X at yaw 0). */
+ in = pad(0, 0.0f, 1.0f);
+ CHECK(tpl_char_input(w, id, &in) == 1);
+ tpl_world_tick(w, 30);
+ tpl_char_state(w, id, &s);
+ CHECK(s.state == TPL_STATE_WALK);
+ CHECK(s.position.x > 100.0);
+
+ /* Jump. */
+ in = pad(TPL_BUTTON_JUMP, 0.0f, 0.0f);
+ tpl_char_input(w, id, &in);
+ tpl_world_tick(w, 1 + TPL_INPUT_DELAY_TICKS); /* the game reads the pad late, like the original */
+ tpl_char_state(w, id, &s);
+ CHECK(s.state == TPL_STATE_JUMP && s.velocity.y > 0.0);
+
+ /* Camera. */
+ memset(&cam, 0, sizeof cam);
+ cam.size = sizeof cam;
+ CHECK(tpl_char_camera(w, id, &cam) == 1);
+ CHECK(cam.style == TPL_CAMERA_THIRD_PERSON);
+ CHECK(cam.fov_y > 0.0 && cam.up.y == 1.0);
+ CHECK(cam.position.x < s.position.x);
+
+ /* Rollback: save, step, load, step the same again: same hash, same events. */
+ {
+ static unsigned char snap[4096];
+ int32_t size = tpl_state_size(w), written;
+ uint64_t h1, h2;
+ tpl_event e1[64], e2[64];
+ int32_t n1, n2;
+ CHECK(size > 0 && size <= (int32_t)sizeof snap);
+ CHECK(tpl_save_state(w, snap, size - 1) == 0);
+ written = tpl_save_state(w, snap, sizeof snap);
+ CHECK(written == size);
+ tpl_events(w, ev, 64); /* empty the buffer */
+ in = pad(0, 0.5f, 1.0f);
+ tpl_char_input(w, id, &in);
+ tpl_world_tick(w, 90);
+ h1 = tpl_state_hash(w);
+ n1 = tpl_events(w, e1, 64);
+ CHECK(tpl_load_state(w, snap, written) == 1);
+ tpl_char_input(w, id, &in);
+ tpl_world_tick(w, 90);
+ h2 = tpl_state_hash(w);
+ n2 = tpl_events(w, e2, 64);
+ CHECK(h1 != 0 && h1 == h2);
+ CHECK(n1 > 0 && n1 == n2);
+ for (i = 0; i < n1 && i < n2; i++) CHECK(e1[i].id == e2[i].id && e1[i].tick == e2[i].tick && e1[i].type == e2[i].type);
+ snap[0] ^= 0xFF; /* a broken snapshot is refused */
+ CHECK(tpl_load_state(w, snap, written) == 0);
+ CHECK(tpl_state_hash(w) == h2);
+ }
+
+ /* Removed characters are gone; ids are not reused. */
+ CHECK(tpl_char_remove(w, id) == 1);
+ CHECK(tpl_char_state(w, id, &s) == 0);
+ CHECK(tpl_char_add(w, &cc) == 2);
+ tpl_world_destroy(w);
+
+ /* Shared units: the same character in metres, Z up. */
+ {
+ tpl_world_config sc = { sizeof(tpl_world_config), TPL_UNITS_SHARED, NULL };
+ tpl_collision zcol = flat_floor(&shared_up);
+ tpl_world *ws = tpl_world_create(&sc, &zcol);
+ CHECK(ws != NULL);
+ if (ws) {
+ memset(&cc, 0, sizeof cc);
+ cc.size = sizeof cc;
+ cc.position.z = 1.0;
+ id = tpl_char_add(ws, &cc);
+ in = pad(0, 0.0f, 1.0f);
+ tpl_char_input(ws, id, &in);
+ tpl_world_tick(ws, 120);
+ memset(&s, 0, sizeof s);
+ s.size = sizeof s;
+ tpl_char_state(ws, id, &s);
+ CHECK(s.grounded == 1 && fabs(s.position.z) < 1e-9);
+ CHECK(s.position.x > 1.0 && fabs(s.position.y) < 1e-9);
+ CHECK(fabs(s.velocity.x - 3.0) < 1e-9); /* 5 cm per tick at 60 Hz = 3 m/s */
+ memset(&cam, 0, sizeof cam);
+ cam.size = sizeof cam;
+ CHECK(tpl_char_camera(ws, id, &cam) == 1 && cam.up.z == 1.0);
+ tpl_world_destroy(ws);
+ }
+ }
+
+ /* The function table. */
+ {
+ const tpl_api *api = tpl_get_api();
+ CHECK(api != NULL && api == tpl_get_api());
+ CHECK(api->size == sizeof(tpl_api));
+ CHECK(api->api_version == TPL_API_VERSION && strcmp(api->prefix, "tpl") == 0);
+ w = api->world_create(&wc, &col);
+ CHECK(w != NULL);
+ memset(&cc, 0, sizeof cc);
+ cc.size = sizeof cc;
+ id = api->char_add(w, &cc);
+ CHECK(api->world_tick(w, 10) == 1);
+ memset(&s, 0, sizeof s);
+ s.size = sizeof s;
+ CHECK(api->char_state(w, id, &s) == 1 && s.tick == 10);
+ CHECK(api->state_hash(w) == tpl_state_hash(w) && api->state_size(w) == tpl_state_size(w));
+ api->world_destroy(w);
+ }
+
+ /* Same bits on every machine: the inputs of tests/Tpl.Core.Tests/Replays/walk-and-jump.replay
+ must end in the hash stored there. If you record that replay again, update this number. */
+ {
+ static const struct { int ticks; uint32_t buttons; float mx, my; } rows[] = {
+ { 10, 0, 0.0f, 0.0f }, { 30, 0, 0.0f, 1.0f }, { 1, TPL_BUTTON_JUMP, 0.0f, 1.0f },
+ { 40, 0, 0.0f, 1.0f }, { 30, 0, 1.0f, 0.0f },
+ };
+ w = tpl_world_create(&wc, &col);
+ memset(&cc, 0, sizeof cc);
+ cc.size = sizeof cc;
+ id = tpl_char_add(w, &cc);
+ for (i = 0; i < (int32_t)(sizeof rows / sizeof rows[0]); i++) {
+ in = pad(rows[i].buttons, rows[i].mx, rows[i].my);
+ tpl_char_input(w, id, &in);
+ tpl_world_tick(w, rows[i].ticks);
+ }
+ if (tpl_state_hash(w) != 0x196007041dc1b243ull)
+ printf("state hash 0x%016llx\n", (unsigned long long)tpl_state_hash(w));
+ CHECK(tpl_state_hash(w) == 0x196007041dc1b243ull);
+ tpl_world_destroy(w);
+ }
+
+ if (failures == 0) printf("test_tpl: all checks passed\n");
+ return failures == 0 ? 0 : 1;
+}
diff --git a/TEMPLATE/native/tpl.def b/TEMPLATE/native/tpl.def
new file mode 100644
index 0000000..96f8492
--- /dev/null
+++ b/TEMPLATE/native/tpl.def
@@ -0,0 +1,22 @@
+; Exports of libtpl.dll. Used on Windows to make an import library for C hosts.
+; HeaderTests checks that this list matches the functions in tpl.h.
+LIBRARY libtpl
+EXPORTS
+ tpl_api_version
+ tpl_last_error
+ tpl_units
+ tpl_world_create
+ tpl_world_destroy
+ tpl_char_add
+ tpl_char_remove
+ tpl_char_input
+ tpl_world_tick
+ tpl_char_state
+ tpl_char_camera
+ tpl_events
+ tpl_events_dropped
+ tpl_state_size
+ tpl_save_state
+ tpl_load_state
+ tpl_state_hash
+ tpl_get_api
diff --git a/TEMPLATE/rename.sh b/TEMPLATE/rename.sh
new file mode 100755
index 0000000..9f7a4eb
--- /dev/null
+++ b/TEMPLATE/rename.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# Turns this template into a new inklib: ./rename.sh
+# prefix: the C prefix, lower case (e.g. pz). Name: the C# name (e.g. Pz).
+# Replaces tpl / TPL / Tpl everywhere, in file contents and in file names.
+# (No English word contains "tpl", so a plain replace is safe.) Run once, in a fresh copy.
+set -eu
+[ $# -eq 2 ] || { echo "usage: $0 "; exit 1; }
+p=$1; N=$2
+P=$(echo "$p" | tr '[:lower:]' '[:upper:]')
+echo "$p" | grep -Eq '^[a-z][a-z0-9]*$' || { echo "prefix: lower case letters and digits"; exit 1; }
+echo "$N" | grep -Eq '^[A-Z][A-Za-z0-9]*$' || { echo "Name: a C# identifier starting with a capital"; exit 1; }
+cd "$(dirname "$0")"
+rm -rf native/build src/*/bin src/*/obj tests/*/bin tests/*/obj
+
+find . -type f ! -path './.git/*' ! -name rename.sh | while read -r f; do
+ sed -i.bak -e "s/tpl/${p}/g; s/TPL/${P}/g; s/Tpl/${N}/g" "$f"
+ rm -f "$f.bak"
+done
+find . -depth \( -name '*tpl*' -o -name '*Tpl*' \) ! -path './.git/*' | while read -r f; do
+ mv "$f" "$(dirname "$f")/$(basename "$f" | sed "s/tpl/${p}/g; s/Tpl/${N}/g")"
+done
+echo "Renamed to ${p}_ / ${N}. Next: README.md, Units.cs, Tuning.cs, Character.cs, the header enums, Docs/."
diff --git a/TEMPLATE/src/Tpl.Core/Character.cs b/TEMPLATE/src/Tpl.Core/Character.cs
new file mode 100644
index 0000000..f96631a
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Character.cs
@@ -0,0 +1,258 @@
+using System;
+
+namespace Tpl
+{
+ /// Movement states. Values match TPL_STATE_* in tpl.h. A real lib lists its game's states.
+ public enum MoveState
+ {
+ Idle = 0,
+ Walk = 1,
+ Jump = 2,
+ Fall = 3,
+ }
+
+ /// Camera styles (SPEC.md section 7). Values match TPL_CAMERA_*.
+ public enum CameraStyle
+ {
+ FirstPerson = 1,
+ ThirdPerson = 2,
+ Chase = 3,
+ TopDown = 4,
+ Fixed = 5,
+ }
+
+ ///
+ /// The template's character: walks camera-relative, jumps, falls, steps up small rises, and has a
+ /// third-person camera. Everything here is in native units (cm, ticks, radians, Y up).
+ /// A real lib replaces this file with the game's rules.
+ ///
+ public sealed class Character
+ {
+ static readonly Vec3 Up = new Vec3(0, 1, 0);
+
+ readonly Tuning _t;
+ readonly ICollisionWorld _col;
+ readonly PadInput[] _delayed; // inputs set but not yet read by the game (ring)
+ int _delayedHead;
+ bool _jumpWasDown;
+
+ public int Id { get; }
+ public bool HasCamera { get; }
+ public int Variant { get; }
+ public Vec3 Position { get; private set; }
+ /// cm per tick.
+ public Vec3 Velocity { get; private set; }
+ /// Facing, radians around +Y, 0 = +X.
+ public double Yaw { get; private set; }
+ public MoveState State { get; private set; }
+ public bool Grounded { get; private set; }
+ public SurfaceFlags GroundSurface { get; private set; }
+ /// The game's animation id. The template has none, so it reports the state.
+ public int Anim => (int)State;
+ /// The pad the host set last. The game reads it ticks later.
+ public PadInput Input { get; set; }
+ /// The game's input delay for this character (0 if turned off).
+ public int InputDelayTicks => _delayed.Length;
+
+ /// Camera heading, radians around +Y.
+ public double CameraYaw { get; private set; }
+ public Vec3 CameraPosition { get; private set; }
+ public Vec3 CameraTarget { get; private set; }
+
+ Character(int id, Tuning tuning, ICollisionWorld collision, bool camera, int variant, int inputDelay)
+ {
+ _delayed = new PadInput[inputDelay];
+ Id = id;
+ _t = tuning;
+ _col = collision;
+ HasCamera = camera;
+ Variant = variant;
+ }
+
+ internal Character(int id, Tuning tuning, ICollisionWorld collision, Vec3 feet, double yaw, bool camera, int variant, int inputDelay)
+ : this(id, tuning, collision, camera, variant, inputDelay)
+ {
+ Position = feet;
+ Yaw = yaw;
+ CameraYaw = yaw;
+ State = MoveState.Fall;
+ if (_col.Ground(feet + Up * _t.StepHeight, _t.StepHeight * 2, out Hit g) && Math.Abs(g.Point.Y - feet.Y) <= _t.StepHeight)
+ {
+ Position = new Vec3(feet.X, g.Point.Y, feet.Z);
+ Grounded = true;
+ GroundSurface = g.Surface;
+ State = MoveState.Idle;
+ }
+ UpdateCamera();
+ }
+
+ const int InputBytes = 5 * 4;
+ internal const int FixedSnapshotBytes = 7 * 4 + 2 * 8 + 4 * 24 + InputBytes;
+
+ /// Bytes this character takes in a snapshot.
+ internal int SnapshotBytes => FixedSnapshotBytes + _delayed.Length * InputBytes;
+
+ static void SaveInput(ref SnapshotWriter w, PadInput p)
+ {
+ w.U32((uint)p.Buttons);
+ w.F32(p.MoveX); w.F32(p.MoveY); w.F32(p.LookX); w.F32(p.LookY);
+ }
+
+ static PadInput LoadInput(ref SnapshotReader r) =>
+ new PadInput { Buttons = (Buttons)r.U32(), MoveX = r.F32(), MoveY = r.F32(), LookX = r.F32(), LookY = r.F32() };
+
+ /// Writes everything that shapes later ticks. Keep in step with .
+ internal void Save(ref SnapshotWriter w)
+ {
+ w.I32(Id);
+ w.I32(Variant);
+ w.I32(_delayed.Length);
+ w.I32(_delayedHead);
+ w.U32((HasCamera ? 1u : 0) | (Grounded ? 2u : 0) | (_jumpWasDown ? 4u : 0));
+ w.I32((int)State);
+ w.U32((uint)GroundSurface);
+ w.V3(Position);
+ w.V3(Velocity);
+ w.F64(Yaw);
+ w.F64(CameraYaw);
+ w.V3(CameraPosition);
+ w.V3(CameraTarget);
+ SaveInput(ref w, Input);
+ foreach (PadInput p in _delayed) SaveInput(ref w, p);
+ }
+
+ internal static Character Load(ref SnapshotReader r, Tuning tuning, ICollisionWorld collision)
+ {
+ int id = r.I32(), variant = r.I32(), delay = r.I32(), head = r.I32();
+ if (delay < 0 || delay > Tuning.MaxInputDelayTicks || head < 0 || (head >= delay && head != 0))
+ throw new FormatException("bad input delay in snapshot");
+ uint flags = r.U32();
+ var c = new Character(id, tuning, collision, (flags & 1) != 0, variant, delay)
+ {
+ _delayedHead = head,
+ Grounded = (flags & 2) != 0,
+ _jumpWasDown = (flags & 4) != 0,
+ };
+ c.State = (MoveState)r.I32();
+ c.GroundSurface = (SurfaceFlags)r.U32();
+ c.Position = r.V3();
+ c.Velocity = r.V3();
+ c.Yaw = r.F64();
+ c.CameraYaw = r.F64();
+ c.CameraPosition = r.V3();
+ c.CameraTarget = r.V3();
+ c.Input = LoadInput(ref r);
+ for (int i = 0; i < delay; i++) c._delayed[i] = LoadInput(ref r);
+ return c;
+ }
+
+ static Vec3 Forward(double yaw) => new Vec3(DetMath.Cos(yaw), 0, -DetMath.Sin(yaw));
+
+ internal void Step(long tick, Action emit)
+ {
+ // The game reads the pad InputDelayTicks ticks after the host sets it.
+ PadInput pad = Input;
+ if (_delayed.Length > 0)
+ {
+ pad = _delayed[_delayedHead];
+ _delayed[_delayedHead] = Input;
+ _delayedHead = (_delayedHead + 1) % _delayed.Length;
+ }
+ MoveState before = State;
+
+ CameraYaw = Units.WrapAngle(CameraYaw - pad.LookX * _t.CameraTurnSpeed);
+
+ // Camera-relative stick: up = the way the camera looks.
+ double sx = pad.MoveX, sy = pad.MoveY;
+ double tilt = DetMath.Sqrt(sx * sx + sy * sy);
+ if (tilt < _t.StickDeadzone) { sx = 0; sy = 0; tilt = 0; }
+ else if (tilt > 1) { sx /= tilt; sy /= tilt; tilt = 1; }
+ Vec3 fwd = Forward(CameraYaw);
+ Vec3 right = new Vec3(DetMath.Sin(CameraYaw), 0, DetMath.Cos(CameraYaw));
+ Vec3 dir = fwd * sy + right * sx;
+ Vec3 v = Velocity;
+ if (tilt > 0)
+ {
+ double len = dir.Length;
+ Yaw = DetMath.Atan2(-dir.Z, dir.X);
+ v.X = dir.X / len * _t.WalkSpeed * tilt;
+ v.Z = dir.Z / len * _t.WalkSpeed * tilt;
+ }
+ else { v.X = 0; v.Z = 0; }
+
+ bool jumpDown = (pad.Buttons & Buttons.Jump) != 0;
+ bool jumpPressed = jumpDown && !_jumpWasDown;
+ _jumpWasDown = jumpDown;
+
+ if (Grounded && jumpPressed)
+ {
+ v.Y = _t.JumpSpeed;
+ Grounded = false;
+ emit(new Event { Type = (int)EventType.LeaveGround, CharId = Id, Tick = tick, Position = Position });
+ emit(new Event { Type = (int)EventType.Sound, CharId = Id, Tick = tick, A = SoundIds.Jump, Position = Position });
+ }
+ else if (!Grounded)
+ {
+ v.Y -= _t.Gravity;
+ }
+
+ // Horizontal: blocked if the body above step height would touch something.
+ Vec3 next = Position;
+ if (v.X != 0 || v.Z != 0)
+ {
+ Vec3 moved = new Vec3(Position.X + v.X, Position.Y, Position.Z + v.Z);
+ double half = (_t.BodyHeight - _t.StepHeight) / 2;
+ var body = new Shape
+ {
+ Kind = (int)ShapeKind.Box,
+ A = moved + Up * (_t.StepHeight + half),
+ HalfExtents = new Vec3(_t.BodyRadius, half, _t.BodyRadius),
+ };
+ if (_col.Overlap(body, out _)) { v.X = 0; v.Z = 0; }
+ else next = moved;
+ }
+
+ // Vertical, then ground.
+ next.Y += v.Y;
+ bool wasGrounded = Grounded;
+ if (v.Y <= 0)
+ {
+ double top = Math.Max(Position.Y, next.Y) + _t.StepHeight;
+ double lowest = next.Y - (wasGrounded ? _t.StepHeight : 0);
+ if (_col.Ground(new Vec3(next.X, top, next.Z), top - lowest, out Hit g) && g.Point.Y >= lowest)
+ {
+ next.Y = g.Point.Y;
+ v.Y = 0;
+ Grounded = true;
+ GroundSurface = g.Surface;
+ if (!wasGrounded) emit(new Event { Type = (int)EventType.Land, CharId = Id, Tick = tick, Position = next });
+ }
+ else if (wasGrounded)
+ {
+ Grounded = false;
+ GroundSurface = SurfaceFlags.None;
+ emit(new Event { Type = (int)EventType.LeaveGround, CharId = Id, Tick = tick, Position = next });
+ }
+ }
+
+ Position = next;
+ Velocity = v;
+ State = Grounded ? (tilt > 0 ? MoveState.Walk : MoveState.Idle) : (v.Y > 0 ? MoveState.Jump : MoveState.Fall);
+ if (State != before)
+ emit(new Event { Type = (int)EventType.State, CharId = Id, Tick = tick, A = (int)before, B = (int)State, Position = Position });
+
+ UpdateCamera();
+ }
+
+ void UpdateCamera()
+ {
+ if (!HasCamera) return;
+ Vec3 target = Position + Up * (_t.BodyHeight * 0.5);
+ Vec3 wanted = Position + Up * _t.CameraHeight - Forward(CameraYaw) * _t.CameraDistance;
+ if (_col.Segment(target, wanted, SegmentFlags.Camera, out Hit h))
+ wanted = target + (wanted - target) * Math.Max(0, h.T - 0.05);
+ CameraTarget = target;
+ CameraPosition = wanted;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Collision.cs b/TEMPLATE/src/Tpl.Core/Collision.cs
new file mode 100644
index 0000000..ed2d562
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Collision.cs
@@ -0,0 +1,133 @@
+using System;
+
+namespace Tpl
+{
+ ///
+ /// Surface flags on every hit. Bits 0..15 are the same in every inklib (SPEC.md section 4);
+ /// bits 16..31 are this lib's own. Values match TPL_SURFACE_* in tpl.h.
+ ///
+ [Flags]
+ public enum SurfaceFlags : uint
+ {
+ None = 0,
+ NoCollision = 1u << 0,
+ Water = 1u << 1,
+ Hurt = 1u << 2,
+ Death = 1u << 3,
+ Slide = 1u << 4,
+ Ledge = 1u << 5,
+ Climb = 1u << 6,
+ Hang = 1u << 7,
+ Bounce = 1u << 8,
+ CameraPass = 1u << 9,
+ }
+
+ /// Flags for . Values match TPL_SEGMENT_*.
+ [Flags]
+ public enum SegmentFlags : uint
+ {
+ None = 0,
+ /// Ignore surfaces that face up (floors).
+ SkipFloors = 1u << 0,
+ /// The camera is asking: ignore surfaces.
+ Camera = 1u << 1,
+ }
+
+ /// Shape kinds. Values match TPL_SHAPE_*.
+ public enum ShapeKind
+ {
+ Sphere = 1,
+ Capsule = 2,
+ /// Axis-aligned box: centre , half size .
+ Box = 3,
+ }
+
+ /// A query shape. Same layout as tpl_shape.
+ public struct Shape
+ {
+ public int Kind;
+ public uint Reserved;
+ /// Sphere and box: centre. Capsule: one end of the core segment.
+ public Vec3 A;
+ /// Capsule: other end of the core segment. Unused otherwise.
+ public Vec3 B;
+ public double Radius;
+ public Vec3 HalfExtents;
+ }
+
+ /// One answer from the host. Same layout as tpl_hit.
+ public struct Hit
+ {
+ /// Contact point.
+ public Vec3 Point;
+ /// Unit normal at the contact, pointing back at the query.
+ public Vec3 Normal;
+ /// 0..1, how far along the query the contact is.
+ public double T;
+ public SurfaceFlags Surface;
+ /// Host id of what was hit, 0 for level geometry.
+ public int Actor;
+ }
+
+ ///
+ /// The host's collision world, in the world's unit convention. This is the only way Core sees
+ /// geometry. Each method returns true and fills hit on a hit.
+ /// The host never reports the character's own body.
+ ///
+ public interface ICollisionWorld
+ {
+ /// First walkable ground straight down from within .
+ bool Ground(Vec3 from, double maxDrop, out Hit hit);
+
+ /// First hit on the line from to .
+ bool Segment(Vec3 a, Vec3 b, SegmentFlags flags, out Hit hit);
+
+ /// Does touch solid geometry? Normal points out of the geometry.
+ bool Overlap(in Shape shape, out Hit hit);
+ }
+
+ ///
+ /// Wraps a host collision world that speaks the shared convention, so the simulation can ask in
+ /// native units. In native mode it is not used.
+ ///
+ sealed class ConvertingCollision : ICollisionWorld
+ {
+ readonly ICollisionWorld _host;
+ readonly UnitMode _mode;
+
+ public ConvertingCollision(ICollisionWorld host, UnitMode mode) { _host = host; _mode = mode; }
+
+ public bool Ground(Vec3 from, double maxDrop, out Hit hit)
+ {
+ bool ok = _host.Ground(Units.PositionOut(from, _mode), Units.LengthOut(maxDrop, _mode), out hit);
+ if (ok) hit = HitIn(hit);
+ return ok;
+ }
+
+ public bool Segment(Vec3 a, Vec3 b, SegmentFlags flags, out Hit hit)
+ {
+ bool ok = _host.Segment(Units.PositionOut(a, _mode), Units.PositionOut(b, _mode), flags, out hit);
+ if (ok) hit = HitIn(hit);
+ return ok;
+ }
+
+ public bool Overlap(in Shape shape, out Hit hit)
+ {
+ Shape s = shape;
+ s.A = Units.PositionOut(shape.A, _mode);
+ s.B = Units.PositionOut(shape.B, _mode);
+ s.Radius = Units.LengthOut(shape.Radius, _mode);
+ s.HalfExtents = Units.ExtentsOut(shape.HalfExtents, _mode);
+ bool ok = _host.Overlap(s, out hit);
+ if (ok) hit = HitIn(hit);
+ return ok;
+ }
+
+ Hit HitIn(Hit h)
+ {
+ h.Point = Units.PositionIn(h.Point, _mode);
+ h.Normal = Units.DirectionIn(h.Normal, _mode);
+ return h;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/DetMath.cs b/TEMPLATE/src/Tpl.Core/DetMath.cs
new file mode 100644
index 0000000..6171511
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/DetMath.cs
@@ -0,0 +1,77 @@
+using System;
+
+namespace Tpl
+{
+ ///
+ /// Maths that gives the same bits on every machine (SPEC.md section 5). The simulation calls these
+ /// instead of Math.Sin/Cos/Atan2/Pow/..., whose results come from the platform and can differ in
+ /// the last bit between operating systems, CPUs and runtimes.
+ /// Only +, -, *, / and Math.Round are used: IEEE 754 makes those exact the same everywhere.
+ /// Accuracy is about 1e-15, plenty for a game; what matters is that it is identical everywhere.
+ /// Our own code (series expansions); no source copied.
+ ///
+ public static class DetMath
+ {
+ public const double Pi = 3.141592653589793;
+ public const double HalfPi = 1.5707963267948966;
+ public const double TwoPi = 6.283185307179586;
+
+ ///
+ /// Square root. IEEE 754 requires sqrt to be correctly rounded, so Math.Sqrt gives the same bits on
+ /// every conforming machine. It goes through here so the rule lives in one place.
+ ///
+ public static double Sqrt(double x) => Math.Sqrt(x);
+
+ /// Sine of an angle in radians.
+ public static double Sin(double x)
+ {
+ x -= TwoPi * Math.Round(x / TwoPi); // -pi..pi
+ if (x > HalfPi) x = Pi - x; // -pi/2..pi/2, same sine
+ else if (x < -HalfPi) x = -Pi - x;
+ double x2 = x * x;
+ // Taylor series to x^19; the next term is below 3e-16 on this range.
+ double p = 1.0 / 121645100408832000.0; // 1/19!
+ p = p * -x2 + 1.0 / 355687428096000.0; // 1/17!
+ p = p * -x2 + 1.0 / 1307674368000.0; // 1/15!
+ p = p * -x2 + 1.0 / 6227020800.0; // 1/13!
+ p = p * -x2 + 1.0 / 39916800.0; // 1/11!
+ p = p * -x2 + 1.0 / 362880.0; // 1/9!
+ p = p * -x2 + 1.0 / 5040.0; // 1/7!
+ p = p * -x2 + 1.0 / 120.0; // 1/5!
+ p = p * -x2 + 1.0 / 6.0; // 1/3!
+ p = p * -x2 + 1.0;
+ return x * p;
+ }
+
+ /// Cosine of an angle in radians.
+ public static double Cos(double x) => Sin(x + HalfPi);
+
+ /// Arc tangent, -pi/2..pi/2.
+ public static double Atan(double x)
+ {
+ if (double.IsNaN(x)) return x;
+ bool negative = x < 0;
+ if (negative) x = -x;
+ bool inverted = x > 1;
+ if (inverted) x = 1 / x;
+ // atan(x) = 2 atan(x / (1 + sqrt(1 + x^2))), twice: x drops below tan(pi/16) = 0.199.
+ x /= 1 + Sqrt(1 + x * x);
+ x /= 1 + Sqrt(1 + x * x);
+ double x2 = x * x, p = 0;
+ for (int k = 21; k >= 1; k -= 2) p = 1.0 / k - x2 * p; // 1 - x^2/3 + x^4/5 - ... to x^20/21
+ double r = 4 * x * p;
+ if (inverted) r = HalfPi - r;
+ return negative ? -r : r;
+ }
+
+ /// Angle of the vector (x, y) in radians, -pi..pi, like Math.Atan2.
+ public static double Atan2(double y, double x)
+ {
+ if (x > 0) return Atan(y / x);
+ if (x < 0) return y >= 0 ? Atan(y / x) + Pi : Atan(y / x) - Pi;
+ if (y > 0) return HalfPi;
+ if (y < 0) return -HalfPi;
+ return 0;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Events.cs b/TEMPLATE/src/Tpl.Core/Events.cs
new file mode 100644
index 0000000..8359aa7
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Events.cs
@@ -0,0 +1,35 @@
+namespace Tpl
+{
+ /// Event types. 1..255 are the same in every inklib; 256 and up are this lib's own.
+ public enum EventType
+ {
+ /// A = old state, B = new state.
+ State = 1,
+ Land = 2,
+ LeaveGround = 3,
+ /// A = the game's sound id. The host plays it.
+ Sound = 4,
+ }
+
+ /// Sound ids of this lib (the game's own ids in a real lib).
+ public static class SoundIds
+ {
+ public const int Jump = 1;
+ }
+
+ /// One event. Same layout as tpl_event. Position is in the world's unit convention.
+ public struct Event
+ {
+ ///
+ /// Unique in the world: Tick * 65536 + its place among the events of that tick. Simulating the
+ /// same tick again with the same inputs gives the same id (SPEC.md section 6).
+ ///
+ public long Id;
+ /// The tick the event belongs to.
+ public long Tick;
+ public int Type;
+ public int CharId;
+ public int A, B;
+ public Vec3 Position;
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Input.cs b/TEMPLATE/src/Tpl.Core/Input.cs
new file mode 100644
index 0000000..a62ec03
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Input.cs
@@ -0,0 +1,20 @@
+namespace Tpl
+{
+ /// The game's pad buttons. Values match TPL_BUTTON_* in tpl.h. A real lib lists its game's pad.
+ [System.Flags]
+ public enum Buttons : uint
+ {
+ None = 0,
+ Jump = 1u << 0,
+ }
+
+ /// One pad, as the player holds it. Same fields as tpl_input (without size).
+ public struct PadInput
+ {
+ public Buttons Buttons;
+ /// Move stick, -1..1 each, +y = up (away from the player).
+ public float MoveX, MoveY;
+ /// Look (camera) stick, -1..1 each.
+ public float LookX, LookY;
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Provenance.cs b/TEMPLATE/src/Tpl.Core/Provenance.cs
new file mode 100644
index 0000000..a86f7c2
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Provenance.cs
@@ -0,0 +1,20 @@
+using System;
+
+namespace Tpl
+{
+ /// The number was measured or read from a named source. Say which, specifically.
+ [AttributeUsage(AttributeTargets.Field)]
+ public sealed class VerifiedAttribute : Attribute
+ {
+ public string Source { get; }
+ public VerifiedAttribute(string source) { Source = source; }
+ }
+
+ /// The number is a placeholder or a guess. Say why it was picked. List it in Docs/MEASURE.md.
+ [AttributeUsage(AttributeTargets.Field)]
+ public sealed class UnverifiedAttribute : Attribute
+ {
+ public string Reason { get; }
+ public UnverifiedAttribute(string reason) { Reason = reason; }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Snapshot.cs b/TEMPLATE/src/Tpl.Core/Snapshot.cs
new file mode 100644
index 0000000..a14b29e
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Snapshot.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Buffers.Binary;
+
+namespace Tpl
+{
+ ///
+ /// Byte layout of a world snapshot (SPEC.md section 6), little-endian, the same on every machine:
+ /// header (magic "INKS", format, tuning hash, tick, next id, character count), then each character.
+ /// Doubles are stored as their raw bits, so a load restores the exact numbers.
+ ///
+ static class Snapshot
+ {
+ public const uint Magic = 0x534B4E49; // "INKS"
+ public const uint Format = 1;
+ public const int HeaderBytes = 32;
+
+ /// FNV-1a, 64 bit. Used for the state hash and the tuning hash.
+ public static ulong Fnv1a(ReadOnlySpan data, ulong hash = 14695981039346656037UL)
+ {
+ foreach (byte b in data) { hash ^= b; hash *= 1099511628211UL; }
+ return hash;
+ }
+ }
+
+ /// Writes little-endian values into a span. No allocations.
+ ref struct SnapshotWriter
+ {
+ readonly Span _b;
+ public int Length;
+
+ public SnapshotWriter(Span buffer) { _b = buffer; Length = 0; }
+
+ public void I32(int v) { BinaryPrimitives.WriteInt32LittleEndian(_b.Slice(Length), v); Length += 4; }
+ public void U32(uint v) { BinaryPrimitives.WriteUInt32LittleEndian(_b.Slice(Length), v); Length += 4; }
+ public void I64(long v) { BinaryPrimitives.WriteInt64LittleEndian(_b.Slice(Length), v); Length += 8; }
+ public void U64(ulong v) { BinaryPrimitives.WriteUInt64LittleEndian(_b.Slice(Length), v); Length += 8; }
+ public void F32(float v) => I32(BitConverter.SingleToInt32Bits(v));
+ public void F64(double v) => I64(BitConverter.DoubleToInt64Bits(v));
+ public void V3(Vec3 v) { F64(v.X); F64(v.Y); F64(v.Z); }
+ }
+
+ /// Reads what wrote. The caller checks the length first.
+ ref struct SnapshotReader
+ {
+ readonly ReadOnlySpan _b;
+ int _p;
+
+ public SnapshotReader(ReadOnlySpan buffer) { _b = buffer; _p = 0; }
+
+ public int Position => _p;
+
+ public int I32() { int v = BinaryPrimitives.ReadInt32LittleEndian(_b.Slice(_p)); _p += 4; return v; }
+ public uint U32() { uint v = BinaryPrimitives.ReadUInt32LittleEndian(_b.Slice(_p)); _p += 4; return v; }
+ public long I64() { long v = BinaryPrimitives.ReadInt64LittleEndian(_b.Slice(_p)); _p += 8; return v; }
+ public ulong U64() { ulong v = BinaryPrimitives.ReadUInt64LittleEndian(_b.Slice(_p)); _p += 8; return v; }
+ public float F32() => BitConverter.Int32BitsToSingle(I32());
+ public double F64() => BitConverter.Int64BitsToDouble(I64());
+ public Vec3 V3() => new Vec3(F64(), F64(), F64());
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Tpl.Core.csproj b/TEMPLATE/src/Tpl.Core/Tpl.Core.csproj
new file mode 100644
index 0000000..a379d73
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Tpl.Core.csproj
@@ -0,0 +1,15 @@
+
+
+
+
+ netstandard2.1
+ 9.0
+ enable
+ Tpl
+ Tpl.Core
+ true
+ true
+ CS1591
+
+
+
diff --git a/TEMPLATE/src/Tpl.Core/Tuning.cs b/TEMPLATE/src/Tpl.Core/Tuning.cs
new file mode 100644
index 0000000..3b4ac93
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Tuning.cs
@@ -0,0 +1,69 @@
+using System.Reflection;
+
+namespace Tpl
+{
+ ///
+ /// Every gameplay number of the character. Native units: centimetres, ticks, radians, Y up
+ /// (see ). Each field has exactly one of [Verified] or [Unverified]
+ /// (ProvenanceTests checks), and every [Unverified] field is listed in Docs/MEASURE.md.
+ /// The template's numbers are placeholders: a real lib replaces them with the game's.
+ ///
+ public sealed class Tuning
+ {
+ [Unverified("Template placeholder. Real libs: the game's logic rate (MEASURE.md M0).")]
+ public int TickRate = 60; // ticks per real second the host calls (pacing)
+
+ [Unverified("Template placeholder. Real libs: the game's real simulated step, measured (Rayman 3 PC: 0.016 s at 60 Hz).")]
+ public double TickSeconds = 1.0 / 60; // seconds of game time one tick simulates
+
+ [Unverified("Template placeholder. Real libs: the game's input delay, measured (Rayman 3 PC: 1 frame).")]
+ public int InputDelayTicks = 1; // ticks between setting the pad and the game reading it, 0..8
+
+ [Unverified("Template placeholder (3 m/s).")]
+ public double WalkSpeed = 5; // cm per tick at full stick
+
+ [Unverified("Template placeholder.")]
+ public double StickDeadzone = 0.2; // 0..1 stick length treated as zero
+
+ [Unverified("Template placeholder (9 m/s^2).")]
+ public double Gravity = 0.25; // cm per tick per tick
+
+ [Unverified("Template placeholder (4.8 m/s).")]
+ public double JumpSpeed = 8; // cm per tick, upwards at take-off
+
+ [Unverified("Template placeholder.")]
+ public double StepHeight = 30; // cm, tallest rise walked up without a jump
+
+ [Unverified("Template placeholder.")]
+ public double BodyRadius = 40; // cm
+
+ [Unverified("Template placeholder.")]
+ public double BodyHeight = 180; // cm, feet to top
+
+ [Unverified("Template placeholder.")]
+ public double CameraDistance = 400; // cm behind the character
+
+ [Unverified("Template placeholder.")]
+ public double CameraHeight = 150; // cm above the feet
+
+ [Unverified("Template placeholder.")]
+ public double CameraTurnSpeed = 0.05; // radians per tick at full look stick
+
+ [Unverified("Template placeholder (about 57 degrees).")]
+ public double CameraFovY = 1.0; // radians, vertical
+
+ public const int MaxInputDelayTicks = 8;
+
+ /// Returns null if the tuning can be used, else the reason it cannot.
+ public string? Validate()
+ {
+ if (TickRate <= 0) return "TickRate must be > 0";
+ if (!(TickSeconds > 0)) return "TickSeconds must be > 0";
+ if (InputDelayTicks < 0 || InputDelayTicks > MaxInputDelayTicks) return "InputDelayTicks must be 0.." + MaxInputDelayTicks;
+ foreach (FieldInfo f in typeof(Tuning).GetFields(BindingFlags.Public | BindingFlags.Instance))
+ if (f.FieldType == typeof(double) && !((double)f.GetValue(this)! >= 0))
+ return f.Name + " must be >= 0";
+ return null;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Units.cs b/TEMPLATE/src/Tpl.Core/Units.cs
new file mode 100644
index 0000000..603772b
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Units.cs
@@ -0,0 +1,102 @@
+using System;
+
+namespace Tpl
+{
+ /// Which unit convention a world talks to its host in (SPEC.md section 3).
+ public enum UnitMode
+ {
+ /// The game's own numbers, unchanged.
+ Native = 0,
+ /// Metres, seconds, radians, Z up, right-handed, yaw 0 = +X towards +Y.
+ Shared = 1,
+ }
+
+ ///
+ /// The native units of this lib and the conversion to the shared convention.
+ /// The simulation only ever sees native numbers; this class sits at the API boundary.
+ ///
+ /// Template native units (an example; replace with your game's):
+ /// 1 unit = 1 cm, angles in radians, Y up, right-handed, velocity in units per tick.
+ /// Native yaw turns around +Y; yaw 0 faces +X, forward = (cos yaw, 0, -sin yaw).
+ /// Mapping: shared (x, y, z) = native (x, -z, y) times .
+ /// With that mapping native yaw and shared yaw are the same angle.
+ ///
+ /// Keep the constants equal to the TPL_NATIVE_* macros in tpl.h (HeaderTests checks).
+ ///
+ public static class Units
+ {
+ public const double MetresPerUnit = 0.01;
+ public const double RadiansPerUnit = 1.0;
+ /// 0 = X, 1 = Y, 2 = Z.
+ public const int UpAxis = 1;
+ public const int UpSign = 1;
+ /// +1 right-handed, -1 left-handed.
+ public const int Handedness = 1;
+ /// 1 if native velocity is units per tick, 0 if units per second.
+ public const int VelocityPerTick = 1;
+ ///
+ /// The real type the simulation computes in, as the game did: 32 = float32, 64 = double,
+ /// 0 = integer or fixed point. The template uses double. Same as TPL_SIM_BITS.
+ ///
+ public const int SimBits = 64;
+
+ // "0.0 - z" instead of "-z" so a zero stays +0 (no "-0" in logs and replays).
+
+ /// Native position to the convention .
+ public static Vec3 PositionOut(Vec3 n, UnitMode mode) =>
+ mode == UnitMode.Native ? n : new Vec3(n.X, 0.0 - n.Z, n.Y) * MetresPerUnit;
+
+ /// Position in the convention to native.
+ public static Vec3 PositionIn(Vec3 s, UnitMode mode) =>
+ mode == UnitMode.Native ? s : Scale(new Vec3(s.X, s.Z, 0.0 - s.Y));
+
+ /// Unit direction or normal, native to . No scaling.
+ public static Vec3 DirectionOut(Vec3 n, UnitMode mode) =>
+ mode == UnitMode.Native ? n : new Vec3(n.X, 0.0 - n.Z, n.Y);
+
+ public static Vec3 DirectionIn(Vec3 s, UnitMode mode) =>
+ mode == UnitMode.Native ? s : new Vec3(s.X, s.Z, 0.0 - s.Y);
+
+ ///
+ /// Native velocity to (shared: metres per second of game time).
+ /// is the simulated step (Tuning.TickSeconds), not 1 / TickRate.
+ ///
+ public static Vec3 VelocityOut(Vec3 n, UnitMode mode, double tickSeconds)
+ {
+ if (mode == UnitMode.Native) return n;
+ Vec3 p = PositionOut(n, mode);
+ return VelocityPerTick == 1 ? new Vec3(p.X / tickSeconds, p.Y / tickSeconds, p.Z / tickSeconds) : p;
+ }
+
+ /// Native length (distance, radius) to .
+ public static double LengthOut(double n, UnitMode mode) => mode == UnitMode.Native ? n : n * MetresPerUnit;
+
+ public static double LengthIn(double s, UnitMode mode) => mode == UnitMode.Native ? s : s / MetresPerUnit;
+
+ /// Native angle (yaw) to (shared: radians).
+ public static double AngleOut(double n, UnitMode mode) => mode == UnitMode.Native ? n : n * RadiansPerUnit;
+
+ public static double AngleIn(double s, UnitMode mode) => mode == UnitMode.Native ? s : s / RadiansPerUnit;
+
+ ///
+ /// Box half extents are lengths along axes; swapping axes swaps them, signs do not matter.
+ ///
+ public static Vec3 ExtentsOut(Vec3 n, UnitMode mode) =>
+ mode == UnitMode.Native ? n : new Vec3(n.X, n.Z, n.Y) * MetresPerUnit;
+
+ public static Vec3 ExtentsIn(Vec3 s, UnitMode mode) =>
+ mode == UnitMode.Native ? s : Scale(new Vec3(s.X, s.Z, s.Y));
+
+ // Divide (not multiply by 1 / MetresPerUnit): 0.01 is inexact, and dividing by it rounds back
+ // to the native number in far more cases. Integer-unit games round to the nearest integer here.
+ static Vec3 Scale(Vec3 s) => new Vec3(s.X / MetresPerUnit, s.Y / MetresPerUnit, s.Z / MetresPerUnit);
+
+ /// Wraps an angle into -pi..pi. Integer-angle games wrap with a mask instead.
+ public static double WrapAngle(double a)
+ {
+ while (a > DetMath.Pi) a -= 2 * DetMath.Pi;
+ while (a < -DetMath.Pi) a += 2 * DetMath.Pi;
+ return a;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/Vec3.cs b/TEMPLATE/src/Tpl.Core/Vec3.cs
new file mode 100644
index 0000000..2958b7c
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/Vec3.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Tpl
+{
+ /// Three doubles. Same layout as tpl_vec3 in tpl.h.
+ public struct Vec3 : IEquatable
+ {
+ public double X, Y, Z;
+
+ public Vec3(double x, double y, double z) { X = x; Y = y; Z = z; }
+
+ public static readonly Vec3 Zero = new Vec3(0, 0, 0);
+
+ public static Vec3 operator +(Vec3 a, Vec3 b) => new Vec3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ public static Vec3 operator -(Vec3 a, Vec3 b) => new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
+ public static Vec3 operator *(Vec3 a, double s) => new Vec3(a.X * s, a.Y * s, a.Z * s);
+
+ public double Length => DetMath.Sqrt(X * X + Y * Y + Z * Z);
+
+ public bool Equals(Vec3 o) => X == o.X && Y == o.Y && Z == o.Z;
+ public override bool Equals(object? obj) => obj is Vec3 v && Equals(v);
+ public override int GetHashCode() => X.GetHashCode() ^ (Y.GetHashCode() << 7) ^ (Z.GetHashCode() << 14);
+ public override string ToString() => $"({X}, {Y}, {Z})";
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Core/World.cs b/TEMPLATE/src/Tpl.Core/World.cs
new file mode 100644
index 0000000..0175486
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Core/World.cs
@@ -0,0 +1,273 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace Tpl
+{
+ /// A character's state in the world's unit convention. Mirrors tpl_char_state.
+ public struct CharacterState
+ {
+ public MoveState State;
+ public int Anim;
+ public bool Grounded;
+ public long Tick;
+ public Vec3 Position;
+ public Vec3 Velocity;
+ public double Yaw;
+ public SurfaceFlags GroundSurface;
+ }
+
+ /// The character's camera in the world's unit convention. Mirrors tpl_camera.
+ public struct CameraView
+ {
+ public CameraStyle Style;
+ public Vec3 Position, Target, Up;
+ /// Vertical field of view, radians, in both unit modes.
+ public double FovY;
+ }
+
+ ///
+ /// One simulation: characters, the tick counter and the event buffer. This is what tpl_world is.
+ /// Positions and collision answers cross this class in ; inside, all is native.
+ /// Not thread-safe. Worlds share nothing.
+ ///
+ public sealed class World
+ {
+ /// Events kept until the host polls them. More are dropped and counted.
+ public const int EventCapacity = 256;
+
+ readonly ICollisionWorld _col;
+ readonly List _chars = new List();
+ readonly Queue _events = new Queue();
+ readonly Action _emit;
+ readonly ulong _tuningHash;
+ int _nextId = 1;
+ int _eventInTick;
+ byte[] _hashScratch = Array.Empty();
+
+ public Tuning Tuning { get; }
+ public UnitMode Mode { get; }
+ /// Ticks stepped since the world was made.
+ public long Tick { get; private set; }
+ public long EventsDropped { get; private set; }
+
+ /// The character's numbers. Copied by reference; do not change it later.
+ /// The host's collision, speaking .
+ /// The unit convention of every number that crosses this class.
+ public World(Tuning tuning, ICollisionWorld collision, UnitMode mode)
+ {
+ string? bad = tuning.Validate();
+ if (bad != null) throw new ArgumentException(bad, nameof(tuning));
+ Tuning = tuning;
+ Mode = mode;
+ _col = mode == UnitMode.Native ? collision : new ConvertingCollision(collision, mode);
+ _emit = Push;
+ _tuningHash = HashTuning(tuning);
+ }
+
+ void Push(Event e)
+ {
+ e.Id = e.Tick * 65536 + _eventInTick++;
+ if (_events.Count >= EventCapacity) { EventsDropped++; return; }
+ _events.Enqueue(e);
+ }
+
+ /// A snapshot only loads into a world with the same tuning.
+ static ulong HashTuning(Tuning t)
+ {
+ ulong h = Snapshot.Fnv1a(ReadOnlySpan.Empty);
+ Span b = stackalloc byte[8];
+ foreach (FieldInfo f in typeof(Tuning).GetFields(BindingFlags.Public | BindingFlags.Instance))
+ {
+ object v = f.GetValue(t)!;
+ long bits = v is double d ? BitConverter.DoubleToInt64Bits(d) : Convert.ToInt64(v);
+ System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian(b, bits);
+ h = Snapshot.Fnv1a(b, h);
+ }
+ return h;
+ }
+
+ ///
+ /// Adds a character with its feet at . Returns its id (1 or more).
+ /// false turns off the game's input delay (it is on by default:
+ /// closeness to the original comes first).
+ ///
+ public int AddCharacter(Vec3 position, double yaw, bool camera = true, int variant = 0, bool inputDelay = true)
+ {
+ var c = new Character(_nextId++, Tuning, _col, Units.PositionIn(position, Mode), Units.AngleIn(yaw, Mode),
+ camera, variant, inputDelay ? Tuning.InputDelayTicks : 0);
+ _chars.Add(c);
+ return c.Id;
+ }
+
+ public bool RemoveCharacter(int id)
+ {
+ Character? c = Find(id);
+ return c != null && _chars.Remove(c);
+ }
+
+ ///
+ /// Sets the pad. Sticks are quantised to steps of 1/127 here, like a pad's bytes, so the
+ /// simulation depends only on round(stick * 127) (SPEC.md section 6: inputs sent over a network).
+ ///
+ public bool SetInput(int id, PadInput input)
+ {
+ Character? c = Find(id);
+ if (c == null) return false;
+ input.MoveX = Quantise(input.MoveX);
+ input.MoveY = Quantise(input.MoveY);
+ input.LookX = Quantise(input.LookX);
+ input.LookY = Quantise(input.LookY);
+ c.Input = input;
+ return true;
+ }
+
+ /// Stick to the nearest k / 127, k = -127..127. NaN becomes 0.
+ public static float Quantise(float v)
+ {
+ if (float.IsNaN(v)) return 0;
+ double k = Math.Round(Math.Max(-1.0, Math.Min(1.0, (double)v)) * 127.0);
+ return (float)(k / 127.0);
+ }
+
+ /// Steps fixed ticks. Characters step in the order they were added.
+ public void Step(int ticks)
+ {
+ for (int i = 0; i < ticks; i++)
+ {
+ Tick++;
+ _eventInTick = 0;
+ foreach (Character c in _chars) c.Step(Tick, _emit);
+ }
+ }
+
+ public bool GetState(int id, out CharacterState state)
+ {
+ Character? c = Find(id);
+ state = default;
+ if (c == null) return false;
+ state = new CharacterState
+ {
+ State = c.State,
+ Anim = c.Anim,
+ Grounded = c.Grounded,
+ Tick = Tick,
+ Position = Units.PositionOut(c.Position, Mode),
+ Velocity = Units.VelocityOut(c.Velocity, Mode, Tuning.TickSeconds),
+ Yaw = Units.AngleOut(c.Yaw, Mode),
+ GroundSurface = c.GroundSurface,
+ };
+ return true;
+ }
+
+ /// False if the character does not exist or was added without a camera.
+ public bool GetCamera(int id, out CameraView view)
+ {
+ Character? c = Find(id);
+ view = default;
+ if (c == null || !c.HasCamera) return false;
+ view = new CameraView
+ {
+ Style = CameraStyle.ThirdPerson,
+ Position = Units.PositionOut(c.CameraPosition, Mode),
+ Target = Units.PositionOut(c.CameraTarget, Mode),
+ Up = Units.DirectionOut(new Vec3(0, 1, 0), Mode),
+ FovY = Tuning.CameraFovY,
+ };
+ return true;
+ }
+
+ /// Moves up to output.Length events out of the buffer, oldest first. Returns how many.
+ public int DrainEvents(Span output)
+ {
+ int n = 0;
+ while (n < output.Length && _events.Count > 0)
+ {
+ Event e = _events.Dequeue();
+ e.Position = Units.PositionOut(e.Position, Mode);
+ output[n++] = e;
+ }
+ return n;
+ }
+
+ // ---- rollback support (SPEC.md section 6). Costs nothing unless called.
+
+ /// Bytes needs for the world as it is now.
+ public int StateSize
+ {
+ get
+ {
+ int n = Snapshot.HeaderBytes;
+ foreach (Character c in _chars) n += c.SnapshotBytes;
+ return n;
+ }
+ }
+
+ ///
+ /// Writes a complete snapshot: tick, ids, every character with its input and camera.
+ /// Returns the bytes written, or 0 if is smaller than .
+ /// The event buffer is not part of it. No allocations.
+ ///
+ public int SaveState(Span buffer)
+ {
+ if (buffer.Length < StateSize) return 0;
+ var w = new SnapshotWriter(buffer);
+ w.U32(Snapshot.Magic);
+ w.U32(Snapshot.Format);
+ w.U64(_tuningHash);
+ w.I64(Tick);
+ w.I32(_nextId);
+ w.I32(_chars.Count);
+ foreach (Character c in _chars) c.Save(ref w);
+ return w.Length;
+ }
+
+ ///
+ /// Puts the world back to a snapshot from of a world with the same tuning.
+ /// Pending events are thrown away; ticks simulated again send their events again, with the same ids.
+ /// Returns null on success, else why the snapshot was refused (the world is then unchanged).
+ ///
+ public string? LoadState(ReadOnlySpan data)
+ {
+ if (data.Length < Snapshot.HeaderBytes) return "snapshot too short";
+ var r = new SnapshotReader(data);
+ if (r.U32() != Snapshot.Magic) return "not a tpl snapshot";
+ if (r.U32() != Snapshot.Format) return "snapshot format not supported";
+ if (r.U64() != _tuningHash) return "snapshot was made with other tuning";
+ long tick = r.I64();
+ int nextId = r.I32(), count = r.I32();
+ if (count < 0 || data.Length < Snapshot.HeaderBytes + (long)count * Character.FixedSnapshotBytes) return "snapshot size does not match its character count";
+ var chars = new List(count);
+ try
+ {
+ for (int i = 0; i < count; i++) chars.Add(Character.Load(ref r, Tuning, _col));
+ }
+ catch (Exception e) when (e is ArgumentOutOfRangeException || e is FormatException)
+ {
+ return "snapshot is cut short or broken";
+ }
+ if (r.Position != data.Length) return "snapshot has extra bytes";
+ Tick = tick;
+ _nextId = nextId;
+ _chars.Clear();
+ _chars.AddRange(chars);
+ _events.Clear();
+ return null;
+ }
+
+ /// FNV-1a 64 of the snapshot. Equal on two machines = same world, bit for bit.
+ public ulong StateHash()
+ {
+ int size = StateSize;
+ if (_hashScratch.Length < size) _hashScratch = new byte[size];
+ int n = SaveState(_hashScratch);
+ return Snapshot.Fnv1a(new ReadOnlySpan(_hashScratch, 0, n));
+ }
+
+ Character? Find(int id)
+ {
+ foreach (Character c in _chars) if (c.Id == id) return c;
+ return null;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Native/Exports.cs b/TEMPLATE/src/Tpl.Native/Exports.cs
new file mode 100644
index 0000000..d04ba18
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Native/Exports.cs
@@ -0,0 +1,283 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace Tpl.Native
+{
+ /// The tpl_* exports. Every function catches everything: an exception must never reach C.
+ static unsafe class Exports
+ {
+ public const int ApiVersion = 1;
+
+ [ThreadStatic] static string? _lastError;
+
+ static int Fail(string message)
+ {
+ _lastError = message;
+ return 0;
+ }
+
+ static World? Get(void* w) => w == null ? null : (World?)GCHandle.FromIntPtr((IntPtr)w).Target;
+
+ ///
+ /// Reads a versioned struct: min(size, sizeof(T)) bytes, the rest zero.
+ /// In API version 1 every struct is at its first version, so the smallest size is sizeof(T).
+ ///
+ static bool ReadIn(void* p, out T value, string name) where T : unmanaged
+ {
+ value = default;
+ if (p == null) { Fail(name + " is NULL"); return false; }
+ uint size = *(uint*)p;
+ if (size < (uint)sizeof(T)) { Fail($"{name}.size is {size}, expected at least {sizeof(T)}"); return false; }
+ fixed (T* v = &value) Buffer.MemoryCopy(p, v, sizeof(T), Math.Min(size, (uint)sizeof(T)));
+ return true;
+ }
+
+ /// Writes a versioned struct: min(size, sizeof(T)) bytes, leaving the host's size field alone.
+ static bool WriteOut(void* p, T value, string name) where T : unmanaged
+ {
+ if (p == null) return Fail(name + " is NULL") != 0;
+ uint size = *(uint*)p;
+ if (size < (uint)sizeof(T)) return Fail($"{name}.size is {size}, expected at least {sizeof(T)}") != 0;
+ *(uint*)&value = size;
+ Buffer.MemoryCopy(&value, p, size, sizeof(T));
+ return true;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_api_version", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int ApiVersionFn() => ApiVersion;
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_last_error", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int LastError(byte* buf, int size)
+ {
+ string e = _lastError ?? "";
+ byte[] bytes = Encoding.UTF8.GetBytes(e);
+ if (buf != null && size > 0)
+ {
+ int n = Math.Min(bytes.Length, size - 1);
+ while (n > 0 && n < bytes.Length && (bytes[n] & 0xC0) == 0x80) n--; // do not cut a UTF-8 sequence
+ Marshal.Copy(bytes, 0, (IntPtr)buf, n);
+ buf[n] = 0;
+ }
+ return bytes.Length;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_units", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int UnitsFn(CUnitsInfo* output)
+ {
+ var u = new CUnitsInfo
+ {
+ UpAxis = Units.UpAxis, UpSign = Units.UpSign, Handedness = Units.Handedness,
+ VelocityPerTick = Units.VelocityPerTick, TickRate = new Tuning().TickRate,
+ MetresPerUnit = Units.MetresPerUnit, RadiansPerUnit = Units.RadiansPerUnit,
+ TickSeconds = new Tuning().TickSeconds, InputDelayTicks = new Tuning().InputDelayTicks, SimBits = Units.SimBits,
+ };
+ return WriteOut(output, u, "out") ? 1 : 0;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_world_create", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static void* WorldCreate(CWorldConfig* config, CCollision* collision)
+ {
+ try
+ {
+ CWorldConfig cfg = default;
+ if (config != null && !ReadIn(config, out cfg, "config")) return null;
+ if (cfg.Units != (int)UnitMode.Native && cfg.Units != (int)UnitMode.Shared) { Fail("config.units must be TPL_UNITS_NATIVE or TPL_UNITS_SHARED"); return null; }
+ if (!ReadIn(collision, out CCollision col, "collision")) return null;
+ if (col.Ground == null || col.Segment == null || col.Overlap == null) { Fail("collision needs ground, segment and overlap"); return null; }
+ var world = new World(new Tuning(), new CallbackCollision(col), (UnitMode)cfg.Units);
+ return (void*)GCHandle.ToIntPtr(GCHandle.Alloc(world));
+ }
+ catch (Exception e) { Fail(e.Message); return null; }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_world_destroy", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static void WorldDestroy(void* w)
+ {
+ if (w != null) GCHandle.FromIntPtr((IntPtr)w).Free();
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_char_add", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int CharAdd(void* w, CCharConfig* config)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (!ReadIn(config, out CCharConfig c, "config")) return 0;
+ return world.AddCharacter(c.Position, c.Yaw, camera: (c.Flags & 1u) == 0, variant: c.Variant, inputDelay: (c.Flags & 2u) == 0);
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_char_remove", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int CharRemove(void* w, int id)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ return world.RemoveCharacter(id) ? 1 : Fail($"no character {id}");
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_char_input", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int CharInput(void* w, int id, CInput* input)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (!ReadIn(input, out CInput i, "input")) return 0;
+ var pad = new PadInput { Buttons = (Buttons)i.Buttons, MoveX = i.MoveX, MoveY = i.MoveY, LookX = i.LookX, LookY = i.LookY };
+ return world.SetInput(id, pad) ? 1 : Fail($"no character {id}");
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_world_tick", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int WorldTick(void* w, int ticks)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (ticks < 0) return Fail("ticks must be >= 0");
+ world.Step(ticks);
+ return 1;
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_char_state", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int CharState(void* w, int id, CCharState* output)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (!world.GetState(id, out CharacterState s)) return Fail($"no character {id}");
+ var c = new CCharState
+ {
+ State = (int)s.State, Anim = s.Anim, Grounded = s.Grounded ? 1 : 0, Tick = s.Tick,
+ Position = s.Position, Velocity = s.Velocity, Yaw = s.Yaw, GroundSurface = (uint)s.GroundSurface,
+ };
+ return WriteOut(output, c, "out") ? 1 : 0;
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_char_camera", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int CharCamera(void* w, int id, CCamera* output)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (!world.GetCamera(id, out CameraView v)) return Fail($"no camera for character {id}");
+ var c = new CCamera { Style = (int)v.Style, Position = v.Position, Target = v.Target, Up = v.Up, FovY = v.FovY };
+ return WriteOut(output, c, "out") ? 1 : 0;
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_events", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int Events(void* w, Event* output, int max)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (output == null || max <= 0) return 0;
+ return world.DrainEvents(new Span(output, max));
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_events_dropped", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static long EventsDropped(void* w)
+ {
+ World? world = Get(w);
+ return world == null ? 0 : world.EventsDropped;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_state_size", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int StateSize(void* w)
+ {
+ World? world = Get(w);
+ return world == null ? Fail("world is NULL") : world.StateSize;
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_save_state", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int SaveState(void* w, void* buf, int size)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (buf == null || size < world.StateSize) return Fail($"buffer needs {world.StateSize} bytes");
+ return world.SaveState(new Span(buf, size));
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_load_state", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static int LoadState(void* w, void* buf, int size)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) return Fail("world is NULL");
+ if (buf == null || size <= 0) return Fail("buf is NULL or empty");
+ string? error = world.LoadState(new ReadOnlySpan(buf, size));
+ return error == null ? 1 : Fail(error);
+ }
+ catch (Exception e) { return Fail(e.Message); }
+ }
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_state_hash", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static ulong StateHash(void* w)
+ {
+ try
+ {
+ World? world = Get(w);
+ if (world == null) { Fail("world is NULL"); return 0; }
+ return world.StateHash();
+ }
+ catch (Exception e) { Fail(e.Message); return 0; }
+ }
+
+ static CApi* _api;
+
+ [UnmanagedCallersOnly(EntryPoint = "tpl_get_api", CallConvs = new[] { typeof(CallConvCdecl) })]
+ static CApi* GetApi()
+ {
+ if (_api != null) return _api;
+ var api = (CApi*)NativeMemory.AllocZeroed((nuint)sizeof(CApi));
+ api->Size = (uint)sizeof(CApi);
+ api->ApiVersion = ApiVersion;
+ api->Prefix = (byte*)Marshal.StringToCoTaskMemUTF8("tpl");
+ api->ApiVersionFn = &ApiVersionFn;
+ api->LastError = &LastError;
+ api->Units = &UnitsFn;
+ api->WorldCreate = &WorldCreate;
+ api->WorldDestroy = &WorldDestroy;
+ api->CharAdd = &CharAdd;
+ api->CharRemove = &CharRemove;
+ api->CharInput = &CharInput;
+ api->WorldTick = &WorldTick;
+ api->CharState = &CharState;
+ api->CharCamera = &CharCamera;
+ api->Events = &Events;
+ api->EventsDropped = &EventsDropped;
+ api->StateSize = &StateSize;
+ api->SaveState = &SaveState;
+ api->LoadState = &LoadState;
+ api->StateHash = &StateHash;
+ _api = api; // two threads racing here leak one small table; both are valid
+ return _api;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Native/Interop.cs b/TEMPLATE/src/Tpl.Native/Interop.cs
new file mode 100644
index 0000000..464ec1d
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Native/Interop.cs
@@ -0,0 +1,129 @@
+using System.Runtime.InteropServices;
+
+namespace Tpl.Native
+{
+ // Versioned structs from native/include/tpl.h. The small fixed structs (tpl_vec3, tpl_hit,
+ // tpl_shape, tpl_event) are Core's Vec3, Hit, Shape and Event, which have the same layout.
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct CUnitsInfo
+ {
+ public uint Size;
+ public int UpAxis, UpSign, Handedness, VelocityPerTick, TickRate;
+ public double MetresPerUnit, RadiansPerUnit;
+ public double TickSeconds;
+ public int InputDelayTicks, SimBits;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ unsafe struct CCollision
+ {
+ public uint Size;
+ public void* User;
+ public delegate* unmanaged[Cdecl] Ground;
+ public delegate* unmanaged[Cdecl] Segment;
+ public delegate* unmanaged[Cdecl] Overlap;
+ public delegate* unmanaged[Cdecl] Sweep;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ unsafe struct CWorldConfig
+ {
+ public uint Size;
+ public int Units;
+ public byte* DataPath;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct CCharConfig
+ {
+ public uint Size, Flags;
+ public Vec3 Position;
+ public double Yaw;
+ public int Variant, Reserved;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct CInput
+ {
+ public uint Size, Buttons;
+ public float MoveX, MoveY, LookX, LookY;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct CCharState
+ {
+ public uint Size;
+ public int State, Anim, Grounded;
+ public long Tick;
+ public Vec3 Position, Velocity;
+ public double Yaw;
+ public uint GroundSurface, Reserved;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct CCamera
+ {
+ public uint Size;
+ public int Style;
+ public Vec3 Position, Target, Up;
+ public double FovY;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ unsafe struct CApi
+ {
+ public uint Size;
+ public int ApiVersion;
+ public byte* Prefix;
+ public delegate* unmanaged[Cdecl] ApiVersionFn;
+ public delegate* unmanaged[Cdecl] LastError;
+ public delegate* unmanaged[Cdecl] Units;
+ public delegate* unmanaged[Cdecl] WorldCreate;
+ public delegate* unmanaged[Cdecl] WorldDestroy;
+ public delegate* unmanaged[Cdecl] CharAdd;
+ public delegate* unmanaged[Cdecl] CharRemove;
+ public delegate* unmanaged[Cdecl] CharInput;
+ public delegate* unmanaged[Cdecl] WorldTick;
+ public delegate* unmanaged[Cdecl] CharState;
+ public delegate* unmanaged[Cdecl] CharCamera;
+ public delegate* unmanaged[Cdecl] Events;
+ public delegate* unmanaged[Cdecl] EventsDropped;
+ public delegate* unmanaged[Cdecl] StateSize;
+ public delegate* unmanaged[Cdecl] SaveState;
+ public delegate* unmanaged[Cdecl] LoadState;
+ public delegate* unmanaged[Cdecl] StateHash;
+ }
+
+ /// Forwards Core's collision questions to the host's C callbacks.
+ sealed unsafe class CallbackCollision : ICollisionWorld
+ {
+ readonly CCollision _c;
+ public CallbackCollision(CCollision c) { _c = c; }
+
+ public bool Ground(Vec3 from, double maxDrop, out Hit hit)
+ {
+ Hit h = default;
+ bool ok = _c.Ground(_c.User, &from, maxDrop, &h) != 0;
+ hit = h;
+ return ok;
+ }
+
+ public bool Segment(Vec3 a, Vec3 b, SegmentFlags flags, out Hit hit)
+ {
+ Hit h = default;
+ bool ok = _c.Segment(_c.User, &a, &b, (uint)flags, &h) != 0;
+ hit = h;
+ return ok;
+ }
+
+ public bool Overlap(in Shape shape, out Hit hit)
+ {
+ Shape s = shape;
+ Hit h = default;
+ bool ok = _c.Overlap(_c.User, &s, &h) != 0;
+ hit = h;
+ return ok;
+ }
+ }
+}
diff --git a/TEMPLATE/src/Tpl.Native/Tpl.Native.csproj b/TEMPLATE/src/Tpl.Native/Tpl.Native.csproj
new file mode 100644
index 0000000..add1d6f
--- /dev/null
+++ b/TEMPLATE/src/Tpl.Native/Tpl.Native.csproj
@@ -0,0 +1,20 @@
+
+
+
+
+ net8.0
+ enable
+ true
+ Tpl.Native
+ libtpl
+ true
+ Shared
+ true
+ true
+
+
+
+
+
+
+
diff --git a/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs
new file mode 100644
index 0000000..24c6a8c
--- /dev/null
+++ b/TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs
@@ -0,0 +1,66 @@
+using System;
+using System.IO;
+using System.Text.RegularExpressions;
+using Xunit;
+
+namespace Tpl.Tests
+{
+ ///
+ /// Same bits on every machine (SPEC.md section 5). The stored hashes in Replays/*.replay are the real
+ /// check: CI runs them on Linux x64, Windows x64 and macOS arm64.
+ ///
+ public class DeterminismTests
+ {
+ [Theory]
+ [InlineData(0.0)] [InlineData(0.5)] [InlineData(-1.2)] [InlineData(3.0)] [InlineData(100.25)] [InlineData(-1e4)]
+ public void DetMathIsCloseToMath(double x)
+ {
+ Assert.True(Math.Abs(DetMath.Sin(x) - Math.Sin(x)) < 1e-12, "sin");
+ Assert.True(Math.Abs(DetMath.Cos(x) - Math.Cos(x)) < 1e-12, "cos");
+ Assert.True(Math.Abs(DetMath.Atan(x) - Math.Atan(x)) < 1e-14, "atan");
+ Assert.True(Math.Abs(DetMath.Atan2(x, 0.7) - Math.Atan2(x, 0.7)) < 1e-14, "atan2");
+ Assert.True(Math.Abs(DetMath.Atan2(0.3, -x) - Math.Atan2(0.3, -x)) < 1e-14, "atan2 left");
+ }
+
+ /// Golden bits: these must be the same on every machine. Changing DetMath moves them.
+ [Fact]
+ public void DetMathGoldenBits()
+ {
+ double sum = 0;
+ for (int i = -500; i <= 500; i++)
+ {
+ double x = i * 0.0173;
+ sum += DetMath.Sin(x) + DetMath.Cos(x) * 0.5 + DetMath.Atan2(x, 1.5 - x) * 0.25;
+ }
+ Assert.Equal(Golden, "0x" + BitConverter.DoubleToInt64Bits(sum).ToString("x16"));
+ }
+
+ const string Golden = "0x40698e7e61f762cf";
+
+ /// Platform maths and other sources of difference must not appear in Core (outside DetMath.cs).
+ [Fact]
+ public void CoreUsesNoPlatformMaths()
+ {
+ var forbidden = new Regex(@"\bMath\.(Sin|Cos|Tan|Asin|Acos|Atan|Atan2|Sinh|Cosh|Tanh|Pow|Exp|Log|Log10|Log2|Sqrt|Cbrt|FusedMultiplyAdd|ScaleB)\b"
+ + @"|\bMathF\.|System\.Numerics|System\.Runtime\.Intrinsics|\bRandom\b|DateTime|Stopwatch|Environment\.TickCount|\bHashCode\.|Parallel\.|\bThread\b|\bTask\b");
+ string dir = Path.Combine(Repo.Root(), "src", "Tpl.Core");
+ foreach (string file in Directory.GetFiles(dir, "*.cs"))
+ {
+ if (Path.GetFileName(file) == "DetMath.cs") continue;
+ string[] lines = File.ReadAllLines(file);
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string code = Regex.Replace(lines[i], @"//.*$", "");
+ Assert.False(forbidden.IsMatch(code), $"{Path.GetFileName(file)}:{i + 1} uses something that differs between machines: {lines[i].Trim()}");
+ }
+ }
+ }
+
+ [Fact]
+ public void EveryReplayStoresAHash()
+ {
+ foreach (string f in Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "Replays"), "*.replay"))
+ Assert.True(Replay.Load(f).Hash != null, Path.GetFileName(f) + " has no hash: line");
+ }
+ }
+}
diff --git a/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs
new file mode 100644
index 0000000..e13b547
--- /dev/null
+++ b/TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs
@@ -0,0 +1,102 @@
+using System;
+using System.Globalization;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Xunit;
+
+namespace Tpl.Tests
+{
+ /// Keeps native/include/tpl.h, native/tpl.def and Core in step.
+ public class HeaderTests
+ {
+ static string Header() => Repo.Read("native", "include", "tpl.h");
+
+ static string Snake(string name) => Regex.Replace(name, "(?<=[a-z])([A-Z])", "_$1").ToUpperInvariant();
+
+ static string Macro(string name)
+ {
+ Match m = Regex.Match(Header(), $@"#define\s+{name}\s+(\S+)");
+ Assert.True(m.Success, name + " not found in tpl.h");
+ return m.Groups[1].Value;
+ }
+
+ [Fact]
+ public void NativeUnitsMatchCore()
+ {
+ Assert.Equal(Units.MetresPerUnit, double.Parse(Macro("TPL_NATIVE_METRES_PER_UNIT"), CultureInfo.InvariantCulture));
+ Assert.Equal(Units.RadiansPerUnit, double.Parse(Macro("TPL_NATIVE_RADIANS_PER_UNIT"), CultureInfo.InvariantCulture));
+ Assert.Equal(Units.UpAxis, int.Parse(Macro("TPL_NATIVE_UP_AXIS")));
+ Assert.Equal(Units.UpSign, int.Parse(Macro("TPL_NATIVE_UP_SIGN")));
+ Assert.Equal(Units.Handedness, int.Parse(Macro("TPL_NATIVE_HANDEDNESS")));
+ Assert.Equal(Units.VelocityPerTick, int.Parse(Macro("TPL_NATIVE_VELOCITY_PER_TICK")));
+ Assert.Equal(new Tuning().TickRate, int.Parse(Macro("TPL_TICK_RATE")));
+ 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")));
+ }
+
+ [Fact]
+ public void EnumsMatchCore()
+ {
+ string h = Header();
+ foreach (MoveState s in Enum.GetValues(typeof(MoveState)))
+ Assert.Matches($@"TPL_STATE_{Snake(s.ToString())}\s*=\s*{(int)s},", h);
+ foreach (CameraStyle s in Enum.GetValues(typeof(CameraStyle)))
+ Assert.Matches($@"TPL_CAMERA_{Snake(s.ToString())}\s*=\s*{(int)s},", h);
+ foreach (EventType e in Enum.GetValues(typeof(EventType)))
+ Assert.Matches($@"TPL_EVENT_{Snake(e.ToString())}\s*=\s*{(int)e},", h);
+ foreach (ShapeKind k in Enum.GetValues(typeof(ShapeKind)))
+ Assert.Matches($@"TPL_SHAPE_{Snake(k.ToString())}\s*=\s*{(int)k},", h);
+ }
+
+ [Fact]
+ public void FlagsMatchCore()
+ {
+ string h = Header();
+ void Check(string prefix, Type flags)
+ {
+ foreach (object f in Enum.GetValues(flags))
+ {
+ ulong v = Convert.ToUInt64(f);
+ if (v == 0) continue;
+ int bit = (int)Math.Log2(v);
+ Assert.Matches($@"{prefix}{Snake(f.ToString()!)}\s*= 1u << {bit},", h);
+ }
+ }
+ Check("TPL_SURFACE_", typeof(SurfaceFlags));
+ Check("TPL_SEGMENT_", typeof(SegmentFlags));
+ Check("TPL_BUTTON_", typeof(Buttons));
+ }
+
+ /// The standard surface bits 0..9 have the same names in every inklib (SPEC.md section 4).
+ [Fact]
+ public void StandardSurfaceBits()
+ {
+ string[] names = { "NO_COLLISION", "WATER", "HURT", "DEATH", "SLIDE", "LEDGE", "CLIMB", "HANG", "BOUNCE", "CAMERA_PASS" };
+ for (int bit = 0; bit < names.Length; bit++)
+ Assert.Matches($@"TPL_SURFACE_{names[bit]}\s*= 1u << {bit},", Header());
+ }
+
+ /// native/tpl.def (Windows import library) exports exactly the functions in tpl.h.
+ [Fact]
+ public void DefFileMatchesHeader()
+ {
+ var inHeader = Regex.Matches(Header(), @"^[A-Za-z_][\w \*]*?\b(tpl_\w+)\(", RegexOptions.Multiline)
+ .Select(m => m.Groups[1].Value).OrderBy(n => n, StringComparer.Ordinal).ToArray();
+ var inDef = Regex.Matches(Repo.Read("native", "tpl.def"), @"^\s+(tpl_\w+)\s*$", RegexOptions.Multiline)
+ .Select(m => m.Groups[1].Value).OrderBy(n => n, StringComparer.Ordinal).ToArray();
+ Assert.NotEmpty(inHeader);
+ Assert.Equal(inHeader, inDef);
+ }
+
+ /// The standard core functions are all there (SPEC.md section 2).
+ [Fact]
+ public void CoreFunctionsExist()
+ {
+ string[] core = { "api_version", "last_error", "units", "world_create", "world_destroy", "char_add", "char_remove",
+ "char_input", "world_tick", "char_state", "char_camera", "events", "events_dropped",
+ "state_size", "save_state", "load_state", "state_hash", "get_api" };
+ foreach (string f in core) Assert.Matches($@"\btpl_{f}\(", Header());
+ }
+ }
+}
diff --git a/TEMPLATE/tests/Tpl.Core.Tests/ProvenanceTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/ProvenanceTests.cs
new file mode 100644
index 0000000..a3dc53f
--- /dev/null
+++ b/TEMPLATE/tests/Tpl.Core.Tests/ProvenanceTests.cs
@@ -0,0 +1,52 @@
+using System.IO;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using Xunit;
+
+namespace Tpl.Tests
+{
+ /// Every gameplay number is VERIFIED (with a source) or UNVERIFIED (with a reason). SPEC.md section 7.
+ public class ProvenanceTests
+ {
+ static FieldInfo[] Fields() => typeof(Tuning).GetFields(BindingFlags.Public | BindingFlags.Instance);
+
+ [Fact]
+ public void EveryTuningFieldIsVerifiedOrUnverified()
+ {
+ foreach (FieldInfo f in Fields())
+ {
+ bool verified = f.GetCustomAttribute() != null;
+ bool unverified = f.GetCustomAttribute() != null;
+ Assert.True(verified ^ unverified, $"Tuning.{f.Name} needs exactly one of [Verified] or [Unverified].");
+ }
+ }
+
+ [Fact]
+ public void SourcesAndReasonsAreNotEmpty()
+ {
+ foreach (FieldInfo f in Fields())
+ {
+ string? text = f.GetCustomAttribute()?.Source ?? f.GetCustomAttribute()?.Reason;
+ Assert.False(string.IsNullOrWhiteSpace(text), $"Tuning.{f.Name} has an empty source or reason.");
+ }
+ }
+
+ /// Each [Unverified] field must have a plan: Docs/MEASURE.md names it (as `Tuning.Name`).
+ [Fact]
+ public void EveryUnverifiedFieldIsInMeasure()
+ {
+ string measure = Repo.Read("Docs", "MEASURE.md");
+ foreach (FieldInfo f in Fields())
+ if (f.GetCustomAttribute() != null)
+ Assert.True(Regex.IsMatch(measure, $@"`Tuning\.{f.Name}`"), $"Tuning.{f.Name} is UNVERIFIED but Docs/MEASURE.md does not name it.");
+ }
+
+ /// Every replay says where it came from.
+ [Fact]
+ public void EveryReplayHasASource()
+ {
+ foreach (string path in Directory.GetFiles(Path.Combine(Repo.Root(), "tests", "Tpl.Core.Tests", "Replays"), "*.replay"))
+ Assert.Matches(@"(?m)^source:\s*(VERIFIED|UNVERIFIED):\s*\S", File.ReadAllText(path));
+ }
+ }
+}
diff --git a/TEMPLATE/tests/Tpl.Core.Tests/Replay.cs b/TEMPLATE/tests/Tpl.Core.Tests/Replay.cs
new file mode 100644
index 0000000..2946362
--- /dev/null
+++ b/TEMPLATE/tests/Tpl.Core.Tests/Replay.cs
@@ -0,0 +1,218 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+
+namespace Tpl.Tests
+{
+ ///
+ /// Reads, runs and writes inklib replay files (format "inklib-replay 1", Docs/REPLAY.md).
+ /// The format is the same in every inklib; only the button and state names are this lib's.
+ ///
+ sealed class Replay
+ {
+ public sealed class Row
+ {
+ public int Line, Ticks;
+ public PadInput Input;
+ /// Expected x, y, z, yaw after the row; null = do not check.
+ public double?[] Expect = new double?[4];
+ public MoveState? State;
+ }
+
+ static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
+ static readonly string[] Columns = { "ticks", "buttons", "move_x", "move_y", "look_x", "look_y", "|", "x", "y", "z", "yaw", "state" };
+
+ public string Name = "";
+ public string Source = "";
+ public UnitMode Units = UnitMode.Native;
+ public string World = "flat";
+ public double[] Start = new double[4];
+ public double[]? Origin;
+ public double Tolerance = 0.01;
+ /// Expected after the last row, if given.
+ public ulong? Hash;
+ public readonly List<(string Field, string Value)> TuningOverrides = new List<(string, string)>();
+ public readonly List Rows = new List();
+
+ public static Replay Load(string path)
+ {
+ var r = new Replay { Name = Path.GetFileNameWithoutExtension(path) };
+ string[] lines = File.ReadAllLines(path);
+ bool table = false, sawFormat = false, sawLib = false;
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string line = lines[i];
+ int hash = line.IndexOf('#');
+ if (hash >= 0) line = line.Substring(0, hash);
+ line = line.Trim();
+ if (line.Length == 0) continue;
+ string where = $"{path}:{i + 1}";
+
+ if (!table)
+ {
+ if (line.StartsWith("ticks", StringComparison.Ordinal))
+ {
+ string[] cols = Split(line);
+ if (!cols.SequenceEqual(Columns)) throw new FormatException($"{where}: table header must be: {string.Join(" ", Columns)}");
+ table = true;
+ continue;
+ }
+ int colon = line.IndexOf(':');
+ if (colon < 0) throw new FormatException($"{where}: expected 'key: value'");
+ string key = line.Substring(0, colon).Trim(), value = line.Substring(colon + 1).Trim();
+ if (!sawFormat && key != "format") throw new FormatException($"{where}: the first line must be 'format: inklib-replay 1'");
+ switch (key)
+ {
+ case "format":
+ if (value != "inklib-replay 1") throw new FormatException($"{where}: unknown format '{value}'");
+ sawFormat = true; break;
+ case "lib":
+ if (Split(value)[0] != "tpl") throw new FormatException($"{where}: replay is for lib '{value}', this is tpl");
+ sawLib = true; break;
+ case "name": r.Name = value; break;
+ case "source": r.Source = value; break;
+ case "units":
+ r.Units = value == "native" ? UnitMode.Native : value == "shared" ? UnitMode.Shared
+ : throw new FormatException($"{where}: units must be native or shared"); break;
+ case "world": r.World = value; break;
+ case "start": r.Start = Numbers(value, 4, where); break;
+ case "origin": r.Origin = Numbers(value, 3, where); break;
+ case "tolerance": r.Tolerance = double.Parse(value, Inv); break;
+ case "hash":
+ if (!value.StartsWith("0x", StringComparison.Ordinal)) throw new FormatException($"{where}: hash: 0x followed by 16 hex digits");
+ r.Hash = ulong.Parse(value.Substring(2), NumberStyles.HexNumber, Inv); break;
+ case "tuning":
+ string[] kv = Split(value);
+ if (kv.Length != 2) throw new FormatException($"{where}: tuning: Field value");
+ r.TuningOverrides.Add((kv[0], kv[1])); break;
+ default: throw new FormatException($"{where}: unknown key '{key}'");
+ }
+ continue;
+ }
+
+ string[] t = Split(line);
+ if (t.Length != Columns.Length || t[6] != "|") throw new FormatException($"{where}: expected {Columns.Length} columns");
+ var row = new Row { Line = i + 1, Ticks = int.Parse(t[0], Inv) };
+ if (row.Ticks < 1) throw new FormatException($"{where}: ticks must be 1 or more");
+ row.Input = new PadInput
+ {
+ Buttons = ParseButtons(t[1], where),
+ MoveX = float.Parse(t[2], Inv), MoveY = float.Parse(t[3], Inv),
+ LookX = float.Parse(t[4], Inv), LookY = float.Parse(t[5], Inv),
+ };
+ for (int k = 0; k < 4; k++) row.Expect[k] = t[7 + k] == "-" ? (double?)null : double.Parse(t[7 + k], Inv);
+ row.State = t[11] == "-" ? (MoveState?)null : (MoveState)Enum.Parse(typeof(MoveState), t[11]);
+ r.Rows.Add(row);
+ }
+ if (!sawFormat || !sawLib) throw new FormatException($"{path}: needs 'format:' and 'lib:' lines");
+ if (!table) throw new FormatException($"{path}: no table");
+ return r;
+ }
+
+ static string[] Split(string s) => s.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
+
+ static double[] Numbers(string s, int count, string where)
+ {
+ string[] p = Split(s);
+ if (p.Length != count) throw new FormatException($"{where}: expected {count} numbers");
+ return p.Select(x => double.Parse(x, Inv)).ToArray();
+ }
+
+ static Buttons ParseButtons(string s, string where)
+ {
+ if (s == "0") return Buttons.None;
+ if (s.StartsWith("0x", StringComparison.Ordinal)) return (Buttons)uint.Parse(s.Substring(2), NumberStyles.HexNumber, Inv);
+ Buttons b = Buttons.None;
+ foreach (string name in s.Split('+'))
+ {
+ if (!Enum.TryParse(name, true, out Buttons one)) throw new FormatException($"{where}: unknown button '{name}'");
+ b |= one;
+ }
+ return b;
+ }
+
+ static string FormatButtons(Buttons b) =>
+ b == Buttons.None ? "0" : string.Join("+", Enum.GetValues(typeof(Buttons)).Cast()
+ .Where(x => x != Buttons.None && (b & x) == x).Select(x => x.ToString().ToLowerInvariant()));
+
+ public Tuning MakeTuning()
+ {
+ var t = new Tuning();
+ foreach (var (field, value) in TuningOverrides)
+ {
+ FieldInfo f = typeof(Tuning).GetField(field) ?? throw new FormatException($"{Name}: no Tuning.{field}");
+ f.SetValue(t, Convert.ChangeType(value, f.FieldType, Inv));
+ }
+ return t;
+ }
+
+ public (World world, int id) MakeWorld()
+ {
+ ICollisionWorld col = TestWorld.Make(World);
+ if (Units == UnitMode.Shared) col = new SharedHost(col);
+ var w = new World(MakeTuning(), col, Units);
+ int id = w.AddCharacter(new Vec3(Start[0], Start[1], Start[2]), Start[3]);
+ return (w, id);
+ }
+
+ /// Runs the replay. Returns null if it matches, else what went wrong and where.
+ public string? Run()
+ {
+ var (w, id) = MakeWorld();
+ foreach (Row row in Rows)
+ {
+ w.SetInput(id, row.Input);
+ w.Step(row.Ticks);
+ w.GetState(id, out CharacterState s);
+ double[] got = { s.Position.X, s.Position.Y, s.Position.Z, s.Yaw };
+ string[] names = { "x", "y", "z", "yaw" };
+ for (int k = 0; k < 4; k++)
+ {
+ if (row.Expect[k] is not double e) continue;
+ if (k < 3 && Origin != null) e = e - Origin[k] + Start[k];
+ if (Math.Abs(got[k] - e) > Tolerance)
+ return $"{Name} line {row.Line}, tick {s.Tick}: {names[k]} is {got[k].ToString("R", Inv)}, expected {e.ToString("R", Inv)} (tolerance {Tolerance.ToString(Inv)})";
+ }
+ if (row.State is MoveState st && st != s.State)
+ return $"{Name} line {row.Line}, tick {s.Tick}: state is {s.State}, expected {st}";
+ }
+ if (Hash is ulong want && w.StateHash() != want)
+ return $"{Name}: state hash after the last row is 0x{w.StateHash():x16}, expected 0x{want:x16}. "
+ + "Positions matched, so the bits differ: a determinism problem (SPEC.md section 5), or a deliberate change (record again).";
+ return null;
+ }
+
+ ///
+ /// Runs (inputs only) and writes a regression replay with the positions
+ /// the lib produces now. Only for UNVERIFIED regression files; never for measured ones.
+ ///
+ public string Record(string source)
+ {
+ var (w, id) = MakeWorld();
+ var sb = new StringBuilder();
+ sb.Append("format: inklib-replay 1\nlib: tpl 1\n");
+ sb.Append($"name: {Name}\nsource: {source}\nunits: {(Units == UnitMode.Native ? "native" : "shared")}\nworld: {World}\n");
+ sb.Append("start: " + string.Join(" ", Start.Select(F)) + "\n");
+ sb.Append($"tolerance: {F(Tolerance)}\n");
+ sb.Append("hash: HASH\n");
+ foreach (var (field, value) in TuningOverrides) sb.Append($"tuning: {field} {value}\n");
+ sb.Append("\n" + string.Join(" ", Columns) + "\n");
+ foreach (Row row in Rows)
+ {
+ w.SetInput(id, row.Input);
+ w.Step(row.Ticks);
+ w.GetState(id, out CharacterState s);
+ PadInput p = row.Input;
+ sb.Append($"{row.Ticks} {FormatButtons(p.Buttons)} {F(p.MoveX)} {F(p.MoveY)} {F(p.LookX)} {F(p.LookY)} | ");
+ sb.Append($"{F(Math.Round(s.Position.X, 6))} {F(Math.Round(s.Position.Y, 6))} {F(Math.Round(s.Position.Z, 6))} {F(Math.Round(s.Yaw, 6))} {s.State}\n");
+ }
+ return sb.ToString().Replace("hash: HASH", $"hash: 0x{w.StateHash():x16}");
+ }
+
+ static string F(double v) => (v == 0 ? 0.0 : v).ToString("0.######", Inv);
+ }
+}
diff --git a/TEMPLATE/tests/Tpl.Core.Tests/ReplayTests.cs b/TEMPLATE/tests/Tpl.Core.Tests/ReplayTests.cs
new file mode 100644
index 0000000..d8f294b
--- /dev/null
+++ b/TEMPLATE/tests/Tpl.Core.Tests/ReplayTests.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Xunit;
+
+namespace Tpl.Tests
+{
+ public class ReplayTests
+ {
+ public static IEnumerable