From 82ddfc98a677938e3c89cd223e90c7fe3b194c9f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 21:17:41 +0100 Subject: [PATCH] Add retained Box3D session contract --- README.md | 32 +- docs/architecture.md | 19 +- docs/box3d-parity.md | 12 +- docs/retained-session-contract.md | 159 +++ native/Ymir.Box3D/ymir_box3d.c | 589 ++++++++++- src/Ymir.Box3D/Box3DNative.cs | 85 +- src/Ymir.Box3D/Box3DSession.cs | 151 ++- src/Ymir.Box3D/Ymir.Box3D.csproj | 2 +- src/Ymir.Core/RetainedSessionModel.cs | 120 +++ .../YmirServicePublicationDocument.cs | 13 +- src/Ymir.Core/YmirSession.cs | 992 ++++++++++++++++++ tests/Ymir.Box3D.Parity/Box3DOracle.cs | 73 ++ tests/Ymir.Box3D.Parity/Box3DParityTests.cs | 47 + .../Ymir.Tests/YmirServicePublicationTests.cs | 4 +- tests/Ymir.Tests/YmirSessionTests.cs | 215 ++++ 15 files changed, 2473 insertions(+), 40 deletions(-) create mode 100644 docs/retained-session-contract.md create mode 100644 src/Ymir.Core/RetainedSessionModel.cs create mode 100644 src/Ymir.Core/YmirSession.cs create mode 100644 tests/Ymir.Tests/YmirSessionTests.cs diff --git a/README.md b/README.md index 9afa0d5..138a991 100644 --- a/README.md +++ b/README.md @@ -16,12 +16,13 @@ authorities. lifecycle, force and torque lifetime, tolerances, and deterministic step behavior for identical recorded inputs. - Ymir currently owns the pinned Box3D version, stable GameCult entity ids, - native ABI isolation, snapshot lowering, deterministic result ordering, - versioned CultCache snapshots, and a diagnostic Eve publication. -- The Ymir daemon will own long-lived world sessions, typed commands and - receipts, contact lifecycle facts, checkpoint reconstruction, CultMesh - publication, and process supervision. Those are the cutover contract, not a - claim that the current CLI already exposes them. + native ABI isolation, public in-process retained sessions, explicit mutation + receipts, typed contact facts, snapshot lowering, deterministic result + ordering, versioned CultCache snapshots, and a diagnostic Eve publication. +- The Ymir daemon will own named session routing, durable command receipts, + checkpoint reconstruction, CultMesh command/fact publication, and process + supervision. Those are the daemon cutover contract, not a claim that the + current CLI already exposes them. - Aetheria owns gameplay policy and supplies typed physical intent: bodies, fields, tractor targets, forces, projectiles, filters, and the gameplay consequences of Ymir contact facts. @@ -53,16 +54,19 @@ projects the result, and disposes it. It contains no managed integrator, collision loop, or impulse solver. That snapshot facade deliberately does not pretend to own long-lived world -identity. The retained native session exists behind an internal managed port; -there is not yet a public session registry or command contract. Aetheria will -name one Ymir session per run and zone when that contract is exposed. Its old -process-wide simulator objects are not session identifiers. Planar heading, -angular velocity, and transient torque already pass through Box3D. Typed -begin/end/hit lifecycle facts, checkpoint reconstruction, and non-Windows RID -artifacts remain cutover work. +identity. The public in-process `YmirSession` now exposes explicit body +mutations, force and torque commands, revisioned receipts, retained stepping, +and typed Begin/Hit/End facts. It never treats omission as removal. The daemon +still lacks a named session registry and CultMesh command lowering. Aetheria +will name one session per run and zone through that daemon contract; its old +process-wide simulator objects are not session identifiers. Retained-world +queries, checkpoint reconstruction, and non-Windows RID artifacts remain +cutover work. See [the architecture map](docs/architecture.md) and -[the executable parity contract](docs/box3d-parity.md). +[the executable parity contract](docs/box3d-parity.md). The +[retained-session contract](docs/retained-session-contract.md) records the +current ownership cut and the public daemon boundary being built. ## Build And Test diff --git a/docs/architecture.md b/docs/architecture.md index ce93991..4f8a989 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,12 +36,17 @@ an isolated internal session for one complete snapshot, projects its output, and disposes it. Public circle overlap and cast APIs invoke Box3D geometry over caller-supplied bodies. -The retained native session and its managed wrapper are internal. The current -CLI has no named session registry, public mutation commands, command receipts, -retained-world queries, or begin/end/hit lifecycle contract. Its CultCache and -Eve output is a regenerated diagnostic projection. The sections marked as -target contract describe the cut still to build; they are not advertisements -of current daemon capability. +The retained native session now has a public in-process `YmirSession` port with +explicit spawn, remove, teleport, velocity, configuration, force, torque, +step, and disposal operations. It emits revisioned receipts and typed +Begin/Hit/End facts with stable Ymir identities. Ordinary retained steps do not +accept complete body snapshots. + +The current CLI still has no named session registry, CultMesh command +lowerings, retained-world queries, durable receipt ledger, or reconstruction +checkpoint. Its CultCache and Eve output is a regenerated diagnostic +projection. The sections marked as target contract describe that daemon cut; +they are not advertisements of current CLI capability. ## Target Inputs @@ -114,7 +119,7 @@ infer retained identity from a body list. Session identity must be explicit. A process-wide simulator object, zone index, or repeated stable body id is not enough to join two calls to the same world. Aetheria owns run and zone lifetime and will create, retain, and dispose the -corresponding Ymir session after the public port exists. Current projectile +corresponding Ymir session after daemon registry integration. Current projectile sweep and stationary mine proximity integration can use Ymir's static Box3D-backed circle-cast and overlap queries, but those calls do not join a retained world or own contact lifecycle. diff --git a/docs/box3d-parity.md b/docs/box3d-parity.md index e03f84f..1cb7f92 100644 --- a/docs/box3d-parity.md +++ b/docs/box3d-parity.md @@ -21,11 +21,15 @@ the overlap, cast, pair-step, torque-lifetime, version, and ABI-layout operations used by the harness. This keeps Box3D's alpha C ABI out of Ymir's public managed contracts. -Production ABI version 2 uses caller-owned blittable buffers, explicit cdecl, +Production ABI version 3 uses caller-owned blittable buffers, explicit cdecl, fixed-width status/count values, compile-time C layout assertions, and a -managed/native layout sentinel before opening a session. Planar direction maps -to Box3D rotation about Y; angular velocity and transient torque remain Box3D -state and commands rather than managed integration. +managed/native layout sentinel before opening a session. It adds explicit +retained body mutations, one-shot force and torque operations, and a +session-owned Begin/Hit/End event buffer. The private buffer retains Box3D's +stored contact key only long enough to correlate its separate event arrays; +public Ymir facts never expose native contact identity. Planar direction maps to Box3D +rotation about Y; angular velocity and transient torque remain Box3D state and +commands rather than managed integration. `tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with source-generated .NET interop. Run it with: diff --git a/docs/retained-session-contract.md b/docs/retained-session-contract.md new file mode 100644 index 0000000..a5920dd --- /dev/null +++ b/docs/retained-session-contract.md @@ -0,0 +1,159 @@ +# Retained Session Contract + +## Objective + +One named Ymir session owns one retained Box3D world. A product may restore the +world once, issue explicit mutations, step it, query it, and consume typed +Box3D contact facts. A body snapshot is output and checkpoint material; it is +not an implicit command language. + +## Current Mechanism + +`YmirSimulator` is an isolated snapshot compatibility API. It creates a native +session, synchronizes a complete body list, steps once, projects the result, +and disposes the session. Its private compatibility helper uses that complete +list, so omission can delete a body and stale input can teleport or overwrite +solver velocity inside the isolated call. Its legacy contact output merges +current manifolds, begin events, and hit events into one pair-deduplicated list +and omits End. + +The public `YmirSession` does not use that mechanism for ordinary retained +steps. The compatibility path is not the retained daemon contract. + +## Owner + +- One public Ymir session serializes commands for one named world. +- Its native Box3D `b3World` exclusively owns integration, collision, + broadphase, queries, solver state, and contact lifecycle. +- Ymir owns stable GameCult ids, body generations, session revision, step + sequence, deterministic projection, fact identity, and command receipts. +- The product owns session lifetime and gameplay policy. Aetheria will map one + `(RunId, ZoneIndex)` lifetime to one Ymir session. + +## Target Inputs + +The retained port accepts narrow operations with explicit meaning: + +- spawn a body, rejecting an existing id; +- remove a body, rejecting an unknown id; +- teleport a body; +- set linear and angular velocity; +- configure body shape, mass, type, and restitution; +- apply one-shot force or torque; +- step with a fixed delta, substep count, and typed fields; +- dispose the session. + +The current public slice implements those mutation and step operations. +Retained-world overlap and cast queries at a named revision are the next +library cut; the static compatibility queries do not satisfy that contract. + +Restore/import is the only path allowed to accept a complete world snapshot. +There is no `Upsert`, generic patch bag, or omission-based removal. + +## Outputs + +Each accepted mutation produces a receipt that names the session generation, +command id, before revision, and after revision. A step additionally returns: + +- authoritative Box3D body state; +- the new step index; +- typed `Begin`, `Hit`, and `End` facts; +- stable fact ids and contact-episode ids; +- the accepted step configuration through its typed command. + +The current library validates the native Box3D version and ABI before session +creation but does not repeat those facts in every Step result. + +Facts canonicalize bodies by stable id and flip normals when canonicalization +swaps endpoints. Their public order is body pair, contact episode, kind, then +within-kind ordinal. This is stable publication order, not invented substep +chronology. + +## Derived State + +- Box3D handles are process-local and never cross the contract. +- DTO and SoA body arrays are projections. +- `gamecult.ymir.world_state.v1` is an inspection/migration snapshot, not a + retained-session checkpoint. +- Receipt and contact-episode ledgers are session metadata, not physics law. +- Aetheria cargo, damage, loot, feedback, and scoring remain gameplay state + derived from Ymir facts. + +The current in-process receipt ledger is not the durable daemon ledger. It is +kept for the lifetime of the session and is intentionally not advertised as a +reconnect or checkpoint guarantee. + +## Forbidden Writers + +- recurring complete-body synchronization after restore; +- snapshot omission as body removal; +- transform or velocity setters hidden inside ordinary Step; +- managed contact lifecycle inference that replaces Box3D events; +- random fact ids or ids derived from manifold floats; +- Box3D callback order exposed as a public ordering guarantee; +- Unity callbacks, renderer state, or gameplay proximity checks deciding + contact truth. + +## Shared Paths + +Direct commands, agent commands, and spawns use the same explicit in-process +session operations. Imports, reconnects, and replay must lower through those +operations after the daemon registry and reconstruction contract exist. +Restore will establish initial state; it will not remain a parallel writer. +Retained queries will observe a named revision without mutating it. Snapshot +reads cannot be fed back without an explicit restore, teleport, velocity, or +configuration operation. + +## Contact Identity + +A contact episode is identified by the canonical pair of body id plus body +generation and a monotonically assigned episode number. Begin and End share +that identity. A later re-contact creates a new episode. Fact identity derives +from session generation, step index, contact episode, kind, and deterministic +ordinal. Box3D contact and shape handles are never durable identity. + +Body removal must close any active episode exactly once. Because Box3D End +events may reference destroyed shapes, the native boundary retains stable ids +until the event buffer has been drained. + +Box3D publishes Begin, Hit, and End in separate arrays rather than one causal +sequence. The private ABI carries Box3D's stored transient contact key so Ymir +can correlate those arrays before assigning public episode identity. That key +is derived process state: it never appears in a public fact or checkpoint. + +## Cut Line + +1. Typed native mutation operations and step-owned lifecycle buffers: done. +2. Public managed retained session with no ordinary full synchronization: + done. +3. Add retained-world queries and revision checks. +4. Add the daemon session registry, generation-bearing routed commands, + idempotent Create, bounded live dedupe backed by durable receipts, and + CultMesh command lowering. +5. Move Aetheria to one session per run and zone, then delete its process-wide + simulator identity, manual tractor geometry, per-projectile mini-worlds, + and tuple contact dedup. + +The isolated `YmirSimulator` remains a compatibility API. It is never the +daemon authority. + +Mutation-generated End evidence is currently retained in the native pending +buffer and published by the next accepted Step. The daemon transaction cut +must make mutation plus Step one publication boundary, or return mutation facts +directly, before Ymir promises that removal followed by disposal publishes an +End fact. + +## Verification + +- A spawned body advances across steps without being resubmitted. +- Omission from unrelated commands cannot remove or reset a body. +- Force and torque affect exactly one accepted step. +- stale revisions and conflicting command ids cannot mutate the world. +- persistent touching emits one Begin, separation emits one End, and re-contact + creates a new episode. +- duplicate fact delivery cannot commit Aetheria cargo twice. +- different insertion orders produce the same semantic fact order. +- queries observe the requested retained revision and cannot inject bodies. +- disposed or stale session generations fail closed. +- restored continuation must reproduce bodies and fact identity before Ymir + advertises retained-session checkpoint support. diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c index 0126aa8..9120c2c 100644 --- a/native/Ymir.Box3D/ymir_box3d.c +++ b/native/Ymir.Box3D/ymir_box3d.c @@ -131,6 +131,40 @@ typedef struct ymir_box3d_session_contact_output float relative_speed; } ymir_box3d_session_contact_output; +typedef enum ymir_box3d_contact_kind +{ + YMIR_BOX3D_CONTACT_BEGIN = 1, + YMIR_BOX3D_CONTACT_HIT = 2, + YMIR_BOX3D_CONTACT_END = 3, +} ymir_box3d_contact_kind; + +typedef struct ymir_box3d_session_contact_event_output +{ + int32_t kind; + uint32_t has_details; + uint32_t contact_id[3]; + uint64_t stable_id_a; + uint64_t stable_id_b; + float point_x; + float point_y; + float normal_x; + float normal_y; + float penetration; + float relative_speed; +} ymir_box3d_session_contact_event_output; + +typedef struct ymir_box3d_retired_shape +{ + uint64_t shape_id; + uint64_t stable_id; +} ymir_box3d_retired_shape; + +typedef struct ymir_box3d_drained_event +{ + int32_t kind; + uint32_t contact_id[3]; +} ymir_box3d_drained_event; + typedef struct ymir_box3d_session_body { uint64_t stable_id; @@ -157,6 +191,18 @@ typedef struct ymir_box3d_session ymir_box3d_session_body* bodies; int body_count; int body_capacity; + ymir_box3d_session_contact_event_output* contact_events; + int contact_event_count; + int contact_event_capacity; + ymir_box3d_session_contact_event_output* pending_events; + int pending_event_count; + int pending_event_capacity; + ymir_box3d_retired_shape* retired_shapes; + int retired_shape_count; + int retired_shape_capacity; + ymir_box3d_drained_event* drained_events; + int drained_event_count; + int drained_event_capacity; } ymir_box3d_session; _Static_assert(sizeof(ymir_box3d_status) == sizeof(int32_t), "Ymir Box3D status ABI must be 32-bit"); @@ -164,6 +210,7 @@ _Static_assert(sizeof(ymir_box3d_session_body_input) == 56, "Unexpected Ymir Box _Static_assert(sizeof(ymir_box3d_radial_field_input) == 16, "Unexpected Ymir Box3D field layout"); _Static_assert(sizeof(ymir_box3d_session_body_output) == 40, "Unexpected Ymir Box3D body output layout"); _Static_assert(sizeof(ymir_box3d_session_contact_output) == 40, "Unexpected Ymir Box3D contact layout"); +_Static_assert(sizeof(ymir_box3d_session_contact_event_output) == 64, "Unexpected Ymir Box3D contact event layout"); static b3Vec3 ymir_vec(float x, float y) { @@ -245,6 +292,76 @@ static ymir_box3d_status ymir_session_reserve_bodies(ymir_box3d_session* session return YMIR_BOX3D_OK; } +static ymir_box3d_status ymir_session_reserve_contact_events( + ymir_box3d_session_contact_event_output** events, + int* current_capacity, + int capacity) +{ + if (capacity <= *current_capacity) + { + return YMIR_BOX3D_OK; + } + + int new_capacity = *current_capacity > 0 ? *current_capacity : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_session_contact_event_output* resized = (ymir_box3d_session_contact_event_output*)realloc( + *events, (size_t)new_capacity * sizeof(ymir_box3d_session_contact_event_output)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + *events = resized; + *current_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_reserve_retired_shapes(ymir_box3d_session* session, int capacity) +{ + if (capacity <= session->retired_shape_capacity) + { + return YMIR_BOX3D_OK; + } + int new_capacity = session->retired_shape_capacity > 0 ? session->retired_shape_capacity * 2 : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_retired_shape* resized = (ymir_box3d_retired_shape*)realloc( + session->retired_shapes, (size_t)new_capacity * sizeof(ymir_box3d_retired_shape)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + session->retired_shapes = resized; + session->retired_shape_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_reserve_drained_events(ymir_box3d_session* session, int capacity) +{ + if (capacity <= session->drained_event_capacity) + { + return YMIR_BOX3D_OK; + } + int new_capacity = session->drained_event_capacity > 0 ? session->drained_event_capacity * 2 : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_drained_event* resized = (ymir_box3d_drained_event*)realloc( + session->drained_events, (size_t)new_capacity * sizeof(ymir_box3d_drained_event)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + session->drained_events = resized; + session->drained_event_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + static float ymir_session_density(float mass, float radius) { float volume = 4.0f / 3.0f * B3_PI * radius * radius * radius; @@ -485,6 +602,217 @@ static int ymir_session_contact_from_manifolds( return 1; } +static uint64_t ymir_session_resolve_event_shape( + const ymir_box3d_session* session, + b3ShapeId shape_id) +{ + if (b3Shape_IsValid(shape_id)) + { + return ymir_session_shape_stable_id(shape_id); + } + + uint64_t stored_shape_id = b3StoreShapeId(shape_id); + for (int i = 0; i < session->retired_shape_count; ++i) + { + if (session->retired_shapes[i].shape_id == stored_shape_id) + { + return session->retired_shapes[i].stable_id; + } + } + return 0; +} + +static int ymir_session_event_was_drained( + const ymir_box3d_session* session, + int32_t kind, + b3ContactId contact_id) +{ + uint32_t stored[3]; + b3StoreContactId(contact_id, stored); + for (int i = 0; i < session->drained_event_count; ++i) + { + const ymir_box3d_drained_event* event = session->drained_events + i; + if (event->kind == kind && event->contact_id[0] == stored[0] && + event->contact_id[1] == stored[1] && event->contact_id[2] == stored[2]) + { + return 1; + } + } + return 0; +} + +static ymir_box3d_status ymir_session_mark_event_drained( + ymir_box3d_session* session, + int32_t kind, + b3ContactId contact_id) +{ + ymir_box3d_status status = ymir_session_reserve_drained_events(session, session->drained_event_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + ymir_box3d_drained_event* stored = session->drained_events + session->drained_event_count++; + stored->kind = kind; + b3StoreContactId(contact_id, stored->contact_id); + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_append_typed_event( + ymir_box3d_session* session, + int pending, + const ymir_box3d_session_contact_event_output* event) +{ + ymir_box3d_session_contact_event_output** events = pending ? &session->pending_events : &session->contact_events; + int* count = pending ? &session->pending_event_count : &session->contact_event_count; + int* capacity = pending ? &session->pending_event_capacity : &session->contact_event_capacity; + ymir_box3d_status status = ymir_session_reserve_contact_events(events, capacity, *count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + (*events)[(*count)++] = *event; + return YMIR_BOX3D_OK; +} + +enum +{ + YMIR_DRAIN_BEGIN = 1, + YMIR_DRAIN_HIT = 2, + YMIR_DRAIN_END = 4, +}; + +static ymir_box3d_status ymir_session_drain_contact_events( + ymir_box3d_session* session, + int event_mask, + int pending) +{ + b3ContactEvents events = b3World_GetContactEvents(session->world_id); + if ((event_mask & YMIR_DRAIN_BEGIN) != 0) + { + for (int i = 0; i < events.beginCount; ++i) + { + const b3ContactBeginTouchEvent* source = events.beginEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_BEGIN, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_BEGIN, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + }; + b3StoreContactId(source->contactId, event.contact_id); + if (b3Contact_IsValid(source->contactId)) + { + b3ContactData data = b3Contact_GetData(source->contactId); + ymir_box3d_session_contact_output details; + if (ymir_session_contact_from_manifolds(&data, &details)) + { + event.has_details = 1; + event.point_x = details.point_x; + event.point_y = details.point_y; + event.normal_x = details.normal_x; + event.normal_y = details.normal_y; + event.penetration = details.penetration; + event.relative_speed = details.relative_speed; + } + } + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_BEGIN, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + + if ((event_mask & YMIR_DRAIN_HIT) != 0) + { + for (int i = 0; i < events.hitCount; ++i) + { + const b3ContactHitEvent* source = events.hitEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_HIT, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_HIT, + .has_details = 1, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + .point_x = source->point.x, + .point_y = source->point.z, + .normal_x = source->normal.x, + .normal_y = source->normal.z, + .relative_speed = -source->approachSpeed, + }; + b3StoreContactId(source->contactId, event.contact_id); + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_HIT, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + + if ((event_mask & YMIR_DRAIN_END) != 0) + { + for (int i = 0; i < events.endCount; ++i) + { + const b3ContactEndTouchEvent* source = events.endEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_END, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_END, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + }; + b3StoreContactId(source->contactId, event.contact_id); + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_END, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + return YMIR_BOX3D_OK; +} + static ymir_box3d_status ymir_session_emit_contact( ymir_box3d_stable_pair_set* seen, const ymir_box3d_session_contact_output* contact, @@ -822,16 +1150,18 @@ YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_get_abi_version(void) { - return 2; + return 3; } YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( uint32_t* body_input_size, uint32_t* field_input_size, uint32_t* body_output_size, - uint32_t* contact_output_size) + uint32_t* contact_output_size, + uint32_t* contact_event_output_size) { - if (body_input_size == NULL || field_input_size == NULL || body_output_size == NULL || contact_output_size == NULL) + if (body_input_size == NULL || field_input_size == NULL || body_output_size == NULL || + contact_output_size == NULL || contact_event_output_size == NULL) { return YMIR_BOX3D_INVALID_ARGUMENT; } @@ -840,6 +1170,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( *field_input_size = (uint32_t)sizeof(ymir_box3d_radial_field_input); *body_output_size = (uint32_t)sizeof(ymir_box3d_session_body_output); *contact_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_output); + *contact_event_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_event_output); return YMIR_BOX3D_OK; } @@ -884,6 +1215,10 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_session_destroy(ymir_box3d_session* sessio b3DestroyWorld(session->world_id); } free(session->bodies); + free(session->contact_events); + free(session->pending_events); + free(session->retired_shapes); + free(session->drained_events); free(session); } @@ -956,6 +1291,198 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_sync_bodies( return YMIR_BOX3D_OK; } +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_spawn( + ymir_box3d_session* session, + const ymir_box3d_session_body_input* body_input) +{ + if (session == NULL || !ymir_session_body_input_is_valid(body_input)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + if (ymir_session_find_body(session, body_input->stable_id) >= 0) + { + return YMIR_BOX3D_DUPLICATE_ID; + } + ymir_box3d_status status = ymir_session_reserve_bodies(session, session->body_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + ymir_box3d_session_body body; + status = ymir_session_create_body(session, body_input, &body); + if (status == YMIR_BOX3D_OK) + { + session->bodies[session->body_count++] = body; + } + return status; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_remove(ymir_box3d_session* session, uint64_t stable_id) +{ + if (session == NULL || stable_id == 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_status status = ymir_session_reserve_retired_shapes(session, session->retired_shape_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + session->retired_shapes[session->retired_shape_count++] = (ymir_box3d_retired_shape){ + .shape_id = b3StoreShapeId(session->bodies[index].shape_id), + .stable_id = stable_id, + }; + b3DestroyBody(session->bodies[index].body_id); + session->bodies[index] = session->bodies[session->body_count - 1]; + session->body_count -= 1; + return ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_teleport( + ymir_box3d_session* session, + uint64_t stable_id, + float position_x, + float position_y, + float direction_x, + float direction_y) +{ + float direction_length_squared = direction_x * direction_x + direction_y * direction_y; + if (session == NULL || !ymir_is_finite(position_x) || !ymir_is_finite(position_y) || + !ymir_is_finite(direction_x) || !ymir_is_finite(direction_y) || direction_length_squared <= 1.0e-8f) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + b3Body_SetTransform(body->body_id, ymir_vec(position_x, position_y), ymir_session_rotation(direction_x, direction_y)); + body->last_position_x = position_x; + body->last_position_y = position_y; + body->last_direction_x = direction_x; + body->last_direction_y = direction_y; + return ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_set_velocity( + ymir_box3d_session* session, + uint64_t stable_id, + float velocity_x, + float velocity_y, + float angular_velocity) +{ + if (session == NULL || !ymir_is_finite(velocity_x) || !ymir_is_finite(velocity_y) || + !ymir_is_finite(angular_velocity)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + b3Body_SetLinearVelocity(body->body_id, ymir_vec(velocity_x, velocity_y)); + b3Body_SetAngularVelocity(body->body_id, (b3Vec3){0.0f, angular_velocity, 0.0f}); + body->last_velocity_x = velocity_x; + body->last_velocity_y = velocity_y; + body->last_angular_velocity = angular_velocity; + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_configure( + ymir_box3d_session* session, + uint64_t stable_id, + float radius, + float mass, + float restitution, + uint32_t is_static) +{ + if (session == NULL || !ymir_is_finite(radius) || radius <= 0.0f || !ymir_is_finite(mass) || + (is_static == 0 && mass <= 0.0f) || !ymir_is_finite(restitution) || restitution < 0.0f) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + int type_changed = body->is_static != (is_static != 0); + int radius_changed = body->radius != radius; + int mass_changed = body->mass != mass; + if (type_changed) + { + b3Body_SetType(body->body_id, is_static != 0 ? b3_staticBody : b3_dynamicBody); + } + if (radius_changed) + { + b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, radius}; + b3Shape_SetSphere(body->shape_id, &sphere); + } + if (type_changed || radius_changed || mass_changed) + { + float density = is_static != 0 ? 0.0f : ymir_session_density(mass, radius); + b3Shape_SetDensity(body->shape_id, density, false); + b3Body_ApplyMassFromShapes(body->body_id); + } + if (body->restitution != restitution) + { + b3Shape_SetRestitution(body->shape_id, restitution); + } + body->radius = radius; + body->mass = mass; + body->restitution = restitution; + body->is_static = is_static != 0; + ymir_box3d_status status = ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); + return status; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_apply_force( + ymir_box3d_session* session, + uint64_t stable_id, + float force_x, + float force_y) +{ + if (session == NULL || !ymir_is_finite(force_x) || !ymir_is_finite(force_y)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + b3Body_ApplyForceToCenter(session->bodies[index].body_id, ymir_vec(force_x, force_y), true); + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_apply_torque( + ymir_box3d_session* session, + uint64_t stable_id, + float torque) +{ + if (session == NULL || !ymir_is_finite(torque)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + b3Body_ApplyTorque(session->bodies[index].body_id, (b3Vec3){0.0f, torque, 0.0f}, true); + return YMIR_BOX3D_OK; +} + YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( ymir_box3d_session* session, float time_step, @@ -979,6 +1506,23 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( } } + session->contact_event_count = 0; + ymir_box3d_status event_status = ymir_session_reserve_contact_events( + &session->contact_events, &session->contact_event_capacity, session->pending_event_count); + if (event_status != YMIR_BOX3D_OK) + { + return event_status; + } + if (session->pending_event_count > 0) + { + memcpy( + session->contact_events, + session->pending_events, + (size_t)session->pending_event_count * sizeof(ymir_box3d_session_contact_event_output)); + session->contact_event_count = session->pending_event_count; + session->pending_event_count = 0; + } + for (int body_index = 0; body_index < session->body_count; ++body_index) { ymir_box3d_session_body* body = session->bodies + body_index; @@ -1033,6 +1577,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( } b3World_Step(session->world_id, time_step, sub_step_count); + session->drained_event_count = 0; for (int i = 0; i < session->body_count; ++i) { b3Pos position = b3Body_GetPosition(session->bodies[i].body_id); @@ -1048,6 +1593,14 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( session->bodies[i].last_angular_velocity = angular_velocity.y; } + event_status = ymir_session_drain_contact_events( + session, YMIR_DRAIN_BEGIN | YMIR_DRAIN_HIT | YMIR_DRAIN_END, 0); + session->retired_shape_count = 0; + if (event_status != YMIR_BOX3D_OK) + { + return event_status; + } + return YMIR_BOX3D_OK; } @@ -1117,3 +1670,33 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_contacts( *written = 0; return ymir_session_visit_contacts(session, output, capacity, written); } + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_get_contact_event_count(const ymir_box3d_session* session) +{ + return session != NULL ? session->contact_event_count : -YMIR_BOX3D_INVALID_ARGUMENT; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_contact_events( + const ymir_box3d_session* session, + ymir_box3d_session_contact_event_output* output, + int32_t capacity, + int32_t* written) +{ + if (session == NULL || written == NULL || capacity < 0 || (capacity > 0 && output == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + *written = session->contact_event_count; + if (capacity < session->contact_event_count) + { + return YMIR_BOX3D_BUFFER_TOO_SMALL; + } + if (session->contact_event_count > 0) + { + memcpy( + output, + session->contact_events, + (size_t)session->contact_event_count * sizeof(ymir_box3d_session_contact_event_output)); + } + return YMIR_BOX3D_OK; +} diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs index 86b3615..f250b7b 100644 --- a/src/Ymir.Box3D/Box3DNative.cs +++ b/src/Ymir.Box3D/Box3DNative.cs @@ -28,7 +28,8 @@ internal static partial class Box3DNative out uint bodyInputSize, out uint fieldInputSize, out uint bodyOutputSize, - out uint contactOutputSize); + out uint contactOutputSize, + out uint contactEventOutputSize); [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] @@ -72,6 +73,60 @@ internal static partial class Box3DNative Box3DBodyInput* bodies, int bodyCount); + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_spawn( + Box3DSessionHandle session, + Box3DBodyInput* body); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_remove(Box3DSessionHandle session, ulong stableId); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_teleport( + Box3DSessionHandle session, + ulong stableId, + float positionX, + float positionZ, + float directionX, + float directionZ); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_set_velocity( + Box3DSessionHandle session, + ulong stableId, + float velocityX, + float velocityZ, + float angularVelocity); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_configure( + Box3DSessionHandle session, + ulong stableId, + float radius, + float mass, + float restitution, + uint isStatic); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_apply_force( + Box3DSessionHandle session, + ulong stableId, + float forceX, + float forceZ); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_apply_torque( + Box3DSessionHandle session, + ulong stableId, + float torque); + [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static unsafe partial Box3DStatus ymir_box3d_session_step( @@ -104,6 +159,18 @@ internal static partial class Box3DNative Box3DContactOutput* output, int capacity, out int written); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_contact_event_count(Box3DSessionHandle session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contact_events( + Box3DSessionHandle session, + Box3DContactEventOutput* output, + int capacity, + out int written); } internal sealed class Box3DSessionHandle : SafeHandleZeroOrMinusOneIsInvalid @@ -166,6 +233,22 @@ internal readonly record struct Box3DContactOutput( float Penetration, float RelativeSpeed); +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DContactEventOutput( + int Kind, + uint HasDetails, + uint ContactId0, + uint ContactId1, + uint ContactId2, + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DCastOutput( int Hit, diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs index dc409a9..b6a9035 100644 --- a/src/Ymir.Box3D/Box3DSession.cs +++ b/src/Ymir.Box3D/Box3DSession.cs @@ -39,9 +39,31 @@ internal readonly record struct Box3DContact( float Penetration, float RelativeSpeed); +internal enum Box3DContactKind +{ + Begin = 1, + Hit = 2, + End = 3 +} + +internal readonly record struct Box3DContactKey(uint Part0, uint Part1, uint Part2); + +internal readonly record struct Box3DContactFact( + Box3DContactKind Kind, + Box3DContactKey ContactKey, + ulong StableIdA, + ulong StableIdB, + bool HasDetails, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + internal sealed class Box3DSession : IDisposable { - internal const uint AbiVersion = 2; + internal const uint AbiVersion = 3; internal const int DefaultSubstepCount = 4; private readonly Box3DSessionHandle _handle; @@ -93,6 +115,67 @@ internal sealed class Box3DSession : IDisposable } } + internal unsafe void Spawn(Box3DBody body) + { + ThrowIfDisposed(); + var native = ToNative(body); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_spawn(_handle, &native), "spawn body"); + } + + internal void Remove(ulong stableId) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_remove(_handle, stableId), "remove body"); + } + + internal void Teleport( + ulong stableId, + float positionX, + float positionZ, + float directionX, + float directionZ) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_teleport( + _handle, stableId, positionX, positionZ, directionX, directionZ), + "teleport body"); + } + + internal void SetVelocity(ulong stableId, float linearX, float linearZ, float angular) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_set_velocity(_handle, stableId, linearX, linearZ, angular), + "set body velocity"); + } + + internal void Configure( + ulong stableId, + float radius, + float mass, + float restitution, + bool isStatic) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_configure( + _handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u), + "configure body"); + } + + internal void ApplyForce(ulong stableId, float x, float z) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_force(_handle, stableId, x, z), "apply body force"); + } + + internal void ApplyTorque(ulong stableId, float value) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_torque(_handle, stableId, value), "apply body torque"); + } + internal unsafe void Step(float deltaTime, ReadOnlySpan fields, int substepCount = DefaultSubstepCount) { ThrowIfDisposed(); @@ -114,7 +197,7 @@ internal sealed class Box3DSession : IDisposable fixed (Box3DRadialField* pointer = native) { - ThrowIfFailed( + ThrowIfMutationFailed( Box3DNative.ymir_box3d_session_step(_handle, deltaTime, substepCount, pointer, native.Length), "step session"); } @@ -180,6 +263,42 @@ internal sealed class Box3DSession : IDisposable contact.RelativeSpeed)).ToArray(); } + internal unsafe Box3DContactFact[] CopyContactEvents() + { + ThrowIfDisposed(); + var count = Box3DNative.ymir_box3d_session_get_contact_event_count(_handle); + if (count < 0) + { + throw new InvalidOperationException("Box3D returned an invalid contact event count."); + } + + var native = new Box3DContactEventOutput[count]; + fixed (Box3DContactEventOutput* pointer = native) + { + ThrowIfFailed( + Box3DNative.ymir_box3d_session_copy_contact_events(_handle, pointer, count, out var written), + "copy contact events"); + if (written != count) + { + throw new InvalidOperationException( + $"Box3D contact event snapshot changed during copy: expected {count}, received {written}."); + } + } + + return native.Select(contact => new Box3DContactFact( + (Box3DContactKind)contact.Kind, + new Box3DContactKey(contact.ContactId0, contact.ContactId1, contact.ContactId2), + contact.StableIdA, + contact.StableIdB, + contact.HasDetails != 0, + contact.PointX, + contact.PointZ, + contact.NormalX, + contact.NormalZ, + contact.Penetration, + contact.RelativeSpeed)).ToArray(); + } + public void Dispose() { if (_disposed) @@ -204,12 +323,14 @@ internal sealed class Box3DSession : IDisposable out var bodyInputSize, out var fieldInputSize, out var bodyOutputSize, - out var contactOutputSize), + out var contactOutputSize, + out var contactEventOutputSize), "read native ABI layout"); EnsureSize(bodyInputSize); EnsureSize(fieldInputSize); EnsureSize(bodyOutputSize); EnsureSize(contactOutputSize); + EnsureSize(contactEventOutputSize); Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision); if (major != 0 || minor != 1 || revision != 0) @@ -236,5 +357,29 @@ internal sealed class Box3DSession : IDisposable } } + private void ThrowIfMutationFailed(Box3DStatus status, string operation) + { + if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError) + { + Dispose(); + } + ThrowIfFailed(status, operation); + } + + private static Box3DBodyInput ToNative(Box3DBody body) => new( + body.StableId, + body.PositionX, + body.PositionZ, + body.VelocityX, + body.VelocityZ, + body.DirectionX, + body.DirectionZ, + body.AngularVelocity, + body.Torque, + body.Radius, + body.Mass, + body.Restitution, + body.IsStatic ? 1u : 0u); + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); } diff --git a/src/Ymir.Box3D/Ymir.Box3D.csproj b/src/Ymir.Box3D/Ymir.Box3D.csproj index 8664858..8d5c0f2 100644 --- a/src/Ymir.Box3D/Ymir.Box3D.csproj +++ b/src/Ymir.Box3D/Ymir.Box3D.csproj @@ -9,7 +9,7 @@ Ymir.Box3D Native ABI boundary between Ymir sessions and pinned Box3D. GameCult.Ymir.Box3D - 0.1.0 + 0.2.0 GameCult true README.md diff --git a/src/Ymir.Core/RetainedSessionModel.cs b/src/Ymir.Core/RetainedSessionModel.cs new file mode 100644 index 0000000..a30ea72 --- /dev/null +++ b/src/Ymir.Core/RetainedSessionModel.cs @@ -0,0 +1,120 @@ +namespace Ymir.Core; + +public sealed record YmirSessionCreateRequest( + string SessionId, + IReadOnlyList InitialBodies, + float InitialTime = 0.0f); + +public sealed record YmirCommandHeader(string CommandId, long ExpectedRevision); + +public sealed record YmirSpawnBodyCommand(YmirCommandHeader Header, PhysicsBody Body); + +public sealed record YmirRemoveBodyCommand(YmirCommandHeader Header, string BodyId); + +public sealed record YmirTeleportBodyCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 Position, + Vec2 Direction); + +public sealed record YmirSetBodyVelocityCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 LinearVelocity, + float AngularVelocity); + +public sealed record YmirConfigureBodyCommand( + YmirCommandHeader Header, + string BodyId, + float Radius, + float Mass, + bool IsStatic, + float Restitution); + +public sealed record YmirApplyForceCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 Force); + +public sealed record YmirApplyTorqueCommand( + YmirCommandHeader Header, + string BodyId, + float Torque); + +public sealed record YmirStepSessionCommand( + YmirCommandHeader Header, + float DeltaTime, + IReadOnlyList Fields, + int SubstepCount = 4); + +public sealed record YmirDisposeSessionCommand(YmirCommandHeader Header); + +public enum YmirCommandOutcome +{ + Accepted, + Rejected +} + +public enum YmirCommandError +{ + None, + StaleRevision, + CommandIdConflict, + DuplicateBody, + UnknownBody, + StaticBody, + InvalidCommand, + SessionDisposed, + SessionFaulted +} + +public sealed record YmirCommandReceipt( + string ReceiptId, + string SessionId, + string SessionGeneration, + string CommandId, + string CommandKind, + YmirCommandOutcome Outcome, + YmirCommandError Error, + long BeforeRevision, + long AfterRevision, + long ObservedStepIndex, + IReadOnlyList ProducedFactIds); + +public enum YmirContactFactKind +{ + Begin, + Hit, + End +} + +public sealed record YmirContactFact( + string FactId, + string ContactId, + YmirContactFactKind Kind, + string SessionId, + string SessionGeneration, + long StepIndex, + string BodyA, + long BodyAGeneration, + string BodyB, + long BodyBGeneration, + Vec2? Point, + Vec2? Normal, + float? Penetration, + float? RelativeSpeed); + +public sealed record YmirSessionStepResult( + YmirCommandReceipt Receipt, + YmirWorld World, + long Revision, + long StepIndex, + IReadOnlyList ContactFacts); + +public sealed record YmirSessionInfo( + string SessionId, + string SessionGeneration, + long Revision, + long StepIndex, + bool IsDisposed, + bool IsFaulted); diff --git a/src/Ymir.Core/YmirServicePublicationDocument.cs b/src/Ymir.Core/YmirServicePublicationDocument.cs index 4b492ea..615692b 100644 --- a/src/Ymir.Core/YmirServicePublicationDocument.cs +++ b/src/Ymir.Core/YmirServicePublicationDocument.cs @@ -17,7 +17,7 @@ public sealed class YmirProviderAdvertisementDocument public string Title { get; set; } = "Ymir Physics"; [Key(2)] - public string Description { get; set; } = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface."; + public string Description { get; set; } = "GameCult Box3D retained-session library and physics-daemon cutover surface."; [Key(3)] public string[] Owns { get; set; } = []; @@ -44,7 +44,7 @@ public sealed class YmirOperatorStateDocument public string Status { get; set; } = "mvp"; [Key(2)] - public string StateOwner { get; set; } = "Isolated Box3D snapshot steps and typed diagnostic projections"; + public string StateOwner { get; set; } = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections"; [Key(3)] public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)"; @@ -81,10 +81,12 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Title = "Ymir Physics", - Description = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface.", + Description = "GameCult Box3D retained-session library and physics-daemon cutover surface.", Owns = [ "Box3D-only isolated snapshot stepping", + "public in-process retained sessions with explicit mutation receipts", + "typed Begin, Hit, and End contact facts for retained steps", "stable GameCult id to transient Box3D handle projection", "Box3D-backed circle overlap and cast queries over submitted bodies", "deterministic result ordering", @@ -93,8 +95,7 @@ public static class YmirServicePublication ], DoesNotOwn = [ - "public retained session lifecycle yet", - "typed command receipts or begin/end/hit lifecycle facts yet", + "daemon-owned named session registry or CultMesh command lowering yet", "complete checkpoint reconstruction yet", "physics algorithm invention", "Box3D solver and collision semantics", @@ -111,7 +112,7 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Status = "mvp", - StateOwner = "Isolated Box3D snapshot steps and typed diagnostic projections", + StateOwner = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections", NumericSubstrate = "Box3D v0.1.0 (C17)", BatchKernel = "Box3D native solver; Ymir does not own physics algorithms", Persistence = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration", diff --git a/src/Ymir.Core/YmirSession.cs b/src/Ymir.Core/YmirSession.cs new file mode 100644 index 0000000..e963e6c --- /dev/null +++ b/src/Ymir.Core/YmirSession.cs @@ -0,0 +1,992 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Ymir.Box3D; + +namespace Ymir.Core; + +/// +/// Owns one retained Box3D world. Ordinary operations are explicit commands; +/// complete snapshots are accepted only while the session is created. +/// +public sealed class YmirSession : IDisposable +{ + private readonly object _gate = new(); + private readonly Box3DSession _native = new(); + private readonly Dictionary _activeKeysById = new(StringComparer.Ordinal); + private readonly Dictionary _idsByKey = new(); + private readonly Dictionary _generationsByKey = new(); + private readonly Dictionary _bodies = new(StringComparer.Ordinal); + private readonly Dictionary _episodesByNativeContact = new(); + private readonly Dictionary _ledger = new(StringComparer.Ordinal); + private readonly string _sessionId; + private readonly string _sessionGeneration; + private ulong _nextNativeKey = 1; + private long _nextBodyGeneration = 1; + private long _revision; + private long _stepIndex; + private float _time; + private RadialField[] _fields = []; + private bool _disposed; + private bool _faulted; + + private YmirSession(YmirSessionCreateRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (string.IsNullOrWhiteSpace(request.SessionId)) + { + throw new ArgumentException("Session id is required.", nameof(request)); + } + if (!float.IsFinite(request.InitialTime) || request.InitialTime < 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Initial time must be finite and non-negative."); + } + + _sessionId = request.SessionId; + _sessionGeneration = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); + _time = request.InitialTime; + + var initial = request.InitialBodies ?? throw new ArgumentNullException(nameof(request.InitialBodies)); + ValidateUniqueBodyIds(initial); + try + { + foreach (var body in initial.OrderBy(body => body.Id, StringComparer.Ordinal)) + { + ValidateBody(body, allowTorque: false); + SpawnCore(body); + } + } + catch + { + _native.Dispose(); + _disposed = true; + throw; + } + } + + public static YmirSession Create(YmirSessionCreateRequest request) => new(request); + + public YmirSessionInfo Info + { + get + { + lock (_gate) + { + return new YmirSessionInfo( + _sessionId, _sessionGeneration, _revision, _stepIndex, _disposed, _faulted); + } + } + } + + public YmirCommandReceipt Spawn(YmirSpawnBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.spawn", writer => WriteBody(writer, command.Body)); + if (Preflight(command.Header, fingerprint, "body.spawn") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.spawn", fingerprint); + } + if (!TryValidateBody(command.Body, allowTorque: false)) + { + return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.InvalidCommand); + } + if (_activeKeysById.ContainsKey(command.Body.Id)) + { + return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.DuplicateBody); + } + + SpawnCore(command.Body); + return AcceptAndStore(command.Header, fingerprint, "body.spawn"); + } + } + + public YmirCommandReceipt Remove(YmirRemoveBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.remove", writer => WriteString(writer, command.BodyId)); + if (Preflight(command.Header, fingerprint, "body.remove") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.remove", fingerprint); + } + if (string.IsNullOrWhiteSpace(command.BodyId) || + !_activeKeysById.TryGetValue(command.BodyId, out var key)) + { + return RejectAndStore(command.Header, fingerprint, "body.remove", YmirCommandError.UnknownBody); + } + + RunNative(() => + { + _native.Remove(key); + _activeKeysById.Remove(command.BodyId); + _bodies.Remove(command.BodyId); + }); + return AcceptAndStore(command.Header, fingerprint, "body.remove"); + } + } + + public YmirCommandReceipt Teleport(YmirTeleportBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.teleport", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.Position); + Write(writer, command.Direction); + }); + if (Preflight(command.Header, fingerprint, "body.teleport") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.teleport", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.UnknownBody); + } + if (!Finite(command.Position) || !ValidDirection(command.Direction)) + { + return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.InvalidCommand); + } + + var direction = Normalize(command.Direction); + RunNative(() => + { + _native.Teleport(key, command.Position.X, command.Position.Y, direction.X, direction.Y); + _bodies[command.BodyId] = body with { Position = command.Position, Direction = direction }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.teleport"); + } + } + + public YmirCommandReceipt SetVelocity(YmirSetBodyVelocityCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.set_velocity", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.LinearVelocity); + writer.Write(command.AngularVelocity); + }); + if (Preflight(command.Header, fingerprint, "body.set_velocity") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.set_velocity", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.StaticBody); + } + if (!Finite(command.LinearVelocity) || !float.IsFinite(command.AngularVelocity)) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.InvalidCommand); + } + + RunNative(() => + { + _native.SetVelocity(key, command.LinearVelocity.X, command.LinearVelocity.Y, command.AngularVelocity); + _bodies[command.BodyId] = body with + { + Velocity = command.LinearVelocity, + AngularVelocity = command.AngularVelocity + }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.set_velocity"); + } + } + + public YmirCommandReceipt Configure(YmirConfigureBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.configure", writer => + { + WriteString(writer, command.BodyId); + writer.Write(command.Radius); + writer.Write(command.Mass); + writer.Write(command.IsStatic); + writer.Write(command.Restitution); + }); + if (Preflight(command.Header, fingerprint, "body.configure") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.configure", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.UnknownBody); + } + if (!float.IsFinite(command.Radius) || command.Radius <= 0.0f || + !float.IsFinite(command.Mass) || (!command.IsStatic && command.Mass <= 0.0f) || + !float.IsFinite(command.Restitution) || command.Restitution < 0.0f) + { + return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.InvalidCommand); + } + + RunNative(() => + { + _native.Configure(key, command.Radius, command.Mass, command.Restitution, command.IsStatic); + _bodies[command.BodyId] = body with + { + Radius = command.Radius, + Mass = command.Mass, + IsStatic = command.IsStatic, + Restitution = command.Restitution + }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.configure"); + } + } + + public YmirCommandReceipt ApplyForce(YmirApplyForceCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.apply_force", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.Force); + }); + if (Preflight(command.Header, fingerprint, "body.apply_force") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.apply_force", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.StaticBody); + } + if (!Finite(command.Force)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.InvalidCommand); + } + + RunNative(() => _native.ApplyForce(key, command.Force.X, command.Force.Y)); + return AcceptAndStore(command.Header, fingerprint, "body.apply_force"); + } + } + + public YmirCommandReceipt ApplyTorque(YmirApplyTorqueCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.apply_torque", writer => + { + WriteString(writer, command.BodyId); + writer.Write(command.Torque); + }); + if (Preflight(command.Header, fingerprint, "body.apply_torque") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.apply_torque", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.StaticBody); + } + if (!float.IsFinite(command.Torque)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.InvalidCommand); + } + + RunNative(() => _native.ApplyTorque(key, command.Torque)); + return AcceptAndStore(command.Header, fingerprint, "body.apply_torque"); + } + } + + public YmirSessionStepResult Step(YmirStepSessionCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var submittedFields = command.Fields; + var fieldsValid = submittedFields != null && FieldsAreValid(submittedFields); + var orderedFields = fieldsValid + ? submittedFields!.OrderBy(field => field.Id, StringComparer.Ordinal).ToArray() + : []; + var fingerprint = Fingerprint(command.Header, "session.step", writer => + { + writer.Write(command.DeltaTime); + writer.Write(command.SubstepCount); + if (submittedFields == null) + { + writer.Write(-1); + return; + } + var fields = fieldsValid ? orderedFields : submittedFields; + writer.Write(fields.Count); + foreach (var field in fields) + { + WriteField(writer, field); + } + }); + if (Preflight(command.Header, fingerprint, "session.step") is { } previous) + { + if (previous.Result is YmirSessionStepResult replay) + { + return replay; + } + var rejected = ReceiptFrom(previous, command.Header, "session.step", fingerprint); + return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []); + } + if (!float.IsFinite(command.DeltaTime) || command.DeltaTime <= 0.0f || + command.SubstepCount <= 0 || !fieldsValid) + { + var rejected = RejectAndStore(command.Header, fingerprint, "session.step", YmirCommandError.InvalidCommand); + return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []); + } + + var nativeFields = orderedFields + .Select(field => new Box3DField(field.Position.X, field.Position.Y, field.Strength, field.Radius)) + .ToArray(); + YmirContactFact[] facts; + try + { + _native.Step(command.DeltaTime, nativeFields, command.SubstepCount); + UpdateBodyProjection(_native.CopyBodies()); + _time += command.DeltaTime; + _fields = orderedFields; + _stepIndex += 1; + _revision += 1; + facts = ProjectFacts(_native.CopyContactEvents()).ToArray(); + PruneRetiredIdentity(); + } + catch + { + Poison(); + throw; + } + try + { + var receipt = AcceptedReceipt(command.Header, "session.step", _revision - 1, _revision, + facts.Select(fact => fact.FactId).ToArray()); + var result = new YmirSessionStepResult(receipt, SnapshotCore(), _revision, _stepIndex, facts); + _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, result)); + return result; + } + catch + { + Poison(); + throw; + } + } + } + + public YmirWorld Snapshot() + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + return SnapshotCore(); + } + } + + public YmirCommandReceipt Dispose(YmirDisposeSessionCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "session.dispose", _ => { }); + if (Preflight(command.Header, fingerprint, "session.dispose") is { } previous) + { + return ReceiptFrom(previous, command.Header, "session.dispose", fingerprint); + } + + var before = _revision; + _native.Dispose(); + _disposed = true; + _revision += 1; + var receipt = AcceptedReceipt(command.Header, "session.dispose", before, _revision, []); + _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) + { + return; + } + _native.Dispose(); + _disposed = true; + } + } + + private void SpawnCore(PhysicsBody body) + { + var key = NextKey(); + var generation = _nextBodyGeneration++; + var canonicalBody = body with { Torque = 0.0f, Direction = DirectionOrDefault(body.Direction) }; + RunNative(() => + { + _native.Spawn(ToNative(key, canonicalBody)); + _activeKeysById.Add(canonicalBody.Id, key); + _idsByKey.Add(key, canonicalBody.Id); + _generationsByKey.Add(key, generation); + _bodies.Add(canonicalBody.Id, canonicalBody); + }); + } + + private IReadOnlyList ProjectFacts(IReadOnlyList nativeFacts) + { + var projected = new List(nativeFacts.Count); + var ephemeralEpisodes = new Dictionary(); + var newEpisodeOrdinals = new Dictionary(); + var factOrdinals = new Dictionary<( + ContactPair Pair, + long StartStep, + long EpisodeOrdinal, + YmirContactFactKind Kind), int>(); + foreach (var native in nativeFacts) + { + var canonical = CanonicalizeContact(native); + var pair = new ContactPair( + canonical.BodyA, + canonical.BodyAGeneration, + canonical.BodyB, + canonical.BodyBGeneration); + ActiveEpisode episode; + if (native.Kind == Box3DContactKind.Begin) + { + if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!)) + { + episode = NewEpisode(pair, newEpisodeOrdinals); + _episodesByNativeContact[native.ContactKey] = episode; + } + } + else if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!) && + !ephemeralEpisodes.TryGetValue(native.ContactKey, out episode!)) + { + episode = NewEpisode(pair, newEpisodeOrdinals); + ephemeralEpisodes.Add(native.ContactKey, episode); + } + + var kind = native.Kind switch + { + Box3DContactKind.Begin => YmirContactFactKind.Begin, + Box3DContactKind.Hit => YmirContactFactKind.Hit, + Box3DContactKind.End => YmirContactFactKind.End, + _ => throw new InvalidOperationException($"Unknown Box3D contact fact kind {native.Kind}.") + }; + var ordinalKey = (pair, episode.StartStepIndex, episode.Ordinal, kind); + var ordinal = factOrdinals.GetValueOrDefault(ordinalKey); + factOrdinals[ordinalKey] = ordinal + 1; + var pairId = PairId(pair); + var contactId = $"{_sessionGeneration}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}"; + var factId = $"{_sessionGeneration}:step:{_stepIndex}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}:{kind.ToString().ToLowerInvariant()}:{ordinal}"; + var hasDetails = native.HasDetails; + var fact = new YmirContactFact( + factId, + contactId, + kind, + _sessionId, + _sessionGeneration, + _stepIndex, + canonical.BodyA, + canonical.BodyAGeneration, + canonical.BodyB, + canonical.BodyBGeneration, + hasDetails ? canonical.Point : null, + hasDetails ? canonical.Normal : null, + hasDetails ? native.Penetration : null, + hasDetails ? native.RelativeSpeed : null); + projected.Add(new ProjectedFact(fact, episode.StartStepIndex, episode.Ordinal, ordinal)); + + if (native.Kind == Box3DContactKind.End) + { + _episodesByNativeContact.Remove(native.ContactKey); + ephemeralEpisodes.Remove(native.ContactKey); + } + } + + return projected + .OrderBy(item => item.Fact.BodyA, StringComparer.Ordinal) + .ThenBy(item => item.Fact.BodyAGeneration) + .ThenBy(item => item.Fact.BodyB, StringComparer.Ordinal) + .ThenBy(item => item.Fact.BodyBGeneration) + .ThenBy(item => item.EpisodeStartStep) + .ThenBy(item => item.EpisodeOrdinal) + .ThenBy(item => FactKindOrder(item.Fact.Kind)) + .ThenBy(item => item.Ordinal) + .Select(item => item.Fact) + .ToArray(); + } + + private CanonicalContact CanonicalizeContact(Box3DContactFact fact) + { + var idA = ResolveId(fact.StableIdA); + var idB = ResolveId(fact.StableIdB); + var generationA = _generationsByKey[fact.StableIdA]; + var generationB = _generationsByKey[fact.StableIdB]; + var swap = StringComparer.Ordinal.Compare(idA, idB) > 0 || + (StringComparer.Ordinal.Equals(idA, idB) && generationA > generationB); + return swap + ? new CanonicalContact( + idB, generationB, idA, generationA, + new Vec2(fact.PointX, fact.PointZ), + new Vec2(-fact.NormalX, -fact.NormalZ)) + : new CanonicalContact( + idA, generationA, idB, generationB, + new Vec2(fact.PointX, fact.PointZ), + new Vec2(fact.NormalX, fact.NormalZ)); + } + + private void UpdateBodyProjection(IReadOnlyList states) + { + foreach (var state in states) + { + var id = ResolveId(state.StableId); + if (!_bodies.TryGetValue(id, out var body) || _activeKeysById.GetValueOrDefault(id) != state.StableId) + { + throw new InvalidOperationException($"Box3D returned inactive body key {state.StableId}."); + } + _bodies[id] = body with + { + Position = new Vec2(state.PositionX, state.PositionZ), + Velocity = new Vec2(state.VelocityX, state.VelocityZ), + Direction = new Vec2(state.DirectionX, state.DirectionZ), + AngularVelocity = state.AngularVelocity, + Torque = 0.0f + }; + } + } + + private LedgerEntry? Preflight(YmirCommandHeader header, string fingerprint, string kind) + { + ValidateHeader(header); + if (_ledger.TryGetValue(header.CommandId, out var existing)) + { + return existing.Fingerprint == fingerprint + ? existing + : new LedgerEntry(fingerprint, ConflictReceipt(header, kind, fingerprint)); + } + if (_faulted) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionFaulted); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + if (_disposed) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionDisposed); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + if (header.ExpectedRevision != _revision) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.StaleRevision); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + return null; + } + + private YmirCommandReceipt ReceiptFrom( + LedgerEntry entry, + YmirCommandHeader header, + string kind, + string fingerprint) + { + if (entry.Fingerprint != fingerprint) + { + return RejectedReceipt(header, kind, YmirCommandError.CommandIdConflict); + } + return entry.Result switch + { + YmirCommandReceipt receipt => receipt, + YmirSessionStepResult step => step.Receipt, + _ => throw new InvalidOperationException("Unknown Ymir receipt ledger entry.") + }; + } + + private YmirCommandReceipt AcceptAndStore(YmirCommandHeader header, string fingerprint, string kind) + { + try + { + var before = _revision; + _revision += 1; + var receipt = AcceptedReceipt(header, kind, before, _revision, []); + _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + catch + { + Poison(); + throw; + } + } + + private YmirCommandReceipt RejectAndStore( + YmirCommandHeader header, + string fingerprint, + string kind, + YmirCommandError error) + { + var receipt = RejectedReceipt(header, kind, error); + _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + + private YmirCommandReceipt AcceptedReceipt( + YmirCommandHeader header, + string kind, + long before, + long after, + IReadOnlyList facts) => + new( + $"{_sessionGeneration}:receipt:{header.CommandId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Accepted, + YmirCommandError.None, + before, + after, + _stepIndex, + facts); + + private YmirCommandReceipt RejectedReceipt( + YmirCommandHeader header, + string kind, + YmirCommandError error) => + new( + $"{_sessionGeneration}:receipt:{header.CommandId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Rejected, + error, + _revision, + _revision, + _stepIndex, + []); + + private YmirCommandReceipt ConflictReceipt( + YmirCommandHeader header, + string kind, + string fingerprint) + { + var conflictId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint))) + .ToLowerInvariant(); + return new YmirCommandReceipt( + $"{_sessionGeneration}:receipt-conflict:{header.CommandId}:{conflictId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Rejected, + YmirCommandError.CommandIdConflict, + _revision, + _revision, + _stepIndex, + []); + } + + private YmirWorld SnapshotCore() => new( + _time, + _bodies.Values.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray(), + _fields.ToArray()); + + private bool TryBody(string? id, out ulong key, out PhysicsBody body) + { + if (!string.IsNullOrWhiteSpace(id) && + _activeKeysById.TryGetValue(id, out key) && + _bodies.TryGetValue(id, out body!)) + { + return true; + } + key = 0; + body = null!; + return false; + } + + private string ResolveId(ulong key) => _idsByKey.TryGetValue(key, out var id) + ? id + : throw new InvalidOperationException($"Box3D returned unknown stable body key {key}."); + + private ActiveEpisode NewEpisode(ContactPair pair, IDictionary ordinals) + { + var ordinal = (ordinals.TryGetValue(pair, out var previous) ? previous : 0) + 1; + ordinals[pair] = ordinal; + return new ActiveEpisode(_stepIndex, ordinal, pair); + } + + private void PruneRetiredIdentity() + { + var activeKeys = _activeKeysById.Values.ToHashSet(); + foreach (var key in _idsByKey.Keys.Where(key => !activeKeys.Contains(key)).ToArray()) + { + var id = _idsByKey[key]; + var generation = _generationsByKey[key]; + if (_episodesByNativeContact.Values.Any(active => + (active.Pair.BodyA == id && active.Pair.BodyAGeneration == generation) || + (active.Pair.BodyB == id && active.Pair.BodyBGeneration == generation))) + { + throw new InvalidOperationException( + $"Box3D did not close every contact episode for removed body '{id}' generation {generation}."); + } + _idsByKey.Remove(key); + _generationsByKey.Remove(key); + } + } + + private void RunNative(Action operation) + { + try + { + operation(); + } + catch + { + Poison(); + throw; + } + } + + private void Poison() + { + _native.Dispose(); + _disposed = true; + _faulted = true; + } + + private ulong NextKey() + { + if (_nextNativeKey == 0) + { + throw new InvalidOperationException("Ymir exhausted its native body key space."); + } + return _nextNativeKey++; + } + + private static Box3DBody ToNative(ulong key, PhysicsBody body) + { + var direction = DirectionOrDefault(body.Direction); + return new Box3DBody( + key, + body.Position.X, + body.Position.Y, + body.Velocity.X, + body.Velocity.Y, + direction.X, + direction.Y, + body.AngularVelocity, + 0.0f, + body.Radius, + body.Mass, + body.Restitution, + body.IsStatic); + } + + private static Vec2 DirectionOrDefault(Vec2? direction) => + direction is { } value && ValidDirection(value) ? Normalize(value) : new Vec2(0.0f, 1.0f); + + private static Vec2 Normalize(Vec2 value) + { + var inverseLength = 1.0f / MathF.Sqrt(value.X * value.X + value.Y * value.Y); + return new Vec2(value.X * inverseLength, value.Y * inverseLength); + } + + private static void ValidateHeader(YmirCommandHeader header) + { + ArgumentNullException.ThrowIfNull(header); + if (string.IsNullOrWhiteSpace(header.CommandId)) + { + throw new ArgumentException("Command id is required.", nameof(header)); + } + if (header.ExpectedRevision < 0) + { + throw new ArgumentOutOfRangeException(nameof(header), "Expected revision must be non-negative."); + } + } + + private static void ValidateUniqueBodyIds(IReadOnlyList bodies) + { + var ids = new HashSet(StringComparer.Ordinal); + foreach (var body in bodies) + { + if (!ids.Add(body.Id)) + { + throw new ArgumentException($"Ymir body id '{body.Id}' occurs more than once.", nameof(bodies)); + } + } + } + + private static bool TryValidateBody(PhysicsBody body, bool allowTorque) + { + try + { + ValidateBody(body, allowTorque); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + private static void ValidateBody(PhysicsBody body, bool allowTorque) + { + ArgumentNullException.ThrowIfNull(body); + if (string.IsNullOrWhiteSpace(body.Id) || !Finite(body.Position) || !Finite(body.Velocity) || + !float.IsFinite(body.Radius) || body.Radius <= 0.0f || + !float.IsFinite(body.Mass) || (!body.IsStatic && body.Mass <= 0.0f) || + !float.IsFinite(body.Restitution) || body.Restitution < 0.0f || + (body.Direction is { } direction && !ValidDirection(direction)) || + !float.IsFinite(body.AngularVelocity) || !float.IsFinite(body.Torque) || + (!allowTorque && body.Torque != 0.0f)) + { + throw new ArgumentException("Body definition is not valid for a retained Ymir session.", nameof(body)); + } + } + + private static bool FieldsAreValid(IReadOnlyList fields) + { + var ids = new HashSet(StringComparer.Ordinal); + return fields.All(field => field != null && + !string.IsNullOrWhiteSpace(field.Id) && ids.Add(field.Id) && Finite(field.Position) && + float.IsFinite(field.Strength) && float.IsFinite(field.Radius) && field.Radius >= 0.0f); + } + + private static bool Finite(Vec2 value) => float.IsFinite(value.X) && float.IsFinite(value.Y); + + private static bool ValidDirection(Vec2 value) => + Finite(value) && value.X * value.X + value.Y * value.Y > 1.0e-8f; + + private static string Fingerprint( + YmirCommandHeader header, + string kind, + Action writePayload) + { + using var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(1); + WriteString(writer, kind); + writer.Write(header.ExpectedRevision); + writePayload(writer); + } + return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))) + .ToLowerInvariant(); + } + + private static void WriteBody(BinaryWriter writer, PhysicsBody? body) + { + writer.Write(body != null); + if (body == null) + { + return; + } + WriteString(writer, body.Id); + Write(writer, body.Position); + Write(writer, body.Velocity); + writer.Write(body.Radius); + writer.Write(body.Mass); + writer.Write(body.IsStatic); + writer.Write(body.Restitution); + writer.Write(body.Direction.HasValue); + if (body.Direction is { } direction) + { + Write(writer, direction); + } + writer.Write(body.AngularVelocity); + writer.Write(body.Torque); + } + + private static void WriteField(BinaryWriter writer, RadialField? field) + { + writer.Write(field != null); + if (field == null) + { + return; + } + WriteString(writer, field.Id); + Write(writer, field.Position); + writer.Write(field.Strength); + writer.Write(field.Radius); + } + + private static void Write(BinaryWriter writer, Vec2 value) + { + writer.Write(value.X); + writer.Write(value.Y); + } + + private static void WriteString(BinaryWriter writer, string? value) + { + writer.Write(value != null); + if (value != null) + { + writer.Write(value); + } + } + + private static string PairId(ContactPair pair) + { + var source = $"{pair.BodyA.Length}:{pair.BodyA}:{pair.BodyAGeneration}:{pair.BodyB.Length}:{pair.BodyB}:{pair.BodyBGeneration}"; + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source))).ToLowerInvariant(); + } + + private static int FactKindOrder(Box3DContactKind kind) => kind switch + { + Box3DContactKind.Begin => 0, + Box3DContactKind.Hit => 1, + Box3DContactKind.End => 2, + _ => 3 + }; + + private static int FactKindOrder(YmirContactFactKind kind) => kind switch + { + YmirContactFactKind.Begin => 0, + YmirContactFactKind.Hit => 1, + YmirContactFactKind.End => 2, + _ => 3 + }; + + private sealed record LedgerEntry(string Fingerprint, object Result); + + private sealed record ContactPair(string BodyA, long BodyAGeneration, string BodyB, long BodyBGeneration); + + private sealed record ActiveEpisode(long StartStepIndex, long Ordinal, ContactPair Pair); + + private sealed record ProjectedFact( + YmirContactFact Fact, + long EpisodeStartStep, + long EpisodeOrdinal, + int Ordinal); + + private sealed record CanonicalContact( + string BodyA, + long BodyAGeneration, + string BodyB, + long BodyBGeneration, + Vec2 Point, + Vec2 Normal); +} diff --git a/tests/Ymir.Box3D.Parity/Box3DOracle.cs b/tests/Ymir.Box3D.Parity/Box3DOracle.cs index beb1d58..43a98be 100644 --- a/tests/Ymir.Box3D.Parity/Box3DOracle.cs +++ b/tests/Ymir.Box3D.Parity/Box3DOracle.cs @@ -59,6 +59,47 @@ internal static partial class Box3DOracle [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DTorqueResult ymir_box3d_torque_lifetime(float torque, float timeStep, int subStepCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial uint ymir_box3d_get_abi_version(); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_create(out nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial void ymir_box3d_session_destroy(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_spawn(nint session, Box3DSessionBodyInput* body); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_remove(nint session, ulong stableId); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_step( + nint session, + float deltaTime, + int substepCount, + void* fields, + int fieldCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_contact_event_count(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_copy_contact_events( + nint session, + Box3DSessionContactEvent* events, + int capacity, + out int written); } [StructLayout(LayoutKind.Sequential)] @@ -109,3 +150,35 @@ internal readonly record struct Box3DPairStepResult( internal readonly record struct Box3DTorqueResult( float AngularVelocityAfterAppliedStep, float AngularVelocityAfterUnforcedStep); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DSessionBodyInput( + ulong StableId, + float PositionX, + float PositionY, + float VelocityX, + float VelocityY, + float DirectionX, + float DirectionY, + float AngularVelocity, + float Torque, + float Radius, + float Mass, + float Restitution, + uint IsStatic); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DSessionContactEvent( + int Kind, + uint HasDetails, + uint ContactId0, + uint ContactId1, + uint ContactId2, + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointY, + float NormalX, + float NormalY, + float Penetration, + float RelativeSpeed); diff --git a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs index 828c501..7d68ca3 100644 --- a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs +++ b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs @@ -120,4 +120,51 @@ public sealed class Box3DParityTests result.AngularVelocityAfterUnforcedStep, precision: 5); } + + [Fact] + public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle() + { + Assert.Equal(3u, Box3DOracle.ymir_box3d_get_abi_version()); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session)); + try + { + var bodyA = new Box3DSessionBodyInput( + 1, -0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); + var bodyB = new Box3DSessionBodyInput( + 2, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyB)); + Assert.Equal(2, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); + Assert.Equal(1, Box3DOracle.ymir_box3d_session_remove(session, 999)); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + var beginEvents = CopyEvents(session); + var begin = Assert.Single(beginEvents, value => value.Kind == 1); + Assert.Equal(new HashSet { 1, 2 }, new HashSet { begin.StableIdA, begin.StableIdB }); + Assert.Equal(1u, begin.HasDetails); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_remove(session, 2)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + var end = Assert.Single(CopyEvents(session), value => value.Kind == 3); + Assert.Equal(new HashSet { 1, 2 }, new HashSet { end.StableIdA, end.StableIdB }); + Assert.Equal(0u, end.HasDetails); + } + finally + { + Box3DOracle.ymir_box3d_session_destroy(session); + } + } + + private static unsafe Box3DSessionContactEvent[] CopyEvents(nint session) + { + var count = Box3DOracle.ymir_box3d_session_get_contact_event_count(session); + Assert.True(count >= 0); + var events = new Box3DSessionContactEvent[count]; + fixed (Box3DSessionContactEvent* pointer = events) + { + Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_contact_events(session, pointer, count, out var written)); + Assert.Equal(count, written); + } + return events; + } } diff --git a/tests/Ymir.Tests/YmirServicePublicationTests.cs b/tests/Ymir.Tests/YmirServicePublicationTests.cs index d06be58..3668aed 100644 --- a/tests/Ymir.Tests/YmirServicePublicationTests.cs +++ b/tests/Ymir.Tests/YmirServicePublicationTests.cs @@ -17,7 +17,9 @@ public sealed class YmirServicePublicationTests Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal); Assert.Contains("Box3D-only isolated snapshot stepping", advertisement.Owns); - Assert.Contains("public retained session lifecycle yet", advertisement.DoesNotOwn); + Assert.Contains("public in-process retained sessions with explicit mutation receipts", advertisement.Owns); + Assert.Contains("typed Begin, Hit, and End contact facts for retained steps", advertisement.Owns); + Assert.Contains("daemon-owned named session registry or CultMesh command lowering yet", advertisement.DoesNotOwn); Assert.Empty(advertisement.CommandLowerings); Assert.Contains("Box3D solver and collision semantics", advertisement.DoesNotOwn); Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate); diff --git a/tests/Ymir.Tests/YmirSessionTests.cs b/tests/Ymir.Tests/YmirSessionTests.cs new file mode 100644 index 0000000..662a250 --- /dev/null +++ b/tests/Ymir.Tests/YmirSessionTests.cs @@ -0,0 +1,215 @@ +using Ymir.Core; + +namespace Ymir.Tests; + +public sealed class YmirSessionTests +{ + [Fact] + public void RetainedBodyAdvancesWithoutSnapshotResubmission() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "retained-motion", + [Body("ship", positionX: 0.0f, velocityX: 2.0f)])); + + var first = session.Step(Step("step-1", 0, 0.25f)); + var second = session.Step(Step("step-2", 1, 0.25f)); + + Assert.Equal(YmirCommandOutcome.Accepted, first.Receipt.Outcome); + Assert.Equal(1, first.Revision); + Assert.Equal(2, second.Revision); + Assert.Equal(2, second.StepIndex); + Assert.True(second.World.Bodies.Single().Position.X > first.World.Bodies.Single().Position.X); + Assert.Equal(2.0f, second.World.Bodies.Single().Velocity.X, 4); + } + + [Fact] + public void ForceReceiptIsIdempotentAndForceIsConsumedByOneStep() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("force-once", [Body("ship")])); + var command = new YmirApplyForceCommand(Header("force", 0), "ship", new Vec2(10.0f, 0.0f)); + + var accepted = session.ApplyForce(command); + var replay = session.ApplyForce(command); + var conflict = session.ApplyForce(command with { Force = new Vec2(20.0f, 0.0f) }); + var revisionConflict = session.ApplyForce(command with { Header = Header("force", 1) }); + var forced = session.Step(Step("step-forced", 1, 0.1f)); + var unforced = session.Step(Step("step-unforced", 2, 0.1f)); + + Assert.Same(accepted, replay); + Assert.Equal(1, accepted.AfterRevision); + Assert.Equal(2, session.Info.StepIndex); + Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error); + Assert.Equal(YmirCommandOutcome.Rejected, conflict.Outcome); + Assert.NotEqual(accepted.ReceiptId, conflict.ReceiptId); + Assert.Equal(YmirCommandError.CommandIdConflict, revisionConflict.Error); + Assert.Equal(forced.World.Bodies.Single().Velocity.X, unforced.World.Bodies.Single().Velocity.X, 4); + } + + [Fact] + public void OmissionCannotRemoveBodyAndRemoveIsExplicit() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "explicit-remove", + [Body("a"), Body("b", positionX: 10.0f)])); + + var velocity = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("set-a", 0), "a", new Vec2(1.0f, 0.0f), 0.0f)); + var stepped = session.Step(Step("step", 1, 0.1f)); + var removed = session.Remove(new YmirRemoveBodyCommand(Header("remove-b", 2), "b")); + + Assert.Equal(YmirCommandOutcome.Accepted, velocity.Outcome); + Assert.Equal(2, stepped.World.Bodies.Count); + Assert.Equal(YmirCommandOutcome.Accepted, removed.Outcome); + Assert.Equal(["a"], session.Snapshot().Bodies.Select(body => body.Id).ToArray()); + } + + [Fact] + public void ContactEpisodeEmitsBeginThenEndThenNewBegin() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "contact-lifecycle", + [ + Body("a", positionX: 0.0f, isStatic: true), + Body("b", positionX: 1.5f) + ])); + + var began = session.Step(Step("begin", 0, 0.01f)); + var persistent = session.Step(Step("persistent", 1, 0.01f)); + session.Teleport(new YmirTeleportBodyCommand( + Header("separate", 2), "b", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f))); + var ended = session.Step(Step("end", 3, 0.01f)); + session.Teleport(new YmirTeleportBodyCommand( + Header("return", 4), "b", new Vec2(1.5f, 0.0f), new Vec2(0.0f, 1.0f))); + var beganAgain = session.Step(Step("begin-again", 5, 0.01f)); + + var firstBegin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + var end = Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End); + var secondBegin = Assert.Single(beganAgain.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + Assert.Equal(firstBegin.ContactId, end.ContactId); + Assert.NotEqual(firstBegin.ContactId, secondBegin.ContactId); + Assert.Equal("a", firstBegin.BodyA); + Assert.Equal("b", firstBegin.BodyB); + } + + [Fact] + public void RemoveAndRecreateChangesBodyGeneration() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "body-generation", + [Body("wall", isStatic: true), Body("pickup", positionX: 1.5f)])); + var first = session.Step(Step("begin-1", 0, 0.01f)); + var firstFact = Assert.Single(first.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + session.Remove(new YmirRemoveBodyCommand(Header("remove", 1), "pickup")); + var removed = session.Step(Step("removed", 2, 0.01f)); + session.Spawn(new YmirSpawnBodyCommand(Header("spawn", 3), Body("pickup", positionX: 1.5f))); + var second = session.Step(Step("begin-2", 4, 0.01f)); + var secondFact = Assert.Single(second.ContactFacts, fact => + fact.Kind == YmirContactFactKind.Begin && + (fact.BodyA == "pickup" || fact.BodyB == "pickup")); + + var firstGeneration = BodyGeneration(firstFact, "pickup"); + Assert.Contains(removed.ContactFacts, fact => + fact.Kind == YmirContactFactKind.End && fact.ContactId == firstFact.ContactId); + Assert.True(BodyGeneration(secondFact, "pickup") > firstGeneration); + Assert.NotEqual(firstFact.ContactId, secondFact.ContactId); + } + + [Fact] + public void SnapshotImmediatelyReflectsCanonicalNativeMutationState() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "canonical-snapshot", + [Body("ship") with { Direction = new Vec2(0.0f, 2.0f) }])); + + Assert.Equal(new Vec2(0.0f, 1.0f), session.Snapshot().Bodies.Single().Direction); + session.Teleport(new YmirTeleportBodyCommand( + Header("teleport", 0), "ship", new Vec2(3.0f, 4.0f), new Vec2(2.0f, 0.0f))); + var teleported = session.Snapshot().Bodies.Single(); + Assert.Equal(1.0f, teleported.Direction!.Value.X, 5); + Assert.Equal(0.0f, teleported.Direction.Value.Y, 5); + Assert.Equal(new Vec2(3.0f, 4.0f), teleported.Position); + + session.Configure(new YmirConfigureBodyCommand( + Header("static", 1), "ship", 2.0f, 1.0f, true, 0.5f)); + var configured = session.Snapshot().Bodies.Single(); + Assert.True(configured.IsStatic); + Assert.Equal(2.0f, configured.Radius); + Assert.Equal(0.5f, configured.Restitution); + } + + [Fact] + public void StaleAndDisposedCommandsFailClosedWithoutMutation() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("stale", [Body("ship")])); + var accepted = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("accepted", 0), "ship", new Vec2(1.0f, 0.0f), 0.0f)); + var stale = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("stale", 0), "ship", new Vec2(100.0f, 0.0f), 0.0f)); + var disposed = session.Dispose(new YmirDisposeSessionCommand(Header("dispose", 1))); + var afterDispose = session.Remove(new YmirRemoveBodyCommand(Header("late", 2), "ship")); + + Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome); + Assert.Equal(YmirCommandError.StaleRevision, stale.Error); + Assert.Equal(YmirCommandOutcome.Accepted, disposed.Outcome); + Assert.Equal(YmirCommandError.SessionDisposed, afterDispose.Error); + Assert.Equal(2, afterDispose.BeforeRevision); + Assert.Equal(afterDispose.BeforeRevision, afterDispose.AfterRevision); + } + + [Fact] + public void TypedFingerprintRejectsDelimiterCollisionsAndNullPayloads() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("fingerprints", [])); + var accepted = session.Spawn(new YmirSpawnBodyCommand( + Header("spawn", 0), Body("body|with|delimiters"))); + var conflict = session.Spawn(new YmirSpawnBodyCommand( + Header("spawn", 0), Body("body") with { Position = new Vec2(1.0f, 2.0f) })); + var nullBody = session.Spawn(new YmirSpawnBodyCommand(Header("null-body", 1), null!)); + var nullFields = session.Step(new YmirStepSessionCommand(Header("null-fields", 1), 0.1f, null!)); + + Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome); + Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error); + Assert.Equal(YmirCommandError.InvalidCommand, nullBody.Error); + Assert.Equal(YmirCommandError.InvalidCommand, nullFields.Receipt.Error); + Assert.Equal(1, session.Info.Revision); + } + + [Fact] + public void StaticBodyVelocityCommandIsRejectedWithoutARevisionLie() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "static-velocity", [Body("wall", isStatic: true)])); + + var receipt = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("move-wall", 0), "wall", new Vec2(10.0f, 0.0f), 2.0f)); + + Assert.Equal(YmirCommandOutcome.Rejected, receipt.Outcome); + Assert.Equal(YmirCommandError.StaticBody, receipt.Error); + Assert.Equal(0, session.Info.Revision); + Assert.Equal(Vec2.Zero, session.Snapshot().Bodies.Single().Velocity); + } + + private static YmirCommandHeader Header(string id, long revision) => new(id, revision); + + private static long BodyGeneration(YmirContactFact fact, string bodyId) => + fact.BodyA == bodyId ? fact.BodyAGeneration : fact.BodyBGeneration; + + private static YmirStepSessionCommand Step(string id, long revision, float deltaTime) => + new(Header(id, revision), deltaTime, []); + + private static PhysicsBody Body( + string id, + float positionX = 0.0f, + float velocityX = 0.0f, + bool isStatic = false) => + new( + id, + new Vec2(positionX, 0.0f), + new Vec2(velocityX, 0.0f), + 1.0f, + 1.0f, + isStatic, + 0.0f, + new Vec2(0.0f, 1.0f)); +}