Merge branch 'codex/directed-attractor' into codex/aetheria-box3d-integration
# Conflicts: # README.md # docs/architecture.md # docs/box3d-parity.md # src/Ymir.Core/Ymir.Core.csproj # src/Ymir.Core/YmirServicePublicationDocument.cs # tests/Ymir.Tests/YmirServicePublicationTests.cs
This commit is contained in:
commit
796908ed75
32 changed files with 5278 additions and 221 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -6,4 +6,4 @@ obj/
|
|||
*.user
|
||||
TestResults/
|
||||
BenchmarkDotNet.Artifacts/
|
||||
artifacts/box3d-native/
|
||||
artifacts/
|
||||
|
|
|
|||
Binary file not shown.
61
README.md
61
README.md
|
|
@ -18,14 +18,15 @@ Aetheria daemon owns every step, query, and contact fact.
|
|||
|
||||
- Box3D owns rigid-body integration, collision geometry, broadphase, solver
|
||||
behavior, continuous collision, overlap and cast semantics, contact
|
||||
lifecycle, force and torque lifetime, tolerances, and step behavior for an
|
||||
identical creation order and command stream under the accepted build and
|
||||
runtime configuration.
|
||||
- Ymir owns the pinned Box3D version, stable GameCult entity ids, native ABI
|
||||
isolation, long-lived world sessions, typed commands and facts,
|
||||
deterministic result ordering, checkpoint reconstruction, and the embedded
|
||||
session boundary. Its optional standalone service owns only its own
|
||||
publication and lifecycle.
|
||||
lifecycle, force and torque lifetime, tolerances, and deterministic step
|
||||
behavior for identical recorded inputs.
|
||||
- Ymir owns the pinned Box3D version, stable GameCult entity ids,
|
||||
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.
|
||||
- An optional Ymir daemon may own named session routing, durable command receipts,
|
||||
checkpoint reconstruction, CultMesh command/fact publication, and process
|
||||
supervision for worlds it hosts. It is not part of Aetheria's gameplay path.
|
||||
- Aetheria owns gameplay policy and supplies typed physical intent: bodies,
|
||||
fields, tractor targets, forces, projectiles, filters, and the gameplay
|
||||
consequences of Ymir contact facts.
|
||||
|
|
@ -68,15 +69,28 @@ parity suite already witness released Box3D behavior for:
|
|||
- contact-begin facts
|
||||
- restitution mixing
|
||||
- transient torque lifetime
|
||||
- category/mask/group collision filtering
|
||||
- bullet CCD against kinematic bodies, including Box3D's next-step contact-event timing
|
||||
|
||||
The legacy managed Ymir solver remains temporarily live while retained Box3D
|
||||
world sessions, end-contact lifecycle, continuous collision, replay, and
|
||||
checkpoint reconstruction are connected. It is compatibility scaffolding, not
|
||||
the target architecture. It will be deleted, along with Ymir's custom geometry
|
||||
and spatial indexes, once the Box3D-backed path proves the public contract.
|
||||
The production `Ymir.Box3D` boundary owns the native session ABI. The legacy
|
||||
snapshot `YmirSimulator.Step` contract now creates an isolated Box3D session,
|
||||
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 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. Aetheria
|
||||
embeds one session per run and zone; its old process-wide simulator objects
|
||||
are not session identifiers. Revision-checked
|
||||
retained-session circle overlap and cast queries observe the current stable-id
|
||||
body projection without mutating it. 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 shared by embedded and optional standalone hosts.
|
||||
|
||||
## Build And Test
|
||||
|
||||
|
|
@ -96,9 +110,22 @@ dotnet test tests\Ymir.Box3D.Parity\Ymir.Box3D.Parity.csproj
|
|||
|
||||
Box3D is MIT licensed. Its license is retained in `extern/box3d`.
|
||||
|
||||
`GameCult.Ymir.Box3D` packages the managed boundary, Box3D license, and native
|
||||
facade under `runtimes/<rid>/native`. A local Windows x64 package has loaded in
|
||||
an isolated empty consumer without CMake or the submodule. A committed release
|
||||
smoke is still required before that is a repeatable packaging guarantee. Linux
|
||||
and macOS packages must be produced and smoked on their own release workers
|
||||
before those RIDs are advertised.
|
||||
|
||||
The current package version is `0.3.0`. ABI v4 exposes Box3D body type,
|
||||
bullet, field-participation, and collision-filter configuration without
|
||||
exposing Box3D handles. These are Ymir contract fields, but their behavior is
|
||||
Box3D behavior.
|
||||
|
||||
## Cutover Rule
|
||||
|
||||
A Ymir cutover is complete only when all runtime stepping, collision queries,
|
||||
and contact facts come from a retained Box3D world through one Ymir session
|
||||
primitive. Manual Unity callbacks, Aetheria geometry tests, and the managed
|
||||
Ymir solver must be structurally unable to decide the result.
|
||||
and contact facts come from Box3D through an explicitly owned Ymir session.
|
||||
Manual Unity callbacks and Aetheria geometry tests must be structurally unable
|
||||
to decide the result. Snapshot compatibility calls may use isolated sessions;
|
||||
they are not allowed to infer or share retained-world identity.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/ymir-daemon/ymir-daemon.csproj" />
|
||||
<Project Path="src/Ymir.Box3D/Ymir.Box3D.csproj" />
|
||||
<Project Path="src/Ymir.Core/Ymir.Core.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
|
|
|
|||
|
|
@ -37,17 +37,30 @@ advertised Eve/CultMesh surface. Generic Eve clients connect directly to the
|
|||
Aetheria daemon. They never import Ymir internals and do not route gameplay
|
||||
through a standalone Ymir or discovery service.
|
||||
|
||||
A standalone Ymir daemon is a second hosting mode for physics tooling and
|
||||
A standalone Ymir daemon is an optional hosting mode for physics tooling and
|
||||
other products. It hosts the same Ymir session primitive; it is not an
|
||||
Aetheria relay and cannot own a shadow copy of Aetheria's world.
|
||||
|
||||
## Current Mechanism
|
||||
## Current Body
|
||||
|
||||
The native facade currently exists only as a bounded parity oracle. Each world
|
||||
step witness creates and destroys a short-lived Box3D world. Production
|
||||
`ymir-daemon` commands still call the transitional managed `YmirSimulator`; no
|
||||
retained Box3D world or live CultMesh provider session exists yet. The owner,
|
||||
dataflow, and persistence sections below describe the cutover target.
|
||||
The runtime solver cut is complete: Box3D is the only integrator, collision
|
||||
engine, broadphase, query-geometry implementation, and contact source in the
|
||||
committed Ymir path. The public `YmirSimulator.Step` compatibility API creates
|
||||
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 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, 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
|
||||
|
||||
|
|
@ -112,9 +125,19 @@ solver.
|
|||
## Target Shared Paths
|
||||
|
||||
Direct player commands, agent commands, programmatic spawns, server ticks,
|
||||
imports, reconnects, replay, and checkpoint recovery all enter one Ymir world
|
||||
session primitive. DTO compatibility methods may lower into that primitive;
|
||||
they may not run an alternate step.
|
||||
imports, reconnects, replay, and checkpoint recovery will enter the same Ymir
|
||||
session primitive for their named world. Today, DTO compatibility methods
|
||||
lower into an isolated Box3D session; they may not run an alternate step or
|
||||
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 creates, retains, and disposes the
|
||||
corresponding embedded Ymir session. Projectile sweep
|
||||
and stationary mine proximity integration can use Ymir's revision-checked
|
||||
retained-session circle-cast and overlap queries. They observe the current
|
||||
stable-id body projection; they do not invent a contact episode or mutate the
|
||||
Box3D world.
|
||||
|
||||
Radial gravity and tractor attraction are typed force-generation inputs. They
|
||||
are applied to Box3D before stepping. Pickup collection remains an Aetheria
|
||||
|
|
@ -152,6 +175,14 @@ lifecycle identity are binary contracts, not tolerance checks. Authoritative
|
|||
contact facts resume only after canonical history has been replayed through the
|
||||
checkpoint tick; a checkpoint alone cannot emit gameplay contact facts.
|
||||
|
||||
`gamecult.ymir.world_state.v2` appends Box3D body type, bullet,
|
||||
field-participation, and collision filter arrays to the v1 layout. The v1 and
|
||||
v0 readers are explicit migration paths; keys are not reassigned. Torque is
|
||||
transient command state and is intentionally absent. Version 2 is a
|
||||
compatibility world snapshot, not a complete retained-session
|
||||
checkpoint: it does not preserve full shape, material, filter, session tuning,
|
||||
provenance, or warm contact state.
|
||||
|
||||
Transient forces and torques are commands, not durable body state. Derived
|
||||
mass and inertia are published only when useful for inspection. Old checkpoint
|
||||
versions must migrate explicitly or fail closed; they may not silently decode
|
||||
|
|
@ -159,13 +190,15 @@ under a reassigned MessagePack layout.
|
|||
|
||||
## Cut Line
|
||||
|
||||
The managed Ymir solver, `YmirQueryPrimitives`, and `YmirSpatialIndex` are
|
||||
deleted when retained Box3D sessions prove:
|
||||
The managed integrator and circle impulse solver have been deleted from the
|
||||
runtime path. Any uncommitted `YmirQueryPrimitives` or `YmirSpatialIndex` work
|
||||
is obsolete and must not be annexed. The retained-session cut continues until
|
||||
Box3D-backed sessions prove:
|
||||
|
||||
1. fixed-step body state projection;
|
||||
2. begin/end/hit contact lifecycle;
|
||||
3. overlap and shape-cast lowering;
|
||||
4. continuous collision and projectile witnesses;
|
||||
4. continuous collision event timing and same-step Box3D cast witnesses;
|
||||
5. transient force and torque application;
|
||||
6. checkpoint reconstruction and replay;
|
||||
7. Aetheria gravity, tractor, pickup, and payload smokes.
|
||||
|
|
@ -180,7 +213,9 @@ failure fails closed and reports the missing capability.
|
|||
session facts.
|
||||
- Negative source checks prove custom solver and spatial-index authorities are
|
||||
absent after cutover.
|
||||
- Aetheria smokes prove gravity, contact-gated destruction loot, tractor
|
||||
attraction, pickup collection, and fast payload hits.
|
||||
- Aetheria smokes must prove gravity, contact-gated destruction loot, tractor
|
||||
attraction, pickup collection, and fast payload hits through the retained
|
||||
contract. Current gravity, pickup-contact, cast, and overlap witnesses cover
|
||||
only the snapshot/query compatibility path.
|
||||
- Released-client witnesses prove generic Eve clients only observe Ymir and
|
||||
Aetheria provider contracts, never native implementation details.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
## Authority
|
||||
|
||||
Box3D v0.1.0 is Ymir's physics implementation and executable semantics oracle.
|
||||
The production session cutover is still under construction. The exact upstream source is pinned as the
|
||||
The production native session ABI and snapshot lowering are live; explicit
|
||||
retained-world ownership is still being connected. The exact upstream source is pinned as the
|
||||
`extern/box3d` submodule at commit
|
||||
`8441b4a06d6d09dcfb0b0f704df4d847d1437b92`.
|
||||
|
||||
|
|
@ -15,11 +16,23 @@ torque lifetime, and numeric tolerances.
|
|||
## Body
|
||||
|
||||
`native/Ymir.Box3D` statically links the pinned C17 library into one small
|
||||
shared-library facade. The facade exports only blittable sphere overlap,
|
||||
sphere cast, capsule-versus-sphere membership, planar pair stepping, torque
|
||||
lifetime, and version operations. This keeps Box3D's alpha C ABI out of Ymir's
|
||||
shared-library facade. The facade exports retained sphere-world sessions plus
|
||||
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 4 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. 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.
|
||||
ABI v4 additionally carries Box3D static/kinematic/dynamic selection, bullet
|
||||
CCD, category/mask/group filtering, and per-body radial-field participation.
|
||||
|
||||
`tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with
|
||||
source-generated .NET interop. Run it with:
|
||||
|
||||
|
|
@ -47,13 +60,17 @@ is retained in the pinned submodule.
|
|||
- Restitution uses the maximum of the two shape materials.
|
||||
- Applied torque is transient and cleared by each world step; a continuous
|
||||
torque must be submitted again for the next step.
|
||||
- A negative Box3D group index suppresses collision within that group before
|
||||
category/mask evaluation. Category and mask bits then decide eligible pairs.
|
||||
- Bullet CCD against a kinematic target prevents traversal during the fast
|
||||
step, but Box3D v0.1.0 emits the typed contact event on the following step.
|
||||
Same-step gameplay triggering therefore requires an explicit Box3D shape
|
||||
cast; Ymir must not invent an earlier Begin event.
|
||||
|
||||
## Cut Line
|
||||
|
||||
The current managed collision formulas are transitional. They may exist only
|
||||
until differential coverage and production-session witnesses prove the public
|
||||
cutover contract. Missing production coverage includes retained world
|
||||
sessions, end/hit contact lifecycle, continuous collision, replay, checkpoint
|
||||
restart, and RID packaging. Once those facts are projected through a stable
|
||||
Ymir native port, the managed solver, query geometry, and spatial indexes are
|
||||
deleted rather than retained as fallback authority.
|
||||
The managed integrator and circle collision solver are no longer runtime
|
||||
authorities. The remaining parity slice covers explicit retained-world
|
||||
ownership, end-contact lifecycle, continuous collision, and replay. Custom
|
||||
query geometry and spatial indexes are not fallback authorities; Box3D owns
|
||||
those edge cases.
|
||||
|
|
|
|||
164
docs/retained-session-contract.md
Normal file
164
docs/retained-session-contract.md
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
# 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 session 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 maps 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, static/kinematic/dynamic 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 plus
|
||||
revision-checked circle overlap and cast queries. A query observes the current
|
||||
retained body projection under the session lock and accepts an explicit set of
|
||||
stable candidate body ids. The candidate set is product-owned eligibility;
|
||||
Box3D still owns the overlap/cast geometry and numeric result.
|
||||
Bullet, collision-filter, and field-participation profiles are currently
|
||||
spawn/restore definitions. Retained `Configure` changes radius, mass,
|
||||
static/kinematic/dynamic type, and restitution only. Changing the profile
|
||||
requires explicit remove-and-spawn until a typed profile command exists.
|
||||
|
||||
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.v2` 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 a durable reconnect 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 owning product's 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. Revision-checked retained-session overlap and cast queries: done.
|
||||
4. Embed one retained session per Aetheria run and zone, then delete its process-wide
|
||||
simulator identity, manual tractor geometry, per-projectile mini-worlds,
|
||||
and tuple contact dedup.
|
||||
5. For optional standalone hosting, add a session registry, generation-bearing
|
||||
routed commands, idempotent Create, durable receipts, and CultMesh lowering.
|
||||
|
||||
The isolated `YmirSimulator` remains a compatibility API. It is never the
|
||||
retained-world authority.
|
||||
|
||||
Mutation-generated End evidence is currently retained in the native pending
|
||||
buffer and published by the next accepted Step. The host 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.
|
||||
File diff suppressed because it is too large
Load diff
273
src/Ymir.Box3D/Box3DNative.cs
Normal file
273
src/Ymir.Box3D/Box3DNative.cs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal enum Box3DStatus
|
||||
{
|
||||
Ok = 0,
|
||||
InvalidArgument = 1,
|
||||
DuplicateId = 2,
|
||||
BufferTooSmall = 3,
|
||||
OutOfMemory = 4,
|
||||
InternalError = 5
|
||||
}
|
||||
|
||||
internal static partial class Box3DNative
|
||||
{
|
||||
internal const string LibraryName = "ymir_box3d";
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial uint ymir_box3d_get_abi_version();
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_get_abi_layout(
|
||||
out uint bodyInputSize,
|
||||
out uint fieldInputSize,
|
||||
out uint bodyOutputSize,
|
||||
out uint contactOutputSize,
|
||||
out uint contactEventOutputSize);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DCastOutput ymir_box3d_cast_sphere(
|
||||
float originX,
|
||||
float originZ,
|
||||
float translationX,
|
||||
float translationZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius,
|
||||
int canEncroach);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapOutput ymir_box3d_overlap_spheres(
|
||||
float queryX,
|
||||
float queryZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus 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 Box3DStatus ymir_box3d_session_sync_bodies(
|
||||
Box3DSessionHandle session,
|
||||
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,
|
||||
uint isKinematic);
|
||||
|
||||
[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(
|
||||
Box3DSessionHandle session,
|
||||
float deltaTime,
|
||||
int substepCount,
|
||||
Box3DRadialField* fields,
|
||||
int fieldCount);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_body_count(Box3DSessionHandle session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_copy_bodies(
|
||||
Box3DSessionHandle session,
|
||||
Box3DBodyOutput* output,
|
||||
int capacity,
|
||||
out int written);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_contact_count(Box3DSessionHandle session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contacts(
|
||||
Box3DSessionHandle session,
|
||||
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
|
||||
{
|
||||
private Box3DSessionHandle() : base(true)
|
||||
{
|
||||
}
|
||||
|
||||
internal Box3DSessionHandle(nint value) : base(true) => SetHandle(value);
|
||||
|
||||
protected override bool ReleaseHandle()
|
||||
{
|
||||
Box3DNative.ymir_box3d_session_destroy(handle);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyInput(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
uint IsStatic,
|
||||
uint IsKinematic,
|
||||
uint IsBullet,
|
||||
uint ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DRadialField(
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float Strength,
|
||||
float Radius);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyOutput(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DContactOutput(
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
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,
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DOverlapOutput(
|
||||
int Hit,
|
||||
float Distance,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
65
src/Ymir.Box3D/Box3DQueries.cs
Normal file
65
src/Ymir.Box3D/Box3DQueries.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DSphereCastHit(
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
internal readonly record struct Box3DSphereOverlapHit(float Distance, float NormalX, float NormalZ);
|
||||
|
||||
internal static class Box3DQueries
|
||||
{
|
||||
internal static Box3DSphereOverlapHit? OverlapSpheres(
|
||||
float queryX,
|
||||
float queryZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_overlap_spheres(
|
||||
queryX,
|
||||
queryZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereOverlapHit(output.Distance, output.NormalX, output.NormalZ);
|
||||
}
|
||||
|
||||
internal static Box3DSphereCastHit? CastSphere(
|
||||
float originX,
|
||||
float originZ,
|
||||
float translationX,
|
||||
float translationZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_cast_sphere(
|
||||
originX,
|
||||
originZ,
|
||||
translationX,
|
||||
translationZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius,
|
||||
canEncroach: 0);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereCastHit(
|
||||
output.Fraction,
|
||||
output.PointX,
|
||||
output.PointZ,
|
||||
output.NormalX,
|
||||
output.NormalZ);
|
||||
}
|
||||
}
|
||||
404
src/Ymir.Box3D/Box3DSession.cs
Normal file
404
src/Ymir.Box3D/Box3DSession.cs
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DBody(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
bool IsStatic,
|
||||
bool IsKinematic,
|
||||
bool IsBullet,
|
||||
bool ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
internal readonly record struct Box3DField(float PositionX, float PositionZ, float Strength, float Radius);
|
||||
|
||||
internal readonly record struct Box3DBodyState(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity);
|
||||
|
||||
internal readonly record struct Box3DContact(
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
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 = 4;
|
||||
internal const int DefaultSubstepCount = 4;
|
||||
|
||||
private readonly Box3DSessionHandle _handle;
|
||||
private bool _disposed;
|
||||
|
||||
internal Box3DSession()
|
||||
{
|
||||
EnsureCompatibleNativeLibrary();
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_create(out var value), "create session");
|
||||
if (value == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned a null Ymir session.");
|
||||
}
|
||||
|
||||
_handle = new Box3DSessionHandle(value);
|
||||
}
|
||||
|
||||
internal unsafe void SyncBodies(ReadOnlySpan<Box3DBody> bodies)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var native = new Box3DBodyInput[bodies.Length];
|
||||
for (var i = 0; i < bodies.Length; i++)
|
||||
{
|
||||
var body = bodies[i];
|
||||
native[i] = new Box3DBodyInput(
|
||||
body.StableId,
|
||||
body.CollisionCategoryBits,
|
||||
body.CollisionMaskBits,
|
||||
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,
|
||||
body.IsKinematic ? 1u : 0u,
|
||||
body.IsBullet ? 1u : 0u,
|
||||
body.ParticipatesInFields ? 1u : 0u,
|
||||
body.CollisionGroupIndex);
|
||||
}
|
||||
|
||||
fixed (Box3DBodyInput* pointer = native)
|
||||
{
|
||||
var status = Box3DNative.ymir_box3d_session_sync_bodies(_handle, pointer, native.Length);
|
||||
if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError)
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
ThrowIfFailed(status, "synchronize bodies");
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
bool isKinematic)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_configure(
|
||||
_handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u, isKinematic ? 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<Box3DField> fields, int substepCount = DefaultSubstepCount)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (!float.IsFinite(deltaTime) || deltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(deltaTime), "Delta time must be finite and positive.");
|
||||
}
|
||||
|
||||
if (substepCount <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(substepCount), "Substep count must be positive.");
|
||||
}
|
||||
|
||||
var native = new Box3DRadialField[fields.Length];
|
||||
for (var i = 0; i < fields.Length; i++)
|
||||
{
|
||||
native[i] = new Box3DRadialField(fields[i].PositionX, fields[i].PositionZ, fields[i].Strength, fields[i].Radius);
|
||||
}
|
||||
|
||||
fixed (Box3DRadialField* pointer = native)
|
||||
{
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_step(_handle, deltaTime, substepCount, pointer, native.Length),
|
||||
"step session");
|
||||
}
|
||||
}
|
||||
|
||||
internal unsafe Box3DBodyState[] CopyBodies()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var count = Box3DNative.ymir_box3d_session_get_body_count(_handle);
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned an invalid body count.");
|
||||
}
|
||||
|
||||
var native = new Box3DBodyOutput[count];
|
||||
fixed (Box3DBodyOutput* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_bodies(_handle, pointer, count, out var written), "copy bodies");
|
||||
if (written != count)
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D body snapshot changed during copy: expected {count}, received {written}.");
|
||||
}
|
||||
}
|
||||
|
||||
return native.Select(body => new Box3DBodyState(
|
||||
body.StableId,
|
||||
body.PositionX,
|
||||
body.PositionZ,
|
||||
body.VelocityX,
|
||||
body.VelocityZ,
|
||||
body.DirectionX,
|
||||
body.DirectionZ,
|
||||
body.AngularVelocity)).ToArray();
|
||||
}
|
||||
|
||||
internal unsafe Box3DContact[] CopyContacts()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var count = Box3DNative.ymir_box3d_session_get_contact_count(_handle);
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned an invalid contact count.");
|
||||
}
|
||||
|
||||
var native = new Box3DContactOutput[count];
|
||||
fixed (Box3DContactOutput* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_contacts(_handle, pointer, count, out var written), "copy contacts");
|
||||
if (written != count)
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D contact snapshot changed during copy: expected {count}, received {written}.");
|
||||
}
|
||||
}
|
||||
|
||||
return native.Select(contact => new Box3DContact(
|
||||
contact.StableIdA,
|
||||
contact.StableIdB,
|
||||
contact.PointX,
|
||||
contact.PointZ,
|
||||
contact.NormalX,
|
||||
contact.NormalZ,
|
||||
contact.Penetration,
|
||||
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)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_handle.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
internal static void EnsureCompatibleNativeLibrary()
|
||||
{
|
||||
var abi = Box3DNative.ymir_box3d_get_abi_version();
|
||||
if (abi != AbiVersion)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir Box3D ABI mismatch. Managed expects {AbiVersion}, native provides {abi}.");
|
||||
}
|
||||
|
||||
ThrowIfFailed(
|
||||
Box3DNative.ymir_box3d_get_abi_layout(
|
||||
out var bodyInputSize,
|
||||
out var fieldInputSize,
|
||||
out var bodyOutputSize,
|
||||
out var contactOutputSize,
|
||||
out var contactEventOutputSize),
|
||||
"read native ABI layout");
|
||||
EnsureSize<Box3DBodyInput>(bodyInputSize);
|
||||
EnsureSize<Box3DRadialField>(fieldInputSize);
|
||||
EnsureSize<Box3DBodyOutput>(bodyOutputSize);
|
||||
EnsureSize<Box3DContactOutput>(contactOutputSize);
|
||||
EnsureSize<Box3DContactEventOutput>(contactEventOutputSize);
|
||||
|
||||
Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision);
|
||||
if (major != 0 || minor != 1 || revision != 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir requires Box3D 0.1.0, but loaded {major}.{minor}.{revision}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureSize<T>(uint nativeSize) where T : struct
|
||||
{
|
||||
var managedSize = checked((uint)Marshal.SizeOf<T>());
|
||||
if (managedSize != nativeSize)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Ymir Box3D ABI layout mismatch for {typeof(T).Name}. Managed expects {managedSize} bytes, native provides {nativeSize}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ThrowIfFailed(Box3DStatus status, string operation)
|
||||
{
|
||||
if (status != Box3DStatus.Ok)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir could not {operation}: native Box3D status {status}.");
|
||||
}
|
||||
}
|
||||
|
||||
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.CollisionCategoryBits,
|
||||
body.CollisionMaskBits,
|
||||
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,
|
||||
body.IsKinematic ? 1u : 0u,
|
||||
body.IsBullet ? 1u : 0u,
|
||||
body.ParticipatesInFields ? 1u : 0u,
|
||||
body.CollisionGroupIndex);
|
||||
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
3
src/Ymir.Box3D/Properties/AssemblyInfo.cs
Normal file
3
src/Ymir.Box3D/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Core")]
|
||||
13
src/Ymir.Box3D/README.md
Normal file
13
src/Ymir.Box3D/README.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# GameCult.Ymir.Box3D
|
||||
|
||||
This is Ymir's private managed/native boundary for pinned Box3D v0.1.0. It is
|
||||
installed transitively by Ymir; products and clients should reference Ymir's
|
||||
typed session contracts instead of this package.
|
||||
|
||||
The package includes the compiled native facade under `runtimes/<rid>/native`.
|
||||
Package consumers do not need CMake, a C compiler, or the Box3D submodule.
|
||||
Missing or ABI-incompatible native assets fail closed when Ymir opens a physics
|
||||
session.
|
||||
|
||||
Source builds of Ymir use CMake to compile the pinned submodule. Box3D is MIT
|
||||
licensed; its license is included in the package.
|
||||
58
src/Ymir.Box3D/Ymir.Box3D.csproj
Normal file
58
src/Ymir.Box3D/Ymir.Box3D.csproj
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>Ymir.Box3D</RootNamespace>
|
||||
<AssemblyName>Ymir.Box3D</AssemblyName>
|
||||
<Description>Native ABI boundary between Ymir sessions and pinned Box3D.</Description>
|
||||
<PackageId>GameCult.Ymir.Box3D</PackageId>
|
||||
<Version>0.3.0</Version>
|
||||
<Authors>GameCult</Authors>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\production\$(Configuration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(NativeBuildDir)\bin\$(Configuration)\ymir_box3d.dll"
|
||||
Link="ymir_box3d.dll"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/win-x64/native/ymir_box3d.dll"
|
||||
Condition="'$(OS)' == 'Windows_NT'" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.so"
|
||||
Link="libymir_box3d.so"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/linux-x64/native/libymir_box3d.so"
|
||||
Condition="'$(OS)' != 'Windows_NT' and !$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.dylib"
|
||||
Link="libymir_box3d.dylib"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/osx-x64/native/libymir_box3d.dylib"
|
||||
Condition="$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="..\..\extern\box3d\LICENSE"
|
||||
Link="box3d-MIT.txt"
|
||||
Pack="true"
|
||||
PackagePath="licenses" />
|
||||
<None Include="README.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="BuildYmirBox3DNative"
|
||||
BeforeTargets="PrepareForBuild;GetCopyToOutputDirectoryItems;GetCopyToPublishDirectoryItems"
|
||||
Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DBUILD_SHARED_LIBS=OFF" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(Configuration) --target ymir_box3d" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
|
@ -18,7 +18,16 @@ public sealed record PhysicsBody(
|
|||
float Radius,
|
||||
float Mass,
|
||||
bool IsStatic = false,
|
||||
float Restitution = 0.2f);
|
||||
float Restitution = 0.2f,
|
||||
Vec2? Direction = null,
|
||||
float AngularVelocity = 0.0f,
|
||||
float Torque = 0.0f,
|
||||
bool IsKinematic = false,
|
||||
bool IsBullet = false,
|
||||
bool ParticipatesInFields = true,
|
||||
ulong CollisionCategoryBits = 1UL,
|
||||
ulong CollisionMaskBits = ulong.MaxValue,
|
||||
int CollisionGroupIndex = 0);
|
||||
|
||||
public sealed record RadialField(
|
||||
string Id,
|
||||
|
|
@ -46,3 +55,31 @@ public sealed record ContactEvent(
|
|||
public sealed record SimulationStepResult(
|
||||
YmirWorld World,
|
||||
IReadOnlyList<ContactEvent> Contacts);
|
||||
|
||||
public sealed record CircleCastQueryRequest(
|
||||
Vec2 Origin,
|
||||
Vec2 Direction,
|
||||
float Distance,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleCastHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleCastQueryResult(IReadOnlyList<CircleCastHit> Hits);
|
||||
|
||||
public sealed record CircleOverlapQueryRequest(
|
||||
Vec2 Center,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleOverlapHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleOverlapQueryResult(IReadOnlyList<CircleOverlapHit> Hits);
|
||||
|
|
|
|||
3
src/Ymir.Core/Properties/AssemblyInfo.cs
Normal file
3
src/Ymir.Core/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Tests")]
|
||||
165
src/Ymir.Core/RetainedSessionModel.cs
Normal file
165
src/Ymir.Core/RetainedSessionModel.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
namespace Ymir.Core;
|
||||
|
||||
public sealed record YmirSessionCreateRequest(
|
||||
string SessionId,
|
||||
IReadOnlyList<PhysicsBody> 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,
|
||||
bool IsKinematic = false);
|
||||
|
||||
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<RadialField> 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<string> 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<YmirContactFact> ContactFacts);
|
||||
|
||||
public sealed record YmirSessionCircleCastQuery(
|
||||
string QueryId,
|
||||
long ExpectedRevision,
|
||||
Vec2 Origin,
|
||||
Vec2 Direction,
|
||||
float Distance,
|
||||
float Radius,
|
||||
IReadOnlyList<string> CandidateBodyIds);
|
||||
|
||||
public sealed record YmirSessionCircleOverlapQuery(
|
||||
string QueryId,
|
||||
long ExpectedRevision,
|
||||
Vec2 Center,
|
||||
float Radius,
|
||||
IReadOnlyList<string> CandidateBodyIds);
|
||||
|
||||
public enum YmirQueryError
|
||||
{
|
||||
None,
|
||||
StaleRevision,
|
||||
UnknownBody,
|
||||
InvalidQuery,
|
||||
SessionDisposed,
|
||||
SessionFaulted
|
||||
}
|
||||
|
||||
public sealed record YmirSessionCircleCastResult(
|
||||
string QueryId,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long ObservedRevision,
|
||||
long ObservedStepIndex,
|
||||
YmirQueryError Error,
|
||||
IReadOnlyList<CircleCastHit> Hits);
|
||||
|
||||
public sealed record YmirSessionCircleOverlapResult(
|
||||
string QueryId,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long ObservedRevision,
|
||||
long ObservedStepIndex,
|
||||
YmirQueryError Error,
|
||||
IReadOnlyList<CircleOverlapHit> Hits);
|
||||
|
||||
public sealed record YmirSessionInfo(
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long Revision,
|
||||
long StepIndex,
|
||||
bool IsDisposed,
|
||||
bool IsFaulted);
|
||||
|
|
@ -6,6 +6,7 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Ymir.Box3D\Ymir.Box3D.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
|
||||
<ProjectReference Include="$(EveUnityRoot)\packages\org.gamecult.eve.surface\GameCult.Eve.Surface.csproj" />
|
||||
|
|
@ -18,7 +19,7 @@
|
|||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Ymir.Core</RootNamespace>
|
||||
<AssemblyName>Ymir.Core</AssemblyName>
|
||||
<Description>GameCult physics cutover contracts and parity boundary for pinned Box3D.</Description>
|
||||
<Description>GameCult retained physics session library and optional daemon contracts backed by pinned Box3D.</Description>
|
||||
<Authors>GameCult</Authors>
|
||||
</PropertyGroup>
|
||||
|
||||
|
|
|
|||
116
src/Ymir.Core/YmirQueries.cs
Normal file
116
src/Ymir.Core/YmirQueries.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public static class YmirQueries
|
||||
{
|
||||
public static CircleOverlapQueryResult OverlapCircle(CircleOverlapQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Center.X) || !float.IsFinite(request.Center.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap center must be finite.");
|
||||
}
|
||||
|
||||
var hits = new List<CircleOverlapHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
var hit = Box3DQueries.OverlapSpheres(
|
||||
request.Center.X,
|
||||
request.Center.Y,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleOverlapHit(
|
||||
body.Id,
|
||||
request.Center,
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Distance));
|
||||
}
|
||||
|
||||
return new CircleOverlapQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
public static CircleCastQueryResult CastCircle(CircleCastQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Distance) || request.Distance < 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast distance must be finite and non-negative.");
|
||||
}
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Origin.X) || !float.IsFinite(request.Origin.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast origin must be finite.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = request.Direction.X * request.Direction.X + request.Direction.Y * request.Direction.Y;
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
var inverseLength = 1.0f / MathF.Sqrt(directionLengthSquared);
|
||||
var translationX = request.Direction.X * inverseLength * request.Distance;
|
||||
var translationY = request.Direction.Y * inverseLength * request.Distance;
|
||||
var hits = new List<CircleCastHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
|
||||
var hit = Box3DQueries.CastSphere(
|
||||
request.Origin.X,
|
||||
request.Origin.Y,
|
||||
translationX,
|
||||
translationY,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleCastHit(
|
||||
body.Id,
|
||||
new Vec2(value.PointX, value.PointZ),
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Fraction * request.Distance));
|
||||
}
|
||||
|
||||
return new CircleCastQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
private static void ValidateQueryBody(PhysicsBody body, object request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(body.Id) ||
|
||||
!float.IsFinite(body.Position.X) ||
|
||||
!float.IsFinite(body.Position.Y) ||
|
||||
!float.IsFinite(body.Radius) ||
|
||||
body.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentException("Query bodies require stable ids and finite positive radii.", nameof(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ public sealed class YmirProviderAdvertisementDocument
|
|||
public string Title { get; set; } = "Ymir Physics";
|
||||
|
||||
[Key(2)]
|
||||
public string Description { get; set; } = "GameCult cutover CLI and service-record publisher for the planned Box3D wrapper.";
|
||||
public string Description { get; set; } = "GameCult Box3D retained-session library and optional physics-daemon surface.";
|
||||
|
||||
[Key(3)]
|
||||
public string[] Owns { get; set; } = [];
|
||||
|
|
@ -44,16 +44,16 @@ public sealed class YmirOperatorStateDocument
|
|||
public string Status { get; set; } = "box3d-cutover";
|
||||
|
||||
[Key(2)]
|
||||
public string StateOwner { get; set; } = "Stateless managed step/query DTOs and derived service records";
|
||||
public string StateOwner { get; set; } = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections";
|
||||
|
||||
[Key(3)]
|
||||
public string NumericSubstrate { get; set; } = "Active: CultMath managed solver; target oracle: pinned Box3D v0.1.0 (C17)";
|
||||
public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)";
|
||||
|
||||
[Key(4)]
|
||||
public string BatchKernel { get; set; } = "";
|
||||
|
||||
[Key(5)]
|
||||
public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover";
|
||||
public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v2; explicit v1/v0 read migration";
|
||||
|
||||
[Key(6)]
|
||||
public string UpdatedAtUtc { get; set; } = "";
|
||||
|
|
@ -81,21 +81,24 @@ public static class YmirServicePublication
|
|||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Title = "Ymir Physics",
|
||||
Description = "GameCult cutover CLI and service-record publisher for the planned Box3D wrapper.",
|
||||
Description = "GameCult Box3D retained-session library and optional physics-daemon surface.",
|
||||
Owns =
|
||||
[
|
||||
"stateless managed step and query request handling",
|
||||
"stable GameCult physics identity",
|
||||
"typed physics request and result DTOs",
|
||||
"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",
|
||||
"CultCache world and service record emission",
|
||||
"Eve operator surface projection"
|
||||
"CultCache world snapshot v2 with explicit v1/v0 read migration",
|
||||
"diagnostic Eve publication"
|
||||
],
|
||||
DoesNotOwn =
|
||||
[
|
||||
"daemon-owned named session registry or CultMesh command lowering yet",
|
||||
"complete checkpoint reconstruction yet",
|
||||
"physics algorithm invention",
|
||||
"Box3D solver and collision semantics",
|
||||
"retained Box3D production sessions during cutover",
|
||||
"CultMesh provider sessions or discovery during cutover",
|
||||
"Unity scene truth",
|
||||
"rendering",
|
||||
|
|
@ -109,11 +112,11 @@ public static class YmirServicePublication
|
|||
public static YmirOperatorStateDocument OperatorState(DateTimeOffset now) => new()
|
||||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Status = "box3d-cutover",
|
||||
StateOwner = "Stateless managed step/query DTOs and derived service records",
|
||||
NumericSubstrate = "Active: CultMath managed solver; target oracle: pinned Box3D v0.1.0 (C17)",
|
||||
BatchKernel = "Transitional managed solver; no retained Box3D session",
|
||||
Persistence = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover",
|
||||
Status = "box3d-retained-session",
|
||||
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.v2; explicit v1/v0 read migration",
|
||||
UpdatedAtUtc = FormatUtc(now)
|
||||
};
|
||||
|
||||
|
|
|
|||
1110
src/Ymir.Core/YmirSession.cs
Normal file
1110
src/Ymir.Core/YmirSession.cs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,144 +1,20 @@
|
|||
using CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Compatibility façade for the snapshot-in/snapshot-out Ymir contract.
|
||||
/// Calls are isolated by design; retained world ownership is not inferred from snapshots.
|
||||
/// </summary>
|
||||
public sealed class YmirSimulator
|
||||
{
|
||||
private const float MinimumMass = 0.0001f;
|
||||
private const float MinimumDistance = 0.0001f;
|
||||
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
var result = Step(new SoASimulationStepRequest(
|
||||
request.DeltaTime,
|
||||
YmirSoAWorld.FromWorld(request.World)));
|
||||
|
||||
return new SimulationStepResult(result.World.ToWorld(), result.Contacts);
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
if (request.DeltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be positive.");
|
||||
}
|
||||
|
||||
var world = request.World.Clone();
|
||||
world.Validate();
|
||||
|
||||
var accelerationX = new float[world.BodyCount];
|
||||
var accelerationY = new float[world.BodyCount];
|
||||
for (var i = 0; i < world.FieldCount; i++)
|
||||
{
|
||||
BatchMath.AddRadialFalloffAcceleration2D(
|
||||
world.PositionX,
|
||||
world.PositionY,
|
||||
world.FieldPositionX[i],
|
||||
world.FieldPositionY[i],
|
||||
world.FieldStrength[i],
|
||||
world.FieldRadius[i],
|
||||
accelerationX,
|
||||
accelerationY);
|
||||
}
|
||||
|
||||
BatchMath.IntegrateSemiImplicitEuler2D(
|
||||
request.DeltaTime,
|
||||
world.DynamicMask,
|
||||
world.PositionX,
|
||||
world.PositionY,
|
||||
world.VelocityX,
|
||||
world.VelocityY,
|
||||
accelerationX,
|
||||
accelerationY);
|
||||
|
||||
var contacts = new List<ContactEvent>();
|
||||
ResolveCircleContacts(world, contacts);
|
||||
|
||||
world.Time += request.DeltaTime;
|
||||
return new SoASimulationStepResult(
|
||||
world,
|
||||
contacts);
|
||||
}
|
||||
|
||||
private static void ResolveCircleContacts(YmirSoAWorld world, List<ContactEvent> contacts)
|
||||
{
|
||||
for (var i = 0; i < world.BodyCount; i++)
|
||||
{
|
||||
for (var j = i + 1; j < world.BodyCount; j++)
|
||||
{
|
||||
var delta = world.PositionAt(j) - world.PositionAt(i);
|
||||
var distance = length(delta);
|
||||
var combinedRadius = world.Radius[i] + world.Radius[j];
|
||||
var penetration = combinedRadius - distance;
|
||||
|
||||
if (penetration <= 0.0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normal = distance <= MinimumDistance ? float2(1.0f, 0.0f) : delta / distance;
|
||||
var point = world.PositionAt(i) + normal * (world.Radius[i] - penetration * 0.5f);
|
||||
var relativeVelocity = world.VelocityAt(j) - world.VelocityAt(i);
|
||||
var relativeSpeed = dot(relativeVelocity, normal);
|
||||
|
||||
contacts.Add(new ContactEvent(
|
||||
world.BodyIds[i],
|
||||
world.BodyIds[j],
|
||||
Vec2.FromCultMath(point),
|
||||
Vec2.FromCultMath(normal),
|
||||
penetration,
|
||||
relativeSpeed));
|
||||
|
||||
ResolveImpulse(world, i, j, normal, penetration, relativeSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResolveImpulse(
|
||||
YmirSoAWorld world,
|
||||
int left,
|
||||
int right,
|
||||
float2 normal,
|
||||
float penetration,
|
||||
float relativeSpeed)
|
||||
{
|
||||
var leftInvMass = world.DynamicMask[left] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[left], MinimumMass);
|
||||
var rightInvMass = world.DynamicMask[right] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[right], MinimumMass);
|
||||
var invMassSum = leftInvMass + rightInvMass;
|
||||
if (invMassSum <= 0.0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var correction = normal * (penetration / invMassSum);
|
||||
if (leftInvMass > 0.0f)
|
||||
{
|
||||
world.SetPosition(left, world.PositionAt(left) - correction * leftInvMass);
|
||||
}
|
||||
|
||||
if (rightInvMass > 0.0f)
|
||||
{
|
||||
world.SetPosition(right, world.PositionAt(right) + correction * rightInvMass);
|
||||
}
|
||||
|
||||
if (relativeSpeed >= 0.0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var restitution = min(world.Restitution[left], world.Restitution[right]);
|
||||
var impulseMagnitude = -(1.0f + restitution) * relativeSpeed / invMassSum;
|
||||
var impulse = normal * impulseMagnitude;
|
||||
|
||||
if (leftInvMass > 0.0f)
|
||||
{
|
||||
world.SetVelocity(left, world.VelocityAt(left) - impulse * leftInvMass);
|
||||
}
|
||||
|
||||
if (rightInvMass > 0.0f)
|
||||
{
|
||||
world.SetVelocity(right, world.VelocityAt(right) + impulse * rightInvMass);
|
||||
}
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,10 +10,20 @@ public sealed class YmirSoAWorld
|
|||
public float[] PositionY { get; set; } = [];
|
||||
public float[] VelocityX { get; set; } = [];
|
||||
public float[] VelocityY { get; set; } = [];
|
||||
public float[] DirectionX { get; set; } = [];
|
||||
public float[] DirectionY { get; set; } = [];
|
||||
public float[] AngularVelocity { get; set; } = [];
|
||||
public float[] Torque { get; set; } = [];
|
||||
public float[] Radius { get; set; } = [];
|
||||
public float[] Mass { get; set; } = [];
|
||||
public float[] DynamicMask { get; set; } = [];
|
||||
public float[] Restitution { get; set; } = [];
|
||||
public float[] KinematicMask { get; set; } = [];
|
||||
public float[] BulletMask { get; set; } = [];
|
||||
public float[] FieldParticipationMask { get; set; } = [];
|
||||
public ulong[] CollisionCategoryBits { get; set; } = [];
|
||||
public ulong[] CollisionMaskBits { get; set; } = [];
|
||||
public int[] CollisionGroupIndex { get; set; } = [];
|
||||
public string[] FieldIds { get; set; } = [];
|
||||
public float[] FieldPositionX { get; set; } = [];
|
||||
public float[] FieldPositionY { get; set; } = [];
|
||||
|
|
@ -37,10 +47,20 @@ public sealed class YmirSoAWorld
|
|||
PositionY = bodies.Select(body => body.Position.Y).ToArray(),
|
||||
VelocityX = bodies.Select(body => body.Velocity.X).ToArray(),
|
||||
VelocityY = bodies.Select(body => body.Velocity.Y).ToArray(),
|
||||
DirectionX = bodies.Select(body => DirectionOrDefault(body.Direction).X).ToArray(),
|
||||
DirectionY = bodies.Select(body => DirectionOrDefault(body.Direction).Y).ToArray(),
|
||||
AngularVelocity = bodies.Select(body => body.AngularVelocity).ToArray(),
|
||||
Torque = bodies.Select(body => body.Torque).ToArray(),
|
||||
Radius = bodies.Select(body => body.Radius).ToArray(),
|
||||
Mass = bodies.Select(body => body.Mass).ToArray(),
|
||||
DynamicMask = bodies.Select(body => body.IsStatic ? 0.0f : 1.0f).ToArray(),
|
||||
Restitution = bodies.Select(body => body.Restitution).ToArray(),
|
||||
KinematicMask = bodies.Select(body => body.IsKinematic ? 1.0f : 0.0f).ToArray(),
|
||||
BulletMask = bodies.Select(body => body.IsBullet ? 1.0f : 0.0f).ToArray(),
|
||||
FieldParticipationMask = bodies.Select(body => body.ParticipatesInFields ? 1.0f : 0.0f).ToArray(),
|
||||
CollisionCategoryBits = bodies.Select(body => body.CollisionCategoryBits).ToArray(),
|
||||
CollisionMaskBits = bodies.Select(body => body.CollisionMaskBits).ToArray(),
|
||||
CollisionGroupIndex = bodies.Select(body => body.CollisionGroupIndex).ToArray(),
|
||||
FieldIds = fields.Select(field => field.Id).ToArray(),
|
||||
FieldPositionX = fields.Select(field => field.Position.X).ToArray(),
|
||||
FieldPositionY = fields.Select(field => field.Position.Y).ToArray(),
|
||||
|
|
@ -59,7 +79,16 @@ public sealed class YmirSoAWorld
|
|||
Radius[i],
|
||||
Mass[i],
|
||||
DynamicMask[i] <= 0.0f,
|
||||
Restitution[i]))
|
||||
Restitution[i],
|
||||
new Vec2(DirectionX[i], DirectionY[i]),
|
||||
AngularVelocity[i],
|
||||
Torque[i],
|
||||
KinematicMask[i] > 0.0f,
|
||||
BulletMask[i] > 0.0f,
|
||||
FieldParticipationMask[i] > 0.0f,
|
||||
CollisionCategoryBits[i],
|
||||
CollisionMaskBits[i],
|
||||
CollisionGroupIndex[i]))
|
||||
.ToArray(),
|
||||
Enumerable.Range(0, FieldCount)
|
||||
.Select(i => new RadialField(
|
||||
|
|
@ -77,10 +106,20 @@ public sealed class YmirSoAWorld
|
|||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone(),
|
||||
Torque = (float[])Torque.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
KinematicMask = (float[])KinematicMask.Clone(),
|
||||
BulletMask = (float[])BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])CollisionGroupIndex.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
|
|
@ -109,6 +148,27 @@ public sealed class YmirSoAWorld
|
|||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Mass), "Dynamic body mass must be positive.");
|
||||
}
|
||||
|
||||
if (DynamicMask[i] <= 0.0f && KinematicMask[i] > 0.0f)
|
||||
{
|
||||
throw new ArgumentException("A body cannot be both static and kinematic.");
|
||||
}
|
||||
|
||||
if (CollisionCategoryBits[i] == 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(CollisionCategoryBits), "Collision category bits must be non-zero.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = DirectionX[i] * DirectionX[i] + DirectionY[i] * DirectionY[i];
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(DirectionX), "Body direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
if (!float.IsFinite(AngularVelocity[i]) || !float.IsFinite(Torque[i]))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(AngularVelocity), "Body angular state must be finite.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,16 +191,28 @@ public sealed class YmirSoAWorld
|
|||
private void ValidateBodyLengths()
|
||||
{
|
||||
var expected = BodyIds.Length;
|
||||
FillMissingAngularState(expected);
|
||||
FillMissingCollisionState(expected);
|
||||
foreach (var length in new[]
|
||||
{
|
||||
PositionX.Length,
|
||||
PositionY.Length,
|
||||
VelocityX.Length,
|
||||
VelocityY.Length,
|
||||
DirectionX.Length,
|
||||
DirectionY.Length,
|
||||
AngularVelocity.Length,
|
||||
Torque.Length,
|
||||
Radius.Length,
|
||||
Mass.Length,
|
||||
DynamicMask.Length,
|
||||
Restitution.Length
|
||||
Restitution.Length,
|
||||
KinematicMask.Length,
|
||||
BulletMask.Length,
|
||||
FieldParticipationMask.Length,
|
||||
CollisionCategoryBits.Length,
|
||||
CollisionMaskBits.Length,
|
||||
CollisionGroupIndex.Length
|
||||
})
|
||||
{
|
||||
if (length != expected)
|
||||
|
|
@ -150,6 +222,53 @@ public sealed class YmirSoAWorld
|
|||
}
|
||||
}
|
||||
|
||||
private void FillMissingCollisionState(int expected)
|
||||
{
|
||||
if (KinematicMask.Length == 0 && expected > 0) KinematicMask = new float[expected];
|
||||
if (BulletMask.Length == 0 && expected > 0) BulletMask = new float[expected];
|
||||
if (FieldParticipationMask.Length == 0 && expected > 0)
|
||||
FieldParticipationMask = Enumerable.Repeat(1.0f, expected).ToArray();
|
||||
if (CollisionCategoryBits.Length == 0 && expected > 0)
|
||||
CollisionCategoryBits = Enumerable.Repeat(1UL, expected).ToArray();
|
||||
if (CollisionMaskBits.Length == 0 && expected > 0)
|
||||
CollisionMaskBits = Enumerable.Repeat(ulong.MaxValue, expected).ToArray();
|
||||
if (CollisionGroupIndex.Length == 0 && expected > 0) CollisionGroupIndex = new int[expected];
|
||||
}
|
||||
|
||||
private void FillMissingAngularState(int expected)
|
||||
{
|
||||
if (DirectionX.Length == 0 && expected > 0)
|
||||
{
|
||||
DirectionX = new float[expected];
|
||||
}
|
||||
|
||||
if (DirectionY.Length == 0 && expected > 0)
|
||||
{
|
||||
DirectionY = Enumerable.Repeat(1.0f, expected).ToArray();
|
||||
}
|
||||
|
||||
if (AngularVelocity.Length == 0 && expected > 0)
|
||||
{
|
||||
AngularVelocity = new float[expected];
|
||||
}
|
||||
|
||||
if (Torque.Length == 0 && expected > 0)
|
||||
{
|
||||
Torque = new float[expected];
|
||||
}
|
||||
}
|
||||
|
||||
private static Vec2 DirectionOrDefault(Vec2? direction)
|
||||
{
|
||||
if (direction is not { } value ||
|
||||
value.X * value.X + value.Y * value.Y <= 1.0e-8f)
|
||||
{
|
||||
return new Vec2(0.0f, 1.0f);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private void ValidateFieldLengths()
|
||||
{
|
||||
var expected = FieldIds.Length;
|
||||
|
|
|
|||
206
src/Ymir.Core/YmirWorldSession.cs
Normal file
206
src/Ymir.Core/YmirWorldSession.cs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Owns one retained Box3D world and its stable GameCult identity projection.
|
||||
/// Callers own the session lifetime; body snapshots do not imply session identity.
|
||||
/// </summary>
|
||||
internal sealed class YmirWorldSession : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Box3DSession _session = new();
|
||||
private readonly Dictionary<string, ulong> _keysById = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<ulong, string> _idsByKey = new();
|
||||
private ulong _nextKey = 1;
|
||||
private bool _disposed;
|
||||
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var result = Step(new SoASimulationStepRequest(
|
||||
request.DeltaTime,
|
||||
YmirSoAWorld.FromWorld(request.World)));
|
||||
|
||||
return new SimulationStepResult(result.World.ToWorld(), result.Contacts);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.DeltaTime) || request.DeltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be finite and positive.");
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var world = request.World.Clone();
|
||||
world.Validate();
|
||||
ValidateStableIds(world.BodyIds);
|
||||
|
||||
var indicesByKey = new Dictionary<ulong, int>(world.BodyCount);
|
||||
foreach (var id in world.BodyIds.OrderBy(id => id, StringComparer.Ordinal))
|
||||
{
|
||||
GetOrCreateKey(id);
|
||||
}
|
||||
|
||||
var bodies = new Box3DBody[world.BodyCount];
|
||||
for (var i = 0; i < world.BodyCount; i++)
|
||||
{
|
||||
var key = GetOrCreateKey(world.BodyIds[i]);
|
||||
indicesByKey.Add(key, i);
|
||||
bodies[i] = new Box3DBody(
|
||||
key,
|
||||
world.CollisionCategoryBits[i],
|
||||
world.CollisionMaskBits[i],
|
||||
world.PositionX[i],
|
||||
world.PositionY[i],
|
||||
world.VelocityX[i],
|
||||
world.VelocityY[i],
|
||||
world.DirectionX[i],
|
||||
world.DirectionY[i],
|
||||
world.AngularVelocity[i],
|
||||
world.Torque[i],
|
||||
world.Radius[i],
|
||||
world.Mass[i],
|
||||
world.Restitution[i],
|
||||
world.DynamicMask[i] <= 0.0f,
|
||||
world.KinematicMask[i] > 0.0f,
|
||||
world.BulletMask[i] > 0.0f,
|
||||
world.FieldParticipationMask[i] > 0.0f,
|
||||
world.CollisionGroupIndex[i]);
|
||||
}
|
||||
|
||||
Array.Sort(bodies, static (left, right) => left.StableId.CompareTo(right.StableId));
|
||||
|
||||
var fields = Enumerable.Range(0, world.FieldCount)
|
||||
.OrderBy(index => world.FieldIds[index], StringComparer.Ordinal)
|
||||
.Select(index => new Box3DField(
|
||||
world.FieldPositionX[index],
|
||||
world.FieldPositionY[index],
|
||||
world.FieldStrength[index],
|
||||
world.FieldRadius[index]))
|
||||
.ToArray();
|
||||
|
||||
_session.SyncBodies(bodies);
|
||||
_session.Step(request.DeltaTime, fields);
|
||||
|
||||
foreach (var body in _session.CopyBodies())
|
||||
{
|
||||
if (!indicesByKey.TryGetValue(body.StableId, out var index))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {body.StableId}.");
|
||||
}
|
||||
|
||||
world.PositionX[index] = body.PositionX;
|
||||
world.PositionY[index] = body.PositionZ;
|
||||
world.VelocityX[index] = body.VelocityX;
|
||||
world.VelocityY[index] = body.VelocityZ;
|
||||
world.DirectionX[index] = body.DirectionX;
|
||||
world.DirectionY[index] = body.DirectionZ;
|
||||
world.AngularVelocity[index] = body.AngularVelocity;
|
||||
world.Torque[index] = 0.0f;
|
||||
}
|
||||
|
||||
var contacts = _session.CopyContacts()
|
||||
.Select(ProjectContact)
|
||||
.OrderBy(contact => contact.BodyA, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.BodyB, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.Point.X)
|
||||
.ThenBy(contact => contact.Point.Y)
|
||||
.ToArray();
|
||||
|
||||
PruneInactiveIds(world.BodyIds);
|
||||
|
||||
world.Time += request.DeltaTime;
|
||||
return new SoASimulationStepResult(world, contacts);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_session.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private ulong GetOrCreateKey(string id)
|
||||
{
|
||||
if (_keysById.TryGetValue(id, out var existing))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (_nextKey == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Ymir exhausted its stable native body key space.");
|
||||
}
|
||||
|
||||
var key = _nextKey++;
|
||||
_keysById.Add(id, key);
|
||||
_idsByKey.Add(key, id);
|
||||
return key;
|
||||
}
|
||||
|
||||
private ContactEvent ProjectContact(Box3DContact contact)
|
||||
{
|
||||
var bodyA = ResolveId(contact.StableIdA);
|
||||
var bodyB = ResolveId(contact.StableIdB);
|
||||
var normal = new Vec2(contact.NormalX, contact.NormalZ);
|
||||
if (StringComparer.Ordinal.Compare(bodyA, bodyB) > 0)
|
||||
{
|
||||
(bodyA, bodyB) = (bodyB, bodyA);
|
||||
normal = new Vec2(-normal.X, -normal.Y);
|
||||
}
|
||||
|
||||
return new ContactEvent(
|
||||
bodyA,
|
||||
bodyB,
|
||||
new Vec2(contact.PointX, contact.PointZ),
|
||||
normal,
|
||||
contact.Penetration,
|
||||
contact.RelativeSpeed);
|
||||
}
|
||||
|
||||
private string ResolveId(ulong key)
|
||||
{
|
||||
if (!_idsByKey.TryGetValue(key, out var id))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {key}.");
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private void PruneInactiveIds(IReadOnlyList<string> activeIds)
|
||||
{
|
||||
var active = activeIds.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var id in _keysById.Keys.Where(id => !active.Contains(id)).ToArray())
|
||||
{
|
||||
var key = _keysById[id];
|
||||
_keysById.Remove(id);
|
||||
_idsByKey.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateStableIds(IReadOnlyList<string> bodyIds)
|
||||
{
|
||||
var unique = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var id in bodyIds)
|
||||
{
|
||||
if (!unique.Add(id))
|
||||
{
|
||||
throw new ArgumentException($"Ymir body id '{id}' occurs more than once.", nameof(bodyIds));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ namespace Ymir.Core;
|
|||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v0")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocument
|
||||
public sealed class YmirWorldStateDocumentV0
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
|
|
@ -57,7 +57,7 @@ public sealed class YmirWorldStateDocument
|
|||
[Key(15)]
|
||||
public float[] FieldRadius { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocument FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
public static YmirWorldStateDocumentV0 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
|
|
@ -97,6 +97,146 @@ public sealed class YmirWorldStateDocument
|
|||
};
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV1
|
||||
{
|
||||
[Key(0), CultName] public string WorldId { get; set; } = "default";
|
||||
[Key(1)] public float Time { get; set; }
|
||||
[Key(2)] public string[] BodyIds { get; set; } = [];
|
||||
[Key(3)] public float[] PositionX { get; set; } = [];
|
||||
[Key(4)] public float[] PositionY { get; set; } = [];
|
||||
[Key(5)] public float[] VelocityX { get; set; } = [];
|
||||
[Key(6)] public float[] VelocityY { get; set; } = [];
|
||||
[Key(7)] public float[] Radius { get; set; } = [];
|
||||
[Key(8)] public float[] Mass { get; set; } = [];
|
||||
[Key(9)] public float[] DynamicMask { get; set; } = [];
|
||||
[Key(10)] public float[] Restitution { get; set; } = [];
|
||||
[Key(11)] public string[] FieldIds { get; set; } = [];
|
||||
[Key(12)] public float[] FieldPositionX { get; set; } = [];
|
||||
[Key(13)] public float[] FieldPositionY { get; set; } = [];
|
||||
[Key(14)] public float[] FieldStrength { get; set; } = [];
|
||||
[Key(15)] public float[] FieldRadius { get; set; } = [];
|
||||
[Key(16)] public float[] DirectionX { get; set; } = [];
|
||||
[Key(17)] public float[] DirectionY { get; set; } = [];
|
||||
[Key(18)] public float[] AngularVelocity { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV1 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(),
|
||||
PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(),
|
||||
VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(),
|
||||
Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(),
|
||||
Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(),
|
||||
FieldRadius = (float[])world.FieldRadius.Clone(),
|
||||
DirectionX = (float[])world.DirectionX.Clone(),
|
||||
DirectionY = (float[])world.DirectionY.Clone(),
|
||||
AngularVelocity = (float[])world.AngularVelocity.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time,
|
||||
BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(),
|
||||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(),
|
||||
FieldRadius = (float[])FieldRadius.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v2")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV2
|
||||
{
|
||||
[Key(0), CultName] public string WorldId { get; set; } = "default";
|
||||
[Key(1)] public float Time { get; set; }
|
||||
[Key(2)] public string[] BodyIds { get; set; } = [];
|
||||
[Key(3)] public float[] PositionX { get; set; } = [];
|
||||
[Key(4)] public float[] PositionY { get; set; } = [];
|
||||
[Key(5)] public float[] VelocityX { get; set; } = [];
|
||||
[Key(6)] public float[] VelocityY { get; set; } = [];
|
||||
[Key(7)] public float[] Radius { get; set; } = [];
|
||||
[Key(8)] public float[] Mass { get; set; } = [];
|
||||
[Key(9)] public float[] DynamicMask { get; set; } = [];
|
||||
[Key(10)] public float[] Restitution { get; set; } = [];
|
||||
[Key(11)] public string[] FieldIds { get; set; } = [];
|
||||
[Key(12)] public float[] FieldPositionX { get; set; } = [];
|
||||
[Key(13)] public float[] FieldPositionY { get; set; } = [];
|
||||
[Key(14)] public float[] FieldStrength { get; set; } = [];
|
||||
[Key(15)] public float[] FieldRadius { get; set; } = [];
|
||||
[Key(16)] public float[] DirectionX { get; set; } = [];
|
||||
[Key(17)] public float[] DirectionY { get; set; } = [];
|
||||
[Key(18)] public float[] AngularVelocity { get; set; } = [];
|
||||
[Key(19)] public float[] KinematicMask { get; set; } = [];
|
||||
[Key(20)] public float[] BulletMask { get; set; } = [];
|
||||
[Key(21)] public float[] FieldParticipationMask { get; set; } = [];
|
||||
[Key(22)] public ulong[] CollisionCategoryBits { get; set; } = [];
|
||||
[Key(23)] public ulong[] CollisionMaskBits { get; set; } = [];
|
||||
[Key(24)] public int[] CollisionGroupIndex { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV2 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId, Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(), PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(), VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(), Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(), Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(), FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(), FieldRadius = (float[])world.FieldRadius.Clone(),
|
||||
DirectionX = (float[])world.DirectionX.Clone(), DirectionY = (float[])world.DirectionY.Clone(),
|
||||
AngularVelocity = (float[])world.AngularVelocity.Clone(),
|
||||
KinematicMask = (float[])world.KinematicMask.Clone(), BulletMask = (float[])world.BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])world.FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])world.CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])world.CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])world.CollisionGroupIndex.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time, BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(), PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(), VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(), Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(), Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(), FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(), FieldRadius = (float[])FieldRadius.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(), DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone(),
|
||||
KinematicMask = (float[])KinematicMask.Clone(), BulletMask = (float[])BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])CollisionGroupIndex.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
public static class YmirCultCacheStore
|
||||
{
|
||||
public static async Task SaveWorldAsync(string path, string worldId, YmirSoAWorld world)
|
||||
|
|
@ -113,8 +253,8 @@ public static class YmirCultCacheStore
|
|||
using (cache)
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
YmirWorldStateDocument.FromSoA(worldId, world),
|
||||
new CultRecordHandle<YmirWorldStateDocument>(new CultRecordKey($"ymir:world:{worldId}")))
|
||||
YmirWorldStateDocumentV2.FromSoA(worldId, world),
|
||||
new CultRecordHandle<YmirWorldStateDocumentV2>(new CultRecordKey($"ymir:world:{worldId}")))
|
||||
.ConfigureAwait(false);
|
||||
await cache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
|
@ -125,6 +265,9 @@ public static class YmirCultCacheStore
|
|||
using var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false);
|
||||
return cache.Get<YmirWorldStateDocument>(new CultRecordKey($"ymir:world:{worldId}"))?.ToSoA();
|
||||
var key = new CultRecordKey($"ymir:world:{worldId}");
|
||||
return cache.Get<YmirWorldStateDocumentV2>(key)?.ToSoA()
|
||||
?? cache.Get<YmirWorldStateDocumentV1>(key)?.ToSoA()
|
||||
?? cache.Get<YmirWorldStateDocumentV0>(key)?.ToSoA();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ internal static class Program
|
|||
ok = true,
|
||||
path,
|
||||
record = "ymir:world:sample",
|
||||
schema = "gamecult.ymir.world_state.v0",
|
||||
schema = "gamecult.ymir.world_state.v2",
|
||||
bodyCount = result.World.BodyCount,
|
||||
fieldCount = result.World.FieldCount
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Ymir.Box3D.Parity;
|
||||
|
||||
|
|
@ -7,9 +8,11 @@ internal static partial class Box3DOracle
|
|||
private const string LibraryName = "ymir_box3d";
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapResult ymir_box3d_overlap_spheres(
|
||||
float queryX,
|
||||
float queryY,
|
||||
|
|
@ -19,6 +22,7 @@ internal static partial class Box3DOracle
|
|||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapResult ymir_box3d_overlap_capsule_sphere(
|
||||
float startX,
|
||||
float startY,
|
||||
|
|
@ -30,6 +34,7 @@ internal static partial class Box3DOracle
|
|||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DCastResult ymir_box3d_cast_sphere(
|
||||
float originX,
|
||||
float originY,
|
||||
|
|
@ -42,6 +47,7 @@ internal static partial class Box3DOracle
|
|||
int canEncroach);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial void ymir_box3d_step_pair(
|
||||
in Box3DBodyInput bodyA,
|
||||
in Box3DBodyInput bodyB,
|
||||
|
|
@ -51,7 +57,61 @@ internal static partial class Box3DOracle
|
|||
out Box3DPairStepResult result);
|
||||
|
||||
[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 partial int ymir_box3d_session_get_body_count(nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial int ymir_box3d_session_copy_bodies(
|
||||
nint session,
|
||||
Box3DSessionBodyOutput* bodies,
|
||||
int capacity,
|
||||
out int written);
|
||||
|
||||
[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)]
|
||||
|
|
@ -102,3 +162,52 @@ internal readonly record struct Box3DPairStepResult(
|
|||
internal readonly record struct Box3DTorqueResult(
|
||||
float AngularVelocityAfterAppliedStep,
|
||||
float AngularVelocityAfterUnforcedStep);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DSessionBodyInput(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float DirectionX,
|
||||
float DirectionY,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
uint IsStatic,
|
||||
uint IsKinematic,
|
||||
uint IsBullet,
|
||||
uint ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
[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);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DSessionBodyOutput(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float DirectionX,
|
||||
float DirectionY,
|
||||
float AngularVelocity);
|
||||
|
|
|
|||
|
|
@ -120,4 +120,130 @@ public sealed class Box3DParityTests
|
|||
result.AngularVelocityAfterUnforcedStep,
|
||||
precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle()
|
||||
{
|
||||
Assert.Equal(4u, Box3DOracle.ymir_box3d_get_abi_version());
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var bodyA = SessionBody(1, -0.9f);
|
||||
var bodyB = SessionBody(2, 0.9f);
|
||||
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<ulong> { 1, 2 }, new HashSet<ulong> { 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<ulong> { 1, 2 }, new HashSet<ulong> { end.StableIdA, end.StableIdB });
|
||||
Assert.Equal(0u, end.HasDetails);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void NegativeGroupAndCategoryMasksAreBox3DCollisionAuthority()
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var source = SessionBody(1, 0.0f, category: 1, mask: 2, group: -7);
|
||||
var ownPayload = SessionBody(2, 0.0f, category: 2, mask: 1, group: -7);
|
||||
var otherPayload = SessionBody(3, 0.0f, category: 2, mask: 1, group: -8);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &source));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &ownPayload));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &otherPayload));
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
var pairs = CopyEvents(session)
|
||||
.Where(value => value.Kind == 1)
|
||||
.Select(value => new HashSet<ulong> { value.StableIdA, value.StableIdB })
|
||||
.ToArray();
|
||||
|
||||
Assert.Single(pairs);
|
||||
Assert.Equal(new HashSet<ulong> { 1, 3 }, pairs[0]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void BulletUsesBox3DContinuousCollisionAgainstKinematicTarget()
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var bullet = SessionBody(1, -10.0f, velocityX: 100.0f, isBullet: true);
|
||||
var target = SessionBody(2, 0.0f, isKinematic: true);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bullet));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &target));
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 0.2f, 4, null, 0));
|
||||
Assert.Empty(CopyEvents(session));
|
||||
var ccdBodies = CopyBodies(session);
|
||||
Assert.True(ccdBodies.Single(value => value.StableId == 1).PositionX < 0.0f);
|
||||
Assert.Equal(0.0f, ccdBodies.Single(value => value.StableId == 2).PositionX, precision: 5);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
Assert.Contains(CopyEvents(session), value =>
|
||||
(value.Kind == 1 || value.Kind == 2) &&
|
||||
new HashSet<ulong> { value.StableIdA, value.StableIdB }.SetEquals([1UL, 2UL]));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
private static Box3DSessionBodyInput SessionBody(
|
||||
ulong id,
|
||||
float positionX,
|
||||
float velocityX = 0.0f,
|
||||
ulong category = 1,
|
||||
ulong mask = ulong.MaxValue,
|
||||
int group = 0,
|
||||
bool isKinematic = false,
|
||||
bool isBullet = false) => new(
|
||||
id, category, mask, positionX, 0.0f, velocityX, 0.0f, 0.0f, 1.0f,
|
||||
0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0,
|
||||
isKinematic ? 1u : 0u, isBullet ? 1u : 0u, 1u, group);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private static unsafe Box3DSessionBodyOutput[] CopyBodies(nint session)
|
||||
{
|
||||
var count = Box3DOracle.ymir_box3d_session_get_body_count(session);
|
||||
Assert.True(count >= 0);
|
||||
var bodies = new Box3DSessionBodyOutput[count];
|
||||
fixed (Box3DSessionBodyOutput* pointer = bodies)
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_bodies(session, pointer, count, out var written));
|
||||
Assert.Equal(count, written);
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<IsPackable>false</IsPackable>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\$(Configuration)</NativeBuildDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\parity\$(Configuration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -16,16 +16,17 @@ public sealed class YmirServicePublicationTests
|
|||
var diagnostics = YmirServicePublication.OperatorState(now);
|
||||
|
||||
Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal);
|
||||
Assert.Contains("stateless managed step and query request handling", advertisement.Owns);
|
||||
Assert.Contains("Box3D-only isolated snapshot stepping", advertisement.Owns);
|
||||
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.Contains("retained Box3D production sessions during cutover", advertisement.DoesNotOwn);
|
||||
Assert.Contains("CultMesh provider sessions or discovery during cutover", advertisement.DoesNotOwn);
|
||||
Assert.DoesNotContain("daemon", advertisement.Description, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(advertisement.Owns, claim => claim.Contains("session", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.Equal("box3d-cutover", diagnostics.Status);
|
||||
Assert.StartsWith("Active: CultMath managed solver", diagnostics.NumericSubstrate, StringComparison.Ordinal);
|
||||
Assert.Contains("no retained Box3D session", diagnostics.BatchKernel, StringComparison.Ordinal);
|
||||
Assert.Contains("world_state.v0", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate);
|
||||
Assert.Contains("does not own physics algorithms", diagnostics.BatchKernel, StringComparison.Ordinal);
|
||||
Assert.Contains("world_state.v2", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Contains("v0 read migration", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Equal("box3d-retained-session", diagnostics.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
327
tests/Ymir.Tests/YmirSessionTests.cs
Normal file
327
tests/Ymir.Tests/YmirSessionTests.cs
Normal file
|
|
@ -0,0 +1,327 @@
|
|||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CollisionProfilesExcludeOwnGroupAndPayloadPeers()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"collision-profile",
|
||||
[
|
||||
Body("source") with
|
||||
{
|
||||
CollisionCategoryBits = 1,
|
||||
CollisionMaskBits = 2,
|
||||
CollisionGroupIndex = -7
|
||||
},
|
||||
Body("own-payload") with
|
||||
{
|
||||
CollisionCategoryBits = 2,
|
||||
CollisionMaskBits = 1,
|
||||
CollisionGroupIndex = -7
|
||||
},
|
||||
Body("other-payload") with
|
||||
{
|
||||
CollisionCategoryBits = 2,
|
||||
CollisionMaskBits = 1,
|
||||
CollisionGroupIndex = -8
|
||||
}
|
||||
]));
|
||||
|
||||
var result = session.Step(Step("profile-step", 0, 1.0f / 60.0f));
|
||||
var begin = Assert.Single(result.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
|
||||
Assert.Equal(new HashSet<string> { "source", "other-payload" }, new HashSet<string> { begin.BodyA, begin.BodyB });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BodyCanOptOutOfRadialFields()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"field-profile",
|
||||
[Body("affected", positionX: 1.0f), Body("ignored", positionX: -5.0f) with { ParticipatesInFields = false }]));
|
||||
|
||||
var result = session.Step(new YmirStepSessionCommand(
|
||||
Header("field-step", 0),
|
||||
0.1f,
|
||||
[new RadialField("gravity", Vec2.Zero, 10.0f, 10.0f)]));
|
||||
|
||||
Assert.NotEqual(0.0f, result.World.Bodies.Single(body => body.Id == "affected").Velocity.X);
|
||||
Assert.Equal(0.0f, result.World.Bodies.Single(body => body.Id == "ignored").Velocity.X, 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KinematicTargetDoesNotAcceptBulletImpulse()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"bullet-kinematic",
|
||||
[
|
||||
Body("bullet", positionX: -10.0f, velocityX: 100.0f) with { IsBullet = true },
|
||||
Body("target") with { IsKinematic = true }
|
||||
]));
|
||||
|
||||
var ccdStep = session.Step(Step("ccd", 0, 0.2f));
|
||||
var eventStep = session.Step(Step("event", 1, 1.0f / 60.0f));
|
||||
|
||||
Assert.Empty(ccdStep.ContactFacts);
|
||||
Assert.Contains(eventStep.ContactFacts, fact => fact.Kind is YmirContactFactKind.Begin or YmirContactFactKind.Hit);
|
||||
var target = eventStep.World.Bodies.Single(body => body.Id == "target");
|
||||
Assert.Equal(Vec2.Zero, target.Velocity);
|
||||
Assert.Equal(Vec2.Zero, target.Position);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RetainedCastObservesNamedRevisionAndExplicitCandidates()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"retained-cast",
|
||||
[Body("source", positionX: -2.0f), Body("target", positionX: 2.0f), Body("ignored", positionX: 0.0f)]));
|
||||
|
||||
var result = session.CastCircle(new YmirSessionCircleCastQuery(
|
||||
"payload-sweep",
|
||||
0,
|
||||
new Vec2(-5.0f, 0.0f),
|
||||
new Vec2(1.0f, 0.0f),
|
||||
10.0f,
|
||||
0.25f,
|
||||
["target"]));
|
||||
|
||||
Assert.Equal(YmirQueryError.None, result.Error);
|
||||
Assert.Equal(0, result.ObservedRevision);
|
||||
Assert.Equal(0, result.ObservedStepIndex);
|
||||
Assert.Equal("target", Assert.Single(result.Hits).BodyId);
|
||||
Assert.Equal(0, session.Info.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RetainedQueriesFailClosedForStaleUnknownAndDisposedSessions()
|
||||
{
|
||||
var session = YmirSession.Create(new YmirSessionCreateRequest("query-failures", [Body("target")]));
|
||||
|
||||
var stale = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"stale", 1, Vec2.Zero, 1.0f, ["target"]));
|
||||
var unknown = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"unknown", 0, Vec2.Zero, 1.0f, ["missing"]));
|
||||
session.Dispose();
|
||||
var disposed = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"disposed", 0, Vec2.Zero, 1.0f, ["target"]));
|
||||
|
||||
Assert.Equal(YmirQueryError.StaleRevision, stale.Error);
|
||||
Assert.Equal(YmirQueryError.UnknownBody, unknown.Error);
|
||||
Assert.Equal(YmirQueryError.SessionDisposed, disposed.Error);
|
||||
Assert.Empty(stale.Hits);
|
||||
Assert.Empty(unknown.Hits);
|
||||
Assert.Empty(disposed.Hits);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
using Ymir.Core;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
||||
namespace Ymir.Tests;
|
||||
|
||||
|
|
@ -76,7 +78,78 @@ public sealed class YmirSimulatorTests
|
|||
}
|
||||
|
||||
[Fact]
|
||||
public void SoAStepUsesBufferAsSimulationAuthority()
|
||||
public void ExplicitWorldSessionRetainsBox3DStateAcrossSteps()
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
var first = session.Step(new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
[new PhysicsBody("ship", Vec2.Zero, new Vec2(10.0f, 0.0f), 0.5f, 1.0f)],
|
||||
[])));
|
||||
|
||||
var second = session.Step(new SimulationStepRequest(0.1f, first.World));
|
||||
|
||||
Assert.Equal(2.0f, second.World.Bodies[0].Position.X, precision: 5);
|
||||
Assert.Equal(0.2f, second.World.Time, precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Box3DOwnsPlanarOrientationAndConsumesTorqueOnce()
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
var first = session.Step(new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
[new PhysicsBody(
|
||||
"ship",
|
||||
Vec2.Zero,
|
||||
Vec2.Zero,
|
||||
0.5f,
|
||||
1.0f,
|
||||
Direction: new Vec2(0.0f, 1.0f),
|
||||
Torque: 1.0f)],
|
||||
[])));
|
||||
|
||||
var firstBody = first.World.Bodies[0];
|
||||
Assert.NotNull(firstBody.Direction);
|
||||
Assert.NotEqual(0.0f, firstBody.AngularVelocity);
|
||||
Assert.Equal(0.0f, firstBody.Torque);
|
||||
|
||||
var second = session.Step(new SimulationStepRequest(0.1f, first.World));
|
||||
Assert.Equal(firstBody.AngularVelocity, second.World.Bodies[0].AngularVelocity, precision: 4);
|
||||
Assert.NotEqual(firstBody.Direction, second.World.Bodies[0].Direction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CircleCastUsesPinnedBox3DEdgeSemantics()
|
||||
{
|
||||
var result = YmirQueries.CastCircle(new CircleCastQueryRequest(
|
||||
Vec2.Zero,
|
||||
new Vec2(1.0f, 0.0f),
|
||||
10.0f,
|
||||
1.0f,
|
||||
[new PhysicsBody("target", new Vec2(30.0f, 0.0f), Vec2.Zero, 20.0f, 1.0f, IsStatic: true)]));
|
||||
|
||||
var hit = Assert.Single(result.Hits);
|
||||
Assert.Equal("target", hit.BodyId);
|
||||
Assert.InRange(hit.Distance, 8.99f, 9.01f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CircleOverlapUsesPinnedBox3DTangentSemantics()
|
||||
{
|
||||
var result = YmirQueries.OverlapCircle(new CircleOverlapQueryRequest(
|
||||
Vec2.Zero,
|
||||
1.0f,
|
||||
[new PhysicsBody("target", new Vec2(2.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f, IsStatic: true)]));
|
||||
|
||||
Assert.Equal("target", Assert.Single(result.Hits).BodyId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SoAStepProjectsBox3DStateIntoContractBuffers()
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
var world = new YmirSoAWorld
|
||||
|
|
@ -114,7 +187,7 @@ public sealed class YmirSimulatorTests
|
|||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
2.0f,
|
||||
new[] { new PhysicsBody("ship", new Vec2(1.0f, 2.0f), new Vec2(3.0f, 4.0f), 0.5f, 1.0f) },
|
||||
new[] { new PhysicsBody("ship", new Vec2(1.0f, 2.0f), new Vec2(3.0f, 4.0f), 0.5f, 1.0f, Direction: new Vec2(1.0f, 0.0f), AngularVelocity: 2.0f) },
|
||||
new[] { new RadialField("well", new Vec2(5.0f, 6.0f), 7.0f, 8.0f) }));
|
||||
|
||||
await YmirCultCacheStore.SaveWorldAsync(path, "test", world);
|
||||
|
|
@ -124,6 +197,8 @@ public sealed class YmirSimulatorTests
|
|||
Assert.Equal(["ship"], loaded!.BodyIds);
|
||||
Assert.Equal(1.0f, loaded.PositionX[0], precision: 5);
|
||||
Assert.Equal(7.0f, loaded.FieldStrength[0], precision: 5);
|
||||
Assert.Equal(1.0f, loaded.DirectionX[0], precision: 5);
|
||||
Assert.Equal(2.0f, loaded.AngularVelocity[0], precision: 5);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -139,6 +214,82 @@ public sealed class YmirSimulatorTests
|
|||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CultCacheStoreReadsV0WithDefaultAngularState()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"ymir-v0-tests-{Guid.NewGuid():N}.cc");
|
||||
var recordsPath = $"{path}.records";
|
||||
try
|
||||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
2.0f,
|
||||
[new PhysicsBody("ship", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f)],
|
||||
[]));
|
||||
using (var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions { UseDirectoryStore = true, FlushOnDispose = true, StoreFlushOnDispose = true }))
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
YmirWorldStateDocumentV0.FromSoA("test", world),
|
||||
new CultRecordHandle<YmirWorldStateDocumentV0>(new CultRecordKey("ymir:world:test")));
|
||||
await cache.FlushAsync();
|
||||
}
|
||||
|
||||
var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
loaded!.Validate();
|
||||
Assert.Equal(0.0f, loaded.DirectionX[0]);
|
||||
Assert.Equal(1.0f, loaded.DirectionY[0]);
|
||||
Assert.Equal(0.0f, loaded.AngularVelocity[0]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CultCacheV2PreservesBox3DBodyProfile()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"ymir-v2-tests-{Guid.NewGuid():N}.cc");
|
||||
var recordsPath = $"{path}.records";
|
||||
try
|
||||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
3.0f,
|
||||
[new PhysicsBody("payload", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f) with
|
||||
{
|
||||
IsKinematic = true,
|
||||
IsBullet = true,
|
||||
ParticipatesInFields = false,
|
||||
CollisionCategoryBits = 4,
|
||||
CollisionMaskBits = 2,
|
||||
CollisionGroupIndex = -11
|
||||
}],
|
||||
[]));
|
||||
|
||||
await YmirCultCacheStore.SaveWorldAsync(path, "test", world);
|
||||
var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
loaded!.Validate();
|
||||
var body = Assert.Single(loaded.ToWorld().Bodies);
|
||||
Assert.True(body.IsKinematic);
|
||||
Assert.True(body.IsBullet);
|
||||
Assert.False(body.ParticipatesInFields);
|
||||
Assert.Equal(4UL, body.CollisionCategoryBits);
|
||||
Assert.Equal(2UL, body.CollisionMaskBits);
|
||||
Assert.Equal(-11, body.CollisionGroupIndex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static SimulationStepResult Step(params PhysicsBody[] bodies)
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
|
|
|
|||
Loading…
Reference in a new issue