diff --git a/Directory.Build.props b/Directory.Build.props
deleted file mode 100644
index c8a3c67..0000000
--- a/Directory.Build.props
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- $(CULTLIB_ROOT)
- $(MSBuildThisFileDirectory)..\CultLib
-
- 42dce3611a81adc5c5fac54cadbaa5637d6022d3
- C:\Program Files\Git\cmd\git.exe
- git
-
-
diff --git a/Directory.Build.targets b/Directory.Build.targets
deleted file mode 100644
index 46d436a..0000000
--- a/Directory.Build.targets
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
- <_CultLibReference Include="@(ProjectReference)"
- Condition="$([System.String]::Copy('%(Filename)').StartsWith('GameCult.')) or '%(Filename)' == 'CultMath'" />
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Ymir.slnx b/Ymir.slnx
index 180e6d3..51ef251 100644
--- a/Ymir.slnx
+++ b/Ymir.slnx
@@ -1,13 +1,8 @@
-
-
-
-
-
diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs
deleted file mode 100644
index fa82bd2..0000000
--- a/src/Ymir.Box3D/Box3DNative.cs
+++ /dev/null
@@ -1,277 +0,0 @@
-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 nint ymir_box3d_get_build_id();
-
- [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);
diff --git a/src/Ymir.Box3D/Box3DQueries.cs b/src/Ymir.Box3D/Box3DQueries.cs
deleted file mode 100644
index a2f480f..0000000
--- a/src/Ymir.Box3D/Box3DQueries.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-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);
- }
-}
diff --git a/src/Ymir.Box3D/Box3DRuntime.cs b/src/Ymir.Box3D/Box3DRuntime.cs
deleted file mode 100644
index f44bfda..0000000
--- a/src/Ymir.Box3D/Box3DRuntime.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace Ymir.Box3D;
-
-public static class Box3DRuntime
-{
- public const string NativeBuildId =
- "box3d-8441b4a-gc-6cfeeff-abi5-f32";
-
- public static string ValidatedBuildId
- {
- get
- {
- Box3DSession.EnsureCompatibleNativeLibrary();
- return NativeBuildId;
- }
- }
-}
diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs
deleted file mode 100644
index 43bc1a3..0000000
--- a/src/Ymir.Box3D/Box3DSession.cs
+++ /dev/null
@@ -1,411 +0,0 @@
-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 = 5;
- 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 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 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}.");
- }
-
- var buildId = Marshal.PtrToStringAnsi(Box3DNative.ymir_box3d_get_build_id());
- if (!string.Equals(buildId, Box3DRuntime.NativeBuildId, StringComparison.Ordinal))
- {
- throw new InvalidOperationException(
- $"Ymir Box3D build mismatch. Managed expects '{Box3DRuntime.NativeBuildId}', native provides '{buildId ?? ""}'.");
- }
-
- 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(bodyInputSize);
- EnsureSize(fieldInputSize);
- EnsureSize(bodyOutputSize);
- EnsureSize(contactOutputSize);
- EnsureSize(contactEventOutputSize);
-
- Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision);
- if (major != 0 || minor != 1 || revision != 0)
- {
- throw new InvalidOperationException($"Ymir requires Box3D 0.1.0, but loaded {major}.{minor}.{revision}.");
- }
- }
-
- private static void EnsureSize(uint nativeSize) where T : struct
- {
- var managedSize = checked((uint)Marshal.SizeOf());
- 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);
-}
diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs
index e9712c8..5e52077 100644
--- a/src/Ymir.Box3D/Box3DSoaWorld.cs
+++ b/src/Ymir.Box3D/Box3DSoaWorld.cs
@@ -557,7 +557,7 @@ public readonly unsafe ref struct Box3DSoaFacts
internal static unsafe partial class Box3DSoaNative
{
- private const string Library = Box3DNative.LibraryName;
+ private const string Library = "ymir_box3d";
[LibraryImport(Library)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
@@ -979,6 +979,7 @@ public readonly unsafe struct Box3DSoaView
public sealed class Box3DSoaWorld : IDisposable
{
private const uint ExpectedAbi = 21;
+ private static int s_abiVerified;
private nint _handle;
/// The gravity (m/s^2) this world was created with; native has no setter, so this copy cannot disagree.
@@ -992,6 +993,19 @@ public sealed class Box3DSoaWorld : IDisposable
int capacity, float gravityX = 0f, float gravityY = -10f, float gravityZ = 0f, int jointCapacity = 0,
int? factCapacity = null, float hitThreshold = 1f, Box3DSoaParticleCapacities? particles = null)
{
+ EnsureNativeAbi();
+
+ var caps = particles.GetValueOrDefault();
+ Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, particles.HasValue ? &caps : null, out _handle));
+ Gravity = (gravityX, gravityY, gravityZ);
+ }
+
+ private static void EnsureNativeAbi()
+ {
+ if (Volatile.Read(ref s_abiVerified) != 0)
+ {
+ return;
+ }
RequireNativeAbi(Box3DSoaNative.ymir_box3d_soa_get_abi_version());
static uint Size(uint which) => Box3DSoaNative.ymir_box3d_soa_get_particle_desc_size(which);
if (Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
@@ -1012,10 +1026,7 @@ public sealed class Box3DSoaWorld : IDisposable
{
throw new InvalidOperationException("The native Ymir Box3D SoA ABI does not match this build.");
}
-
- var caps = particles.GetValueOrDefault();
- Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, particles.HasValue ? &caps : null, out _handle));
- Gravity = (gravityX, gravityY, gravityZ);
+ Volatile.Write(ref s_abiVerified, 1);
}
/// Fails closed when the native library is not the ABI this build expects, in either direction.
diff --git a/src/Ymir.Box3D/Properties/AssemblyInfo.cs b/src/Ymir.Box3D/Properties/AssemblyInfo.cs
index 93c6e82..9ce53c9 100644
--- a/src/Ymir.Box3D/Properties/AssemblyInfo.cs
+++ b/src/Ymir.Box3D/Properties/AssemblyInfo.cs
@@ -1,4 +1,3 @@
using System.Runtime.CompilerServices;
-[assembly: InternalsVisibleTo("Ymir.Core")]
[assembly: InternalsVisibleTo("Ymir.Box3D.Soa.Tests")]
diff --git a/src/Ymir.Core/PhysicsModel.cs b/src/Ymir.Core/PhysicsModel.cs
deleted file mode 100644
index 9ed51cc..0000000
--- a/src/Ymir.Core/PhysicsModel.cs
+++ /dev/null
@@ -1,85 +0,0 @@
-using CultMath;
-
-namespace Ymir.Core;
-
-public readonly record struct Vec2(float X, float Y)
-{
- public static Vec2 Zero => new(0.0f, 0.0f);
-
- public float2 ToCultMath() => new(X, Y);
-
- public static Vec2 FromCultMath(float2 value) => new(value.x, value.y);
-}
-
-public sealed record PhysicsBody(
- string Id,
- Vec2 Position,
- Vec2 Velocity,
- float Radius,
- float Mass,
- bool IsStatic = false,
- 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,
- Vec2 Position,
- float Strength,
- float Radius);
-
-public sealed record YmirWorld(
- float Time,
- IReadOnlyList Bodies,
- IReadOnlyList Fields);
-
-public sealed record SimulationStepRequest(
- float DeltaTime,
- YmirWorld World);
-
-public sealed record ContactEvent(
- string BodyA,
- string BodyB,
- Vec2 Point,
- Vec2 Normal,
- float Penetration,
- float RelativeSpeed);
-
-public sealed record SimulationStepResult(
- YmirWorld World,
- IReadOnlyList Contacts);
-
-public sealed record CircleCastQueryRequest(
- Vec2 Origin,
- Vec2 Direction,
- float Distance,
- float Radius,
- IReadOnlyList Bodies);
-
-public sealed record CircleCastHit(
- string BodyId,
- Vec2 Point,
- Vec2 Normal,
- float Distance);
-
-public sealed record CircleCastQueryResult(IReadOnlyList Hits);
-
-public sealed record CircleOverlapQueryRequest(
- Vec2 Center,
- float Radius,
- IReadOnlyList Bodies);
-
-public sealed record CircleOverlapHit(
- string BodyId,
- Vec2 Point,
- Vec2 Normal,
- float Distance);
-
-public sealed record CircleOverlapQueryResult(IReadOnlyList Hits);
diff --git a/src/Ymir.Core/Properties/AssemblyInfo.cs b/src/Ymir.Core/Properties/AssemblyInfo.cs
deleted file mode 100644
index 53b0ddf..0000000
--- a/src/Ymir.Core/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,3 +0,0 @@
-using System.Runtime.CompilerServices;
-
-[assembly: InternalsVisibleTo("Ymir.Tests")]
diff --git a/src/Ymir.Core/RetainedSessionModel.cs b/src/Ymir.Core/RetainedSessionModel.cs
deleted file mode 100644
index cac3399..0000000
--- a/src/Ymir.Core/RetainedSessionModel.cs
+++ /dev/null
@@ -1,239 +0,0 @@
-using Ymir.Box3D;
-
-namespace Ymir.Core;
-
-public sealed record YmirSessionCreateRequest(
- string SessionId,
- IReadOnlyList InitialBodies,
- float InitialTime = 0.0f);
-
-public static class YmirSessionCheckpointContract
-{
- public const string FormatId = "gamecult.ymir.session_checkpoint.replay.v1";
- public const string JournalChunkFormatId = "gamecult.ymir.session_journal_chunk.v1";
- public const string ResumeDescriptorFormatId = "gamecult.ymir.session_resume.v1";
- public static string RuntimeFingerprint =>
- $"gamecult.ymir.replay.v1|{Box3DRuntime.ValidatedBuildId}";
-}
-
-public sealed record YmirSessionJournalChunk(
- string FormatId,
- string RuntimeFingerprint,
- string SessionId,
- string SessionGeneration,
- long FirstEntryIndex,
- IReadOnlyList Entries);
-
-public sealed record YmirSessionResumeDescriptor(
- string FormatId,
- string RuntimeFingerprint,
- string SessionId,
- string SessionGeneration,
- long Revision,
- long StepIndex,
- float Time,
- long NextBodyGeneration,
- IReadOnlyList InitialBodies,
- float InitialTime,
- long JournalEntryCount,
- string JournalDigest,
- YmirWorld World,
- IReadOnlyList ActiveContactEpisodes);
-
-public sealed record YmirSessionPersistenceCapture(
- YmirSessionJournalChunk? JournalChunk,
- YmirSessionResumeDescriptor ResumeDescriptor);
-
-public sealed record YmirSessionCheckpoint(
- string FormatId,
- string RuntimeFingerprint,
- string SessionId,
- string SessionGeneration,
- long Revision,
- long StepIndex,
- float Time,
- long NextBodyGeneration,
- IReadOnlyList InitialBodies,
- float InitialTime,
- IReadOnlyList Journal,
- string JournalDigest,
- YmirWorld World,
- IReadOnlyList ActiveContactEpisodes);
-
-public sealed record YmirContactEpisodeCheckpoint(
- string BodyA,
- long BodyAGeneration,
- string BodyB,
- long BodyBGeneration,
- long StartStepIndex,
- long Ordinal);
-
-public abstract record YmirSessionJournalEntry;
-
-public sealed record YmirSpawnBodyJournalEntry(YmirSpawnBodyCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirRemoveBodyJournalEntry(YmirRemoveBodyCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirTeleportBodyJournalEntry(YmirTeleportBodyCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirSetBodyVelocityJournalEntry(YmirSetBodyVelocityCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirConfigureBodyJournalEntry(YmirConfigureBodyCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirApplyForceJournalEntry(YmirApplyForceCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirApplyTorqueJournalEntry(YmirApplyTorqueCommand Command) : YmirSessionJournalEntry;
-public sealed record YmirStepSessionJournalEntry(YmirStepSessionCommand Command) : YmirSessionJournalEntry;
-
-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 Fields,
- int SubstepCount = 4);
-
-public sealed record YmirDisposeSessionCommand(YmirCommandHeader Header);
-
-public enum YmirCommandOutcome
-{
- Accepted,
- Rejected
-}
-
-public enum YmirCommandError
-{
- None,
- StaleRevision,
- CommandIdConflict,
- DuplicateBody,
- UnknownBody,
- StaticBody,
- InvalidCommand,
- SessionDisposed,
- SessionFaulted
-}
-
-public sealed record YmirCommandReceipt(
- string ReceiptId,
- string SessionId,
- string SessionGeneration,
- string CommandId,
- string CommandKind,
- YmirCommandOutcome Outcome,
- YmirCommandError Error,
- long BeforeRevision,
- long AfterRevision,
- long ObservedStepIndex,
- IReadOnlyList ProducedFactIds);
-
-public enum YmirContactFactKind
-{
- Begin,
- Hit,
- End
-}
-
-public sealed record YmirContactFact(
- string FactId,
- string ContactId,
- YmirContactFactKind Kind,
- string SessionId,
- string SessionGeneration,
- long StepIndex,
- string BodyA,
- long BodyAGeneration,
- string BodyB,
- long BodyBGeneration,
- Vec2? Point,
- Vec2? Normal,
- float? Penetration,
- float? RelativeSpeed);
-
-public sealed record YmirSessionStepResult(
- YmirCommandReceipt Receipt,
- YmirWorld World,
- long Revision,
- long StepIndex,
- IReadOnlyList ContactFacts);
-
-public sealed record YmirSessionCircleCastQuery(
- string QueryId,
- long ExpectedRevision,
- Vec2 Origin,
- Vec2 Direction,
- float Distance,
- float Radius,
- IReadOnlyList CandidateBodyIds);
-
-public sealed record YmirSessionCircleOverlapQuery(
- string QueryId,
- long ExpectedRevision,
- Vec2 Center,
- float Radius,
- IReadOnlyList 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 Hits);
-
-public sealed record YmirSessionCircleOverlapResult(
- string QueryId,
- string SessionId,
- string SessionGeneration,
- long ObservedRevision,
- long ObservedStepIndex,
- YmirQueryError Error,
- IReadOnlyList Hits);
-
-public sealed record YmirSessionInfo(
- string SessionId,
- string SessionGeneration,
- long Revision,
- long StepIndex,
- bool IsDisposed,
- bool IsFaulted);
diff --git a/src/Ymir.Core/Ymir.Core.csproj b/src/Ymir.Core/Ymir.Core.csproj
deleted file mode 100644
index 9c06e45..0000000
--- a/src/Ymir.Core/Ymir.Core.csproj
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- net8.0
- enable
- enable
- Ymir.Core
- Ymir.Core
- GameCult retained physics session library and optional daemon contracts backed by pinned Box3D.
- GameCult
-
-
-
diff --git a/src/Ymir.Core/YmirQueries.cs b/src/Ymir.Core/YmirQueries.cs
deleted file mode 100644
index 19cf5a1..0000000
--- a/src/Ymir.Core/YmirQueries.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-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();
- 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();
- 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));
- }
- }
-}
diff --git a/src/Ymir.Core/YmirServicePublicationDocument.cs b/src/Ymir.Core/YmirServicePublicationDocument.cs
deleted file mode 100644
index ec8328d..0000000
--- a/src/Ymir.Core/YmirServicePublicationDocument.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-using GameCult.Caching;
-using GameCult.Caching.MessagePack;
-using MessagePack;
-
-namespace Ymir.Core;
-
-[CultDocument("gamecult.ymir.provider_advertisement", "gamecult.ymir.provider_advertisement.v1")]
-[MessagePackObject]
-public sealed class YmirProviderAdvertisementDocument
-{
- [Key(0)]
- [CultName]
- public string ProviderId { get; set; } = "ymir.physics";
-
- [Key(1)]
- public string Title { get; set; } = "Ymir Physics";
-
- [Key(2)]
- public string Description { get; set; } = "GameCult Box3D retained-session library and optional physics-daemon surface.";
-
- [Key(3)]
- public string[] Owns { get; set; } = [];
-
- [Key(4)]
- public string[] DoesNotOwn { get; set; } = [];
-
- [Key(5)]
- public YmirTransportLoweringDocument[] CommandLowerings { get; set; } = [];
-
- [Key(6)]
- public string UpdatedAtUtc { get; set; } = "";
-}
-
-[CultDocument("gamecult.ymir.operator_state", "gamecult.ymir.operator_state.v1")]
-[MessagePackObject]
-public sealed class YmirOperatorStateDocument
-{
- [Key(0)]
- [CultName]
- public string ProviderId { get; set; } = "ymir.physics";
-
- [Key(1)]
- public string Status { get; set; } = "box3d-cutover";
-
- [Key(2)]
- public string StateOwner { get; set; } = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections";
-
- [Key(3)]
- public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)";
-
- [Key(4)]
- public string BatchKernel { get; set; } = "";
-
- [Key(5)]
- public string Persistence { get; set; } = "Checksummed replay checkpoint v1; host-owned private journal persistence; world_state.v2 inspection snapshot";
-
- [Key(6)]
- public string UpdatedAtUtc { get; set; } = "";
-}
-
-[MessagePackObject]
-public sealed class YmirTransportLoweringDocument
-{
- [Key(0)]
- public string Label { get; set; } = "";
-
- [Key(1)]
- public string Method { get; set; } = "POST";
-
- [Key(2)]
- public string Path { get; set; } = "";
-
- [Key(3)]
- public string Purpose { get; set; } = "";
-}
-
-public static class YmirServicePublication
-{
- public static YmirProviderAdvertisementDocument ProviderAdvertisement(DateTimeOffset now) => new()
- {
- ProviderId = "ymir.physics",
- Title = "Ymir Physics",
- Description = "GameCult Box3D retained-session library and optional physics-daemon surface.",
- Owns =
- [
- "Box3D-only isolated snapshot stepping",
- "public in-process retained sessions with explicit mutation receipts",
- "typed Begin, Hit, and End contact facts for retained steps",
- "stable GameCult id to transient Box3D handle projection",
- "Box3D-backed circle overlap and cast queries over submitted bodies",
- "deterministic result ordering",
- "checksummed replay checkpoint reconstruction bound to the pinned native build",
- "CultCache world snapshot v2 with explicit v1/v0 read migration"
- ],
- DoesNotOwn =
- [
- "daemon-owned named session registry or CultMesh command lowering yet",
- "host-owned durable journal storage or atomic frame persistence",
- "physics algorithm invention",
- "Box3D solver and collision semantics",
- "CultMesh provider sessions or discovery during cutover",
- "Unity scene truth",
- "rendering",
- "gameplay damage policy",
- "editor authoring truth"
- ],
- CommandLowerings = [],
- UpdatedAtUtc = FormatUtc(now)
- };
-
- public static YmirOperatorStateDocument OperatorState(DateTimeOffset now) => new()
- {
- ProviderId = "ymir.physics",
- 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 = "Checksummed replay checkpoint v1; host-owned private journal persistence; world_state.v2 inspection snapshot",
- UpdatedAtUtc = FormatUtc(now)
- };
-
- private static string FormatUtc(DateTimeOffset value) => value.UtcDateTime.ToString("O");
-}
-
-public static class YmirServicePublicationStore
-{
- public static async Task RegenerateDerivedStoreAsync(string path, DateTimeOffset now)
- {
- DeleteDerivedStore(path);
- await PublishAsync(path, now).ConfigureAwait(false);
- }
-
- public static async Task PublishAsync(string path, DateTimeOffset now)
- {
- var cache = await CultCacheMessagePack.OpenAsync(
- path,
- new CultCacheOpenOptions
- {
- UseDirectoryStore = true,
- FlushOnDispose = true,
- StoreFlushOnDispose = true
- }).ConfigureAwait(false);
-
- using (cache)
- {
- var operatorState = YmirServicePublication.OperatorState(now);
- await cache.UpsertAsync(
- YmirServicePublication.ProviderAdvertisement(now),
- new CultRecordHandle(new CultRecordKey("ymir:provider:ymir.physics")))
- .ConfigureAwait(false);
- await cache.UpsertAsync(
- operatorState,
- new CultRecordHandle(new CultRecordKey("ymir:operator:ymir.physics")))
- .ConfigureAwait(false);
- await cache.FlushAsync().ConfigureAwait(false);
- }
- }
-
- private static void DeleteDerivedStore(string path)
- {
- if (File.Exists(path))
- File.Delete(path);
-
- var recordsPath = DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(path);
- if (Directory.Exists(recordsPath))
- Directory.Delete(recordsPath, recursive: true);
- }
-}
diff --git a/src/Ymir.Core/YmirSession.cs b/src/Ymir.Core/YmirSession.cs
deleted file mode 100644
index 419437c..0000000
--- a/src/Ymir.Core/YmirSession.cs
+++ /dev/null
@@ -1,1416 +0,0 @@
-using System.Globalization;
-using System.Security.Cryptography;
-using System.Text;
-using Ymir.Box3D;
-
-namespace Ymir.Core;
-
-///
-/// Owns one retained Box3D world. Ordinary operations are explicit commands;
-/// complete snapshots are accepted only while the session is created.
-///
-public sealed class YmirSession : IDisposable
-{
- private readonly object _gate = new();
- private readonly Box3DSession _native = new();
- private readonly Dictionary _activeKeysById = new(StringComparer.Ordinal);
- private readonly Dictionary _idsByKey = new();
- private readonly Dictionary _generationsByKey = new();
- private readonly Dictionary _bodies = new(StringComparer.Ordinal);
- private readonly Dictionary _episodesByNativeContact = new();
- private readonly Dictionary _ledger = new(StringComparer.Ordinal);
- private readonly List _journal = [];
- private readonly PhysicsBody[] _initialBodies;
- private readonly float _initialTime;
- private readonly string _sessionId;
- private readonly string _sessionGeneration;
- private ulong _nextNativeKey = 1;
- private long _nextBodyGeneration = 1;
- private long _revision;
- private long _stepIndex;
- private float _time;
- private RadialField[] _fields = [];
- private bool _disposed;
- private bool _faulted;
-
- private YmirSession(YmirSessionCreateRequest request, string? restoredSessionGeneration = null)
- {
- ArgumentNullException.ThrowIfNull(request);
- if (string.IsNullOrWhiteSpace(request.SessionId))
- {
- throw new ArgumentException("Session id is required.", nameof(request));
- }
- if (!float.IsFinite(request.InitialTime) || request.InitialTime < 0.0f)
- {
- throw new ArgumentOutOfRangeException(nameof(request), "Initial time must be finite and non-negative.");
- }
-
- _sessionId = request.SessionId;
- _sessionGeneration = string.IsNullOrWhiteSpace(restoredSessionGeneration)
- ? Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)
- : restoredSessionGeneration;
- _time = request.InitialTime;
- _initialTime = request.InitialTime;
-
- var initial = request.InitialBodies ?? throw new ArgumentNullException(nameof(request.InitialBodies));
- ValidateUniqueBodyIds(initial);
- _initialBodies = initial.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray();
- try
- {
- foreach (var body in _initialBodies)
- {
- ValidateBody(body, allowTorque: false);
- SpawnCore(body);
- }
- }
- catch
- {
- _native.Dispose();
- _disposed = true;
- throw;
- }
- }
-
- public static YmirSession Create(YmirSessionCreateRequest request) => new(request);
-
- public static YmirSession Restore(YmirSessionCheckpoint checkpoint)
- {
- ValidateCheckpointHeader(checkpoint);
- var session = new YmirSession(
- new YmirSessionCreateRequest(checkpoint.SessionId, checkpoint.InitialBodies, checkpoint.InitialTime),
- checkpoint.SessionGeneration);
- try
- {
- foreach (var entry in checkpoint.Journal)
- session.Replay(entry);
- session.VerifyCheckpoint(checkpoint);
- return session;
- }
- catch
- {
- session.Dispose();
- throw;
- }
- }
-
- public static YmirSession Restore(
- YmirSessionResumeDescriptor descriptor,
- IReadOnlyList chunks)
- {
- ArgumentNullException.ThrowIfNull(descriptor);
- ArgumentNullException.ThrowIfNull(chunks);
- if (!string.Equals(descriptor.FormatId, YmirSessionCheckpointContract.ResumeDescriptorFormatId, StringComparison.Ordinal) ||
- !string.Equals(descriptor.RuntimeFingerprint, YmirSessionCheckpointContract.RuntimeFingerprint, StringComparison.Ordinal) ||
- descriptor.JournalEntryCount < 0)
- throw new InvalidOperationException("Ymir resume descriptor format or runtime provenance is incompatible.");
-
- var journal = new List();
- foreach (var chunk in chunks.OrderBy(value => value.FirstEntryIndex))
- {
- if (!string.Equals(chunk.FormatId, YmirSessionCheckpointContract.JournalChunkFormatId, StringComparison.Ordinal) ||
- !string.Equals(chunk.RuntimeFingerprint, descriptor.RuntimeFingerprint, StringComparison.Ordinal) ||
- !string.Equals(chunk.SessionId, descriptor.SessionId, StringComparison.Ordinal) ||
- !string.Equals(chunk.SessionGeneration, descriptor.SessionGeneration, StringComparison.Ordinal) ||
- chunk.FirstEntryIndex != journal.Count || chunk.Entries == null)
- throw new InvalidOperationException("Ymir journal chunks are incompatible, overlapping, or incomplete.");
- journal.AddRange(chunk.Entries);
- }
- if (journal.Count != descriptor.JournalEntryCount)
- throw new InvalidOperationException(
- $"Ymir resume requires {descriptor.JournalEntryCount} journal entries but received {journal.Count}.");
-
- return Restore(new YmirSessionCheckpoint(
- YmirSessionCheckpointContract.FormatId,
- descriptor.RuntimeFingerprint,
- descriptor.SessionId,
- descriptor.SessionGeneration,
- descriptor.Revision,
- descriptor.StepIndex,
- descriptor.Time,
- descriptor.NextBodyGeneration,
- descriptor.InitialBodies,
- descriptor.InitialTime,
- journal,
- descriptor.JournalDigest,
- descriptor.World,
- descriptor.ActiveContactEpisodes));
- }
-
- public YmirSessionInfo Info
- {
- get
- {
- lock (_gate)
- {
- return new YmirSessionInfo(
- _sessionId, _sessionGeneration, _revision, _stepIndex, _disposed, _faulted);
- }
- }
- }
-
- ///
- /// Gets the number of commands retained in the current persistence generation.
- ///
- public long PersistenceJournalEntryCount
- {
- get
- {
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- return _journal.Count;
- }
- }
- }
-
- ///
- /// Replaces this session with a fresh persistence generation from the current
- /// Box3D projection when no contact or unstepped mutation state would be lost.
- /// The native world owned by this session is released before the replacement is
- /// allocated so compaction cannot exceed Box3D's fixed world capacity. A successful
- /// call leaves this session disposed and transfers ownership to the caller.
- ///
- public bool TryReplaceWithCompactedPersistenceBaseline(out YmirSession? compacted)
- {
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- if (_faulted)
- throw new InvalidOperationException("A faulted Ymir session cannot compact persistence.");
- if (_episodesByNativeContact.Count > 0 ||
- (_journal.Count > 0 && _journal[^1] is not YmirStepSessionJournalEntry))
- {
- compacted = null;
- return false;
- }
-
- var request = new YmirSessionCreateRequest(
- _sessionId,
- _bodies.Values.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray(),
- _time);
- _native.Dispose();
- _disposed = true;
- compacted = new YmirSession(request);
- return true;
- }
- }
-
- public YmirSessionCheckpoint Checkpoint()
- {
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- if (_faulted)
- throw new InvalidOperationException("A faulted Ymir session cannot publish a checkpoint.");
- var activeEpisodes = _episodesByNativeContact.Values
- .Distinct()
- .Select(EpisodeCheckpoint)
- .OrderBy(value => value.BodyA, StringComparer.Ordinal)
- .ThenBy(value => value.BodyAGeneration)
- .ThenBy(value => value.BodyB, StringComparer.Ordinal)
- .ThenBy(value => value.BodyBGeneration)
- .ThenBy(value => value.StartStepIndex)
- .ThenBy(value => value.Ordinal)
- .ToArray();
- return new YmirSessionCheckpoint(
- YmirSessionCheckpointContract.FormatId,
- YmirSessionCheckpointContract.RuntimeFingerprint,
- _sessionId,
- _sessionGeneration,
- _revision,
- _stepIndex,
- _time,
- _nextBodyGeneration,
- _initialBodies.ToArray(),
- _initialTime,
- _journal.ToArray(),
- JournalDigest(),
- SnapshotCore(),
- activeEpisodes);
- }
- }
-
- public YmirSessionPersistenceCapture CapturePersistence(long persistedJournalEntryCount)
- {
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- if (_faulted)
- throw new InvalidOperationException("A faulted Ymir session cannot publish persistence state.");
- if (persistedJournalEntryCount < 0 || persistedJournalEntryCount > _journal.Count)
- throw new ArgumentOutOfRangeException(nameof(persistedJournalEntryCount));
-
- var checkpoint = Checkpoint();
- var chunk = persistedJournalEntryCount == _journal.Count
- ? null
- : new YmirSessionJournalChunk(
- YmirSessionCheckpointContract.JournalChunkFormatId,
- checkpoint.RuntimeFingerprint,
- checkpoint.SessionId,
- checkpoint.SessionGeneration,
- persistedJournalEntryCount,
- _journal.Skip(checked((int)persistedJournalEntryCount)).ToArray());
- var descriptor = new YmirSessionResumeDescriptor(
- YmirSessionCheckpointContract.ResumeDescriptorFormatId,
- checkpoint.RuntimeFingerprint,
- checkpoint.SessionId,
- checkpoint.SessionGeneration,
- checkpoint.Revision,
- checkpoint.StepIndex,
- checkpoint.Time,
- checkpoint.NextBodyGeneration,
- checkpoint.InitialBodies,
- checkpoint.InitialTime,
- checkpoint.Journal.Count,
- checkpoint.JournalDigest,
- checkpoint.World,
- checkpoint.ActiveContactEpisodes);
- return new YmirSessionPersistenceCapture(chunk, descriptor);
- }
- }
-
- public YmirCommandReceipt Spawn(YmirSpawnBodyCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.spawn", writer => WriteBody(writer, command.Body));
- RecordCommand(command.Header, new YmirSpawnBodyJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.spawn") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.spawn", fingerprint);
- }
- if (!TryValidateBody(command.Body, allowTorque: false))
- {
- return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.InvalidCommand);
- }
- if (_activeKeysById.ContainsKey(command.Body.Id))
- {
- return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.DuplicateBody);
- }
-
- SpawnCore(command.Body);
- return AcceptAndStore(command.Header, fingerprint, "body.spawn");
- }
- }
-
- public YmirCommandReceipt Remove(YmirRemoveBodyCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.remove", writer => WriteString(writer, command.BodyId));
- RecordCommand(command.Header, new YmirRemoveBodyJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.remove") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.remove", fingerprint);
- }
- if (string.IsNullOrWhiteSpace(command.BodyId) ||
- !_activeKeysById.TryGetValue(command.BodyId, out var key))
- {
- return RejectAndStore(command.Header, fingerprint, "body.remove", YmirCommandError.UnknownBody);
- }
-
- RunNative(() =>
- {
- _native.Remove(key);
- _activeKeysById.Remove(command.BodyId);
- _bodies.Remove(command.BodyId);
- });
- return AcceptAndStore(command.Header, fingerprint, "body.remove");
- }
- }
-
- public YmirCommandReceipt Teleport(YmirTeleportBodyCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.teleport", writer =>
- {
- WriteString(writer, command.BodyId);
- Write(writer, command.Position);
- Write(writer, command.Direction);
- });
- RecordCommand(command.Header, new YmirTeleportBodyJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.teleport") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.teleport", fingerprint);
- }
- if (!TryBody(command.BodyId, out var key, out var body))
- {
- return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.UnknownBody);
- }
- if (!Finite(command.Position) || !ValidDirection(command.Direction))
- {
- return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.InvalidCommand);
- }
-
- var direction = Normalize(command.Direction);
- RunNative(() =>
- {
- _native.Teleport(key, command.Position.X, command.Position.Y, direction.X, direction.Y);
- _bodies[command.BodyId] = body with { Position = command.Position, Direction = direction };
- UpdateBodyProjection(_native.CopyBodies());
- });
- return AcceptAndStore(command.Header, fingerprint, "body.teleport");
- }
- }
-
- public YmirCommandReceipt SetVelocity(YmirSetBodyVelocityCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.set_velocity", writer =>
- {
- WriteString(writer, command.BodyId);
- Write(writer, command.LinearVelocity);
- writer.Write(command.AngularVelocity);
- });
- RecordCommand(command.Header, new YmirSetBodyVelocityJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.set_velocity") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.set_velocity", fingerprint);
- }
- if (!TryBody(command.BodyId, out var key, out var body))
- {
- return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.UnknownBody);
- }
- if (body.IsStatic)
- {
- return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.StaticBody);
- }
- if (!Finite(command.LinearVelocity) || !float.IsFinite(command.AngularVelocity))
- {
- return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.InvalidCommand);
- }
-
- RunNative(() =>
- {
- _native.SetVelocity(key, command.LinearVelocity.X, command.LinearVelocity.Y, command.AngularVelocity);
- _bodies[command.BodyId] = body with
- {
- Velocity = command.LinearVelocity,
- AngularVelocity = command.AngularVelocity
- };
- UpdateBodyProjection(_native.CopyBodies());
- });
- return AcceptAndStore(command.Header, fingerprint, "body.set_velocity");
- }
- }
-
- public YmirCommandReceipt Configure(YmirConfigureBodyCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.configure", writer =>
- {
- WriteString(writer, command.BodyId);
- writer.Write(command.Radius);
- writer.Write(command.Mass);
- writer.Write(command.IsStatic);
- writer.Write(command.Restitution);
- writer.Write(command.IsKinematic);
- });
- RecordCommand(command.Header, new YmirConfigureBodyJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.configure") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.configure", fingerprint);
- }
- if (!TryBody(command.BodyId, out var key, out var body))
- {
- return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.UnknownBody);
- }
- if (!float.IsFinite(command.Radius) || command.Radius <= 0.0f ||
- !float.IsFinite(command.Mass) || (!command.IsStatic && command.Mass <= 0.0f) ||
- (command.IsStatic && command.IsKinematic) ||
- !float.IsFinite(command.Restitution) || command.Restitution < 0.0f)
- {
- return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.InvalidCommand);
- }
-
- RunNative(() =>
- {
- _native.Configure(
- key,
- command.Radius,
- command.Mass,
- command.Restitution,
- command.IsStatic,
- command.IsKinematic);
- _bodies[command.BodyId] = body with
- {
- Radius = command.Radius,
- Mass = command.Mass,
- IsStatic = command.IsStatic,
- IsKinematic = command.IsKinematic,
- Restitution = command.Restitution
- };
- UpdateBodyProjection(_native.CopyBodies());
- });
- return AcceptAndStore(command.Header, fingerprint, "body.configure");
- }
- }
-
- public YmirCommandReceipt ApplyForce(YmirApplyForceCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.apply_force", writer =>
- {
- WriteString(writer, command.BodyId);
- Write(writer, command.Force);
- });
- RecordCommand(command.Header, new YmirApplyForceJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.apply_force") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.apply_force", fingerprint);
- }
- if (!TryBody(command.BodyId, out var key, out var body))
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.UnknownBody);
- }
- if (body.IsStatic || body.IsKinematic)
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.StaticBody);
- }
- if (!Finite(command.Force))
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.InvalidCommand);
- }
-
- RunNative(() => _native.ApplyForce(key, command.Force.X, command.Force.Y));
- return AcceptAndStore(command.Header, fingerprint, "body.apply_force");
- }
- }
-
- public YmirCommandReceipt ApplyTorque(YmirApplyTorqueCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "body.apply_torque", writer =>
- {
- WriteString(writer, command.BodyId);
- writer.Write(command.Torque);
- });
- RecordCommand(command.Header, new YmirApplyTorqueJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "body.apply_torque") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "body.apply_torque", fingerprint);
- }
- if (!TryBody(command.BodyId, out var key, out var body))
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.UnknownBody);
- }
- if (body.IsStatic || body.IsKinematic)
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.StaticBody);
- }
- if (!float.IsFinite(command.Torque))
- {
- return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.InvalidCommand);
- }
-
- RunNative(() => _native.ApplyTorque(key, command.Torque));
- return AcceptAndStore(command.Header, fingerprint, "body.apply_torque");
- }
- }
-
- public YmirSessionStepResult Step(YmirStepSessionCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var submittedFields = command.Fields;
- var fieldsValid = submittedFields != null && FieldsAreValid(submittedFields);
- var orderedFields = fieldsValid
- ? submittedFields!.OrderBy(field => field.Id, StringComparer.Ordinal).ToArray()
- : [];
- var fingerprint = Fingerprint(command.Header, "session.step", writer =>
- {
- writer.Write(command.DeltaTime);
- writer.Write(command.SubstepCount);
- if (submittedFields == null)
- {
- writer.Write(-1);
- return;
- }
- var fields = fieldsValid ? orderedFields : submittedFields;
- writer.Write(fields.Count);
- foreach (var field in fields)
- {
- WriteField(writer, field);
- }
- });
- RecordCommand(command.Header, new YmirStepSessionJournalEntry(command));
- if (Preflight(command.Header, fingerprint, "session.step") is { } previous)
- {
- if (previous.Result is YmirSessionStepResult replay)
- {
- return replay;
- }
- var rejected = ReceiptFrom(previous, command.Header, "session.step", fingerprint);
- return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []);
- }
- if (!float.IsFinite(command.DeltaTime) || command.DeltaTime <= 0.0f ||
- command.SubstepCount <= 0 || !fieldsValid)
- {
- var rejected = RejectAndStore(command.Header, fingerprint, "session.step", YmirCommandError.InvalidCommand);
- return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []);
- }
-
- var nativeFields = orderedFields
- .Select(field => new Box3DField(field.Position.X, field.Position.Y, field.Strength, field.Radius))
- .ToArray();
- YmirContactFact[] facts;
- try
- {
- _native.Step(command.DeltaTime, nativeFields, command.SubstepCount);
- UpdateBodyProjection(_native.CopyBodies());
- _time += command.DeltaTime;
- _fields = orderedFields;
- _stepIndex += 1;
- _revision += 1;
- facts = ProjectFacts(_native.CopyContactEvents()).ToArray();
- PruneRetiredIdentity();
- }
- catch
- {
- Poison();
- throw;
- }
- try
- {
- var receipt = AcceptedReceipt(command.Header, "session.step", _revision - 1, _revision,
- facts.Select(fact => fact.FactId).ToArray());
- var result = new YmirSessionStepResult(receipt, SnapshotCore(), _revision, _stepIndex, facts);
- _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, result));
- return result;
- }
- catch
- {
- Poison();
- throw;
- }
- }
- }
-
- public YmirWorld Snapshot()
- {
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- return SnapshotCore();
- }
- }
-
- public YmirSessionCircleCastResult CastCircle(YmirSessionCircleCastQuery query)
- {
- ArgumentNullException.ThrowIfNull(query);
- lock (_gate)
- {
- var error = QueryPreflight(query.QueryId, query.ExpectedRevision, query.CandidateBodyIds, out var bodies);
- if (error != YmirQueryError.None)
- {
- return new YmirSessionCircleCastResult(
- query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, error, []);
- }
-
- try
- {
- var result = YmirQueries.CastCircle(new CircleCastQueryRequest(
- query.Origin, query.Direction, query.Distance, query.Radius, bodies));
- return new YmirSessionCircleCastResult(
- query.QueryId, _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.None, result.Hits);
- }
- catch (ArgumentException)
- {
- return new YmirSessionCircleCastResult(
- query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.InvalidQuery, []);
- }
- }
- }
-
- public YmirSessionCircleOverlapResult OverlapCircle(YmirSessionCircleOverlapQuery query)
- {
- ArgumentNullException.ThrowIfNull(query);
- lock (_gate)
- {
- var error = QueryPreflight(query.QueryId, query.ExpectedRevision, query.CandidateBodyIds, out var bodies);
- if (error != YmirQueryError.None)
- {
- return new YmirSessionCircleOverlapResult(
- query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, error, []);
- }
-
- try
- {
- var result = YmirQueries.OverlapCircle(new CircleOverlapQueryRequest(query.Center, query.Radius, bodies));
- return new YmirSessionCircleOverlapResult(
- query.QueryId, _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.None, result.Hits);
- }
- catch (ArgumentException)
- {
- return new YmirSessionCircleOverlapResult(
- query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.InvalidQuery, []);
- }
- }
- }
-
- public YmirCommandReceipt Dispose(YmirDisposeSessionCommand command)
- {
- ArgumentNullException.ThrowIfNull(command);
- lock (_gate)
- {
- var fingerprint = Fingerprint(command.Header, "session.dispose", _ => { });
- if (Preflight(command.Header, fingerprint, "session.dispose") is { } previous)
- {
- return ReceiptFrom(previous, command.Header, "session.dispose", fingerprint);
- }
-
- var before = _revision;
- _native.Dispose();
- _disposed = true;
- _revision += 1;
- var receipt = AcceptedReceipt(command.Header, "session.dispose", before, _revision, []);
- _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, receipt));
- return receipt;
- }
- }
-
- public void Dispose()
- {
- lock (_gate)
- {
- if (_disposed)
- {
- return;
- }
- _native.Dispose();
- _disposed = true;
- }
- }
-
- private void SpawnCore(PhysicsBody body)
- {
- var key = NextKey();
- var generation = _nextBodyGeneration++;
- var canonicalBody = body with { Torque = 0.0f, Direction = DirectionOrDefault(body.Direction) };
- RunNative(() =>
- {
- _native.Spawn(ToNative(key, canonicalBody));
- _activeKeysById.Add(canonicalBody.Id, key);
- _idsByKey.Add(key, canonicalBody.Id);
- _generationsByKey.Add(key, generation);
- _bodies.Add(canonicalBody.Id, canonicalBody);
- });
- }
-
- private YmirQueryError QueryPreflight(
- string? queryId,
- long expectedRevision,
- IReadOnlyList? candidateBodyIds,
- out PhysicsBody[] bodies)
- {
- bodies = [];
- if (_faulted)
- {
- return YmirQueryError.SessionFaulted;
- }
- if (_disposed)
- {
- return YmirQueryError.SessionDisposed;
- }
- if (string.IsNullOrWhiteSpace(queryId) || expectedRevision < 0 || candidateBodyIds == null)
- {
- return YmirQueryError.InvalidQuery;
- }
- if (expectedRevision != _revision)
- {
- return YmirQueryError.StaleRevision;
- }
-
- var seen = new HashSet(StringComparer.Ordinal);
- var selected = new List(candidateBodyIds.Count);
- foreach (var bodyId in candidateBodyIds)
- {
- if (string.IsNullOrWhiteSpace(bodyId) || !seen.Add(bodyId))
- {
- return YmirQueryError.InvalidQuery;
- }
- if (!_bodies.TryGetValue(bodyId, out var body))
- {
- return YmirQueryError.UnknownBody;
- }
- selected.Add(body);
- }
- bodies = selected.ToArray();
- return YmirQueryError.None;
- }
-
- private IReadOnlyList ProjectFacts(IReadOnlyList nativeFacts)
- {
- var projected = new List(nativeFacts.Count);
- var ephemeralEpisodes = new Dictionary();
- var newEpisodeOrdinals = new Dictionary();
- var factOrdinals = new Dictionary<(
- ContactPair Pair,
- long StartStep,
- long EpisodeOrdinal,
- YmirContactFactKind Kind), int>();
- foreach (var native in nativeFacts)
- {
- var canonical = CanonicalizeContact(native);
- var pair = new ContactPair(
- canonical.BodyA,
- canonical.BodyAGeneration,
- canonical.BodyB,
- canonical.BodyBGeneration);
- ActiveEpisode episode;
- if (native.Kind == Box3DContactKind.Begin)
- {
- if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!))
- {
- episode = NewEpisode(pair, newEpisodeOrdinals);
- _episodesByNativeContact[native.ContactKey] = episode;
- }
- }
- else if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!) &&
- !ephemeralEpisodes.TryGetValue(native.ContactKey, out episode!))
- {
- episode = NewEpisode(pair, newEpisodeOrdinals);
- ephemeralEpisodes.Add(native.ContactKey, episode);
- }
-
- var kind = native.Kind switch
- {
- Box3DContactKind.Begin => YmirContactFactKind.Begin,
- Box3DContactKind.Hit => YmirContactFactKind.Hit,
- Box3DContactKind.End => YmirContactFactKind.End,
- _ => throw new InvalidOperationException($"Unknown Box3D contact fact kind {native.Kind}.")
- };
- var ordinalKey = (pair, episode.StartStepIndex, episode.Ordinal, kind);
- var ordinal = factOrdinals.GetValueOrDefault(ordinalKey);
- factOrdinals[ordinalKey] = ordinal + 1;
- var pairId = PairId(pair);
- var contactId = $"{_sessionGeneration}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}";
- var factId = $"{_sessionGeneration}:step:{_stepIndex}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}:{kind.ToString().ToLowerInvariant()}:{ordinal}";
- var hasDetails = native.HasDetails;
- var fact = new YmirContactFact(
- factId,
- contactId,
- kind,
- _sessionId,
- _sessionGeneration,
- _stepIndex,
- canonical.BodyA,
- canonical.BodyAGeneration,
- canonical.BodyB,
- canonical.BodyBGeneration,
- hasDetails ? canonical.Point : null,
- hasDetails ? canonical.Normal : null,
- hasDetails ? native.Penetration : null,
- hasDetails ? native.RelativeSpeed : null);
- projected.Add(new ProjectedFact(fact, episode.StartStepIndex, episode.Ordinal, ordinal));
-
- if (native.Kind == Box3DContactKind.End)
- {
- _episodesByNativeContact.Remove(native.ContactKey);
- ephemeralEpisodes.Remove(native.ContactKey);
- }
- }
-
- return projected
- .OrderBy(item => item.Fact.BodyA, StringComparer.Ordinal)
- .ThenBy(item => item.Fact.BodyAGeneration)
- .ThenBy(item => item.Fact.BodyB, StringComparer.Ordinal)
- .ThenBy(item => item.Fact.BodyBGeneration)
- .ThenBy(item => item.EpisodeStartStep)
- .ThenBy(item => item.EpisodeOrdinal)
- .ThenBy(item => FactKindOrder(item.Fact.Kind))
- .ThenBy(item => item.Ordinal)
- .Select(item => item.Fact)
- .ToArray();
- }
-
- private CanonicalContact CanonicalizeContact(Box3DContactFact fact)
- {
- var idA = ResolveId(fact.StableIdA);
- var idB = ResolveId(fact.StableIdB);
- var generationA = _generationsByKey[fact.StableIdA];
- var generationB = _generationsByKey[fact.StableIdB];
- var swap = StringComparer.Ordinal.Compare(idA, idB) > 0 ||
- (StringComparer.Ordinal.Equals(idA, idB) && generationA > generationB);
- return swap
- ? new CanonicalContact(
- idB, generationB, idA, generationA,
- new Vec2(fact.PointX, fact.PointZ),
- new Vec2(-fact.NormalX, -fact.NormalZ))
- : new CanonicalContact(
- idA, generationA, idB, generationB,
- new Vec2(fact.PointX, fact.PointZ),
- new Vec2(fact.NormalX, fact.NormalZ));
- }
-
- private void UpdateBodyProjection(IReadOnlyList states)
- {
- foreach (var state in states)
- {
- var id = ResolveId(state.StableId);
- if (!_bodies.TryGetValue(id, out var body) || _activeKeysById.GetValueOrDefault(id) != state.StableId)
- {
- throw new InvalidOperationException($"Box3D returned inactive body key {state.StableId}.");
- }
- _bodies[id] = body with
- {
- Position = new Vec2(state.PositionX, state.PositionZ),
- Velocity = new Vec2(state.VelocityX, state.VelocityZ),
- Direction = new Vec2(state.DirectionX, state.DirectionZ),
- AngularVelocity = state.AngularVelocity,
- Torque = 0.0f
- };
- }
- }
-
- private LedgerEntry? Preflight(YmirCommandHeader header, string fingerprint, string kind)
- {
- ValidateHeader(header);
- if (_ledger.TryGetValue(header.CommandId, out var existing))
- {
- return existing.Fingerprint == fingerprint
- ? existing
- : new LedgerEntry(fingerprint, ConflictReceipt(header, kind, fingerprint));
- }
- if (_faulted)
- {
- var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionFaulted);
- var entry = new LedgerEntry(fingerprint, rejected);
- _ledger.Add(header.CommandId, entry);
- return entry;
- }
- if (_disposed)
- {
- var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionDisposed);
- var entry = new LedgerEntry(fingerprint, rejected);
- _ledger.Add(header.CommandId, entry);
- return entry;
- }
- if (header.ExpectedRevision != _revision)
- {
- var rejected = RejectedReceipt(header, kind, YmirCommandError.StaleRevision);
- var entry = new LedgerEntry(fingerprint, rejected);
- _ledger.Add(header.CommandId, entry);
- return entry;
- }
- return null;
- }
-
- private YmirCommandReceipt ReceiptFrom(
- LedgerEntry entry,
- YmirCommandHeader header,
- string kind,
- string fingerprint)
- {
- if (entry.Fingerprint != fingerprint)
- {
- return RejectedReceipt(header, kind, YmirCommandError.CommandIdConflict);
- }
- return entry.Result switch
- {
- YmirCommandReceipt receipt => receipt,
- YmirSessionStepResult step => step.Receipt,
- _ => throw new InvalidOperationException("Unknown Ymir receipt ledger entry.")
- };
- }
-
- private YmirCommandReceipt AcceptAndStore(YmirCommandHeader header, string fingerprint, string kind)
- {
- try
- {
- var before = _revision;
- _revision += 1;
- var receipt = AcceptedReceipt(header, kind, before, _revision, []);
- _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt));
- return receipt;
- }
- catch
- {
- Poison();
- throw;
- }
- }
-
- private YmirCommandReceipt RejectAndStore(
- YmirCommandHeader header,
- string fingerprint,
- string kind,
- YmirCommandError error)
- {
- var receipt = RejectedReceipt(header, kind, error);
- _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt));
- return receipt;
- }
-
- private YmirCommandReceipt AcceptedReceipt(
- YmirCommandHeader header,
- string kind,
- long before,
- long after,
- IReadOnlyList facts) =>
- new(
- $"{_sessionGeneration}:receipt:{header.CommandId}",
- _sessionId,
- _sessionGeneration,
- header.CommandId,
- kind,
- YmirCommandOutcome.Accepted,
- YmirCommandError.None,
- before,
- after,
- _stepIndex,
- facts);
-
- private YmirCommandReceipt RejectedReceipt(
- YmirCommandHeader header,
- string kind,
- YmirCommandError error) =>
- new(
- $"{_sessionGeneration}:receipt:{header.CommandId}",
- _sessionId,
- _sessionGeneration,
- header.CommandId,
- kind,
- YmirCommandOutcome.Rejected,
- error,
- _revision,
- _revision,
- _stepIndex,
- []);
-
- private YmirCommandReceipt ConflictReceipt(
- YmirCommandHeader header,
- string kind,
- string fingerprint)
- {
- var conflictId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint)))
- .ToLowerInvariant();
- return new YmirCommandReceipt(
- $"{_sessionGeneration}:receipt-conflict:{header.CommandId}:{conflictId}",
- _sessionId,
- _sessionGeneration,
- header.CommandId,
- kind,
- YmirCommandOutcome.Rejected,
- YmirCommandError.CommandIdConflict,
- _revision,
- _revision,
- _stepIndex,
- []);
- }
-
- private YmirWorld SnapshotCore() => new(
- _time,
- _bodies.Values.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray(),
- _fields.ToArray());
-
- private void RecordCommand(YmirCommandHeader header, YmirSessionJournalEntry entry)
- {
- if (!_ledger.ContainsKey(header.CommandId))
- _journal.Add(entry);
- }
-
- private void Replay(YmirSessionJournalEntry entry)
- {
- switch (entry)
- {
- case YmirSpawnBodyJournalEntry value: Spawn(value.Command); break;
- case YmirRemoveBodyJournalEntry value: Remove(value.Command); break;
- case YmirTeleportBodyJournalEntry value: Teleport(value.Command); break;
- case YmirSetBodyVelocityJournalEntry value: SetVelocity(value.Command); break;
- case YmirConfigureBodyJournalEntry value: Configure(value.Command); break;
- case YmirApplyForceJournalEntry value: ApplyForce(value.Command); break;
- case YmirApplyTorqueJournalEntry value: ApplyTorque(value.Command); break;
- case YmirStepSessionJournalEntry value: Step(value.Command); break;
- default: throw new InvalidOperationException($"Unknown Ymir journal entry '{entry?.GetType().FullName ?? ""}'.");
- }
- }
-
- private void VerifyCheckpoint(YmirSessionCheckpoint checkpoint)
- {
- var world = SnapshotCore();
- var active = _episodesByNativeContact.Values
- .Distinct()
- .Select(EpisodeCheckpoint)
- .OrderBy(value => value.BodyA, StringComparer.Ordinal)
- .ThenBy(value => value.BodyAGeneration)
- .ThenBy(value => value.BodyB, StringComparer.Ordinal)
- .ThenBy(value => value.BodyBGeneration)
- .ThenBy(value => value.StartStepIndex)
- .ThenBy(value => value.Ordinal)
- .ToArray();
- var expectedBodies = (checkpoint.World.Bodies ?? Array.Empty())
- .OrderBy(value => value.Id, StringComparer.Ordinal).ToArray();
- var expectedFields = checkpoint.World.Fields ?? Array.Empty();
- if (_revision != checkpoint.Revision || _stepIndex != checkpoint.StepIndex ||
- _time != checkpoint.Time || _nextBodyGeneration != checkpoint.NextBodyGeneration ||
- world.Time != checkpoint.World.Time || !world.Bodies.SequenceEqual(expectedBodies) ||
- !world.Fields.SequenceEqual(expectedFields) ||
- !active.SequenceEqual(checkpoint.ActiveContactEpisodes) ||
- !string.Equals(JournalDigest(), checkpoint.JournalDigest, StringComparison.Ordinal))
- {
- throw new InvalidOperationException(
- $"Ymir checkpoint replay diverged for session '{checkpoint.SessionId}'.");
- }
- }
-
- private string JournalDigest()
- {
- using var stream = new MemoryStream();
- using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
- {
- writer.Write(1);
- writer.Write(_journal.Count);
- foreach (var entry in _journal)
- {
- var header = JournalHeader(entry);
- WriteString(writer, entry.GetType().Name);
- WriteString(writer, header.CommandId);
- if (!_ledger.TryGetValue(header.CommandId, out var ledger))
- throw new InvalidOperationException($"Ymir journal command '{header.CommandId}' has no ledger result.");
- WriteString(writer, ledger.Fingerprint);
- }
- }
- return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length))))
- .ToLowerInvariant();
- }
-
- private static YmirCommandHeader JournalHeader(YmirSessionJournalEntry entry) => entry switch
- {
- YmirSpawnBodyJournalEntry value => value.Command.Header,
- YmirRemoveBodyJournalEntry value => value.Command.Header,
- YmirTeleportBodyJournalEntry value => value.Command.Header,
- YmirSetBodyVelocityJournalEntry value => value.Command.Header,
- YmirConfigureBodyJournalEntry value => value.Command.Header,
- YmirApplyForceJournalEntry value => value.Command.Header,
- YmirApplyTorqueJournalEntry value => value.Command.Header,
- YmirStepSessionJournalEntry value => value.Command.Header,
- _ => throw new InvalidOperationException($"Unknown Ymir journal entry '{entry?.GetType().FullName ?? ""}'.")
- };
-
- private static YmirContactEpisodeCheckpoint EpisodeCheckpoint(ActiveEpisode episode) => new(
- episode.Pair.BodyA,
- episode.Pair.BodyAGeneration,
- episode.Pair.BodyB,
- episode.Pair.BodyBGeneration,
- episode.StartStepIndex,
- episode.Ordinal);
-
- private static void ValidateCheckpointHeader(YmirSessionCheckpoint checkpoint)
- {
- ArgumentNullException.ThrowIfNull(checkpoint);
- if (!string.Equals(checkpoint.FormatId, YmirSessionCheckpointContract.FormatId, StringComparison.Ordinal) ||
- !string.Equals(checkpoint.RuntimeFingerprint, YmirSessionCheckpointContract.RuntimeFingerprint, StringComparison.Ordinal))
- throw new InvalidOperationException("Ymir checkpoint format or runtime provenance is incompatible.");
- if (string.IsNullOrWhiteSpace(checkpoint.SessionId) || string.IsNullOrWhiteSpace(checkpoint.SessionGeneration) ||
- checkpoint.Revision < 0 || checkpoint.StepIndex < 0 || checkpoint.NextBodyGeneration < 1 ||
- !float.IsFinite(checkpoint.Time) || checkpoint.Time < 0 ||
- !float.IsFinite(checkpoint.InitialTime) || checkpoint.InitialTime < 0 ||
- checkpoint.InitialBodies == null || checkpoint.Journal == null || checkpoint.World == null ||
- checkpoint.ActiveContactEpisodes == null || string.IsNullOrWhiteSpace(checkpoint.JournalDigest))
- throw new InvalidOperationException("Ymir checkpoint header is incomplete or invalid.");
- }
-
- private bool TryBody(string? id, out ulong key, out PhysicsBody body)
- {
- if (!string.IsNullOrWhiteSpace(id) &&
- _activeKeysById.TryGetValue(id, out key) &&
- _bodies.TryGetValue(id, out body!))
- {
- return true;
- }
- key = 0;
- body = null!;
- return false;
- }
-
- private string ResolveId(ulong key) => _idsByKey.TryGetValue(key, out var id)
- ? id
- : throw new InvalidOperationException($"Box3D returned unknown stable body key {key}.");
-
- private ActiveEpisode NewEpisode(ContactPair pair, IDictionary ordinals)
- {
- var ordinal = (ordinals.TryGetValue(pair, out var previous) ? previous : 0) + 1;
- ordinals[pair] = ordinal;
- return new ActiveEpisode(_stepIndex, ordinal, pair);
- }
-
- private void PruneRetiredIdentity()
- {
- var activeKeys = _activeKeysById.Values.ToHashSet();
- foreach (var key in _idsByKey.Keys.Where(key => !activeKeys.Contains(key)).ToArray())
- {
- var id = _idsByKey[key];
- var generation = _generationsByKey[key];
- if (_episodesByNativeContact.Values.Any(active =>
- (active.Pair.BodyA == id && active.Pair.BodyAGeneration == generation) ||
- (active.Pair.BodyB == id && active.Pair.BodyBGeneration == generation)))
- {
- throw new InvalidOperationException(
- $"Box3D did not close every contact episode for removed body '{id}' generation {generation}.");
- }
- _idsByKey.Remove(key);
- _generationsByKey.Remove(key);
- }
- }
-
- private void RunNative(Action operation)
- {
- try
- {
- operation();
- }
- catch
- {
- Poison();
- throw;
- }
- }
-
- private void Poison()
- {
- _native.Dispose();
- _disposed = true;
- _faulted = true;
- }
-
- private ulong NextKey()
- {
- if (_nextNativeKey == 0)
- {
- throw new InvalidOperationException("Ymir exhausted its native body key space.");
- }
- return _nextNativeKey++;
- }
-
- private static Box3DBody ToNative(ulong key, PhysicsBody body)
- {
- var direction = DirectionOrDefault(body.Direction);
- return new Box3DBody(
- key,
- body.CollisionCategoryBits,
- body.CollisionMaskBits,
- body.Position.X,
- body.Position.Y,
- body.Velocity.X,
- body.Velocity.Y,
- direction.X,
- direction.Y,
- body.AngularVelocity,
- 0.0f,
- body.Radius,
- body.Mass,
- body.Restitution,
- body.IsStatic,
- body.IsKinematic,
- body.IsBullet,
- body.ParticipatesInFields,
- body.CollisionGroupIndex);
- }
-
- private static Vec2 DirectionOrDefault(Vec2? direction) =>
- direction is { } value && ValidDirection(value) ? Normalize(value) : new Vec2(0.0f, 1.0f);
-
- private static Vec2 Normalize(Vec2 value)
- {
- var inverseLength = 1.0f / MathF.Sqrt(value.X * value.X + value.Y * value.Y);
- return new Vec2(value.X * inverseLength, value.Y * inverseLength);
- }
-
- private static void ValidateHeader(YmirCommandHeader header)
- {
- ArgumentNullException.ThrowIfNull(header);
- if (string.IsNullOrWhiteSpace(header.CommandId))
- {
- throw new ArgumentException("Command id is required.", nameof(header));
- }
- if (header.ExpectedRevision < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(header), "Expected revision must be non-negative.");
- }
- }
-
- private static void ValidateUniqueBodyIds(IReadOnlyList bodies)
- {
- var ids = new HashSet(StringComparer.Ordinal);
- foreach (var body in bodies)
- {
- if (!ids.Add(body.Id))
- {
- throw new ArgumentException($"Ymir body id '{body.Id}' occurs more than once.", nameof(bodies));
- }
- }
- }
-
- private static bool TryValidateBody(PhysicsBody body, bool allowTorque)
- {
- try
- {
- ValidateBody(body, allowTorque);
- return true;
- }
- catch (ArgumentException)
- {
- return false;
- }
- }
-
- private static void ValidateBody(PhysicsBody body, bool allowTorque)
- {
- ArgumentNullException.ThrowIfNull(body);
- if (string.IsNullOrWhiteSpace(body.Id) || !Finite(body.Position) || !Finite(body.Velocity) ||
- !float.IsFinite(body.Radius) || body.Radius <= 0.0f ||
- !float.IsFinite(body.Mass) || (!body.IsStatic && body.Mass <= 0.0f) ||
- (body.IsStatic && body.IsKinematic) ||
- !float.IsFinite(body.Restitution) || body.Restitution < 0.0f ||
- body.CollisionCategoryBits == 0 ||
- (body.Direction is { } direction && !ValidDirection(direction)) ||
- !float.IsFinite(body.AngularVelocity) || !float.IsFinite(body.Torque) ||
- (!allowTorque && body.Torque != 0.0f))
- {
- throw new ArgumentException("Body definition is not valid for a retained Ymir session.", nameof(body));
- }
- }
-
- private static bool FieldsAreValid(IReadOnlyList fields)
- {
- var ids = new HashSet(StringComparer.Ordinal);
- return fields.All(field => field != null &&
- !string.IsNullOrWhiteSpace(field.Id) && ids.Add(field.Id) && Finite(field.Position) &&
- float.IsFinite(field.Strength) && float.IsFinite(field.Radius) && field.Radius >= 0.0f);
- }
-
- private static bool Finite(Vec2 value) => float.IsFinite(value.X) && float.IsFinite(value.Y);
-
- private static bool ValidDirection(Vec2 value) =>
- Finite(value) && value.X * value.X + value.Y * value.Y > 1.0e-8f;
-
- private static string Fingerprint(
- YmirCommandHeader header,
- string kind,
- Action writePayload)
- {
- using var stream = new MemoryStream();
- using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
- {
- writer.Write(1);
- WriteString(writer, kind);
- writer.Write(header.ExpectedRevision);
- writePayload(writer);
- }
- return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length))))
- .ToLowerInvariant();
- }
-
- private static void WriteBody(BinaryWriter writer, PhysicsBody? body)
- {
- writer.Write(body != null);
- if (body == null)
- {
- return;
- }
- WriteString(writer, body.Id);
- Write(writer, body.Position);
- Write(writer, body.Velocity);
- writer.Write(body.Radius);
- writer.Write(body.Mass);
- writer.Write(body.IsStatic);
- writer.Write(body.Restitution);
- writer.Write(body.Direction.HasValue);
- if (body.Direction is { } direction)
- {
- Write(writer, direction);
- }
- writer.Write(body.AngularVelocity);
- writer.Write(body.Torque);
- writer.Write(body.IsKinematic);
- writer.Write(body.IsBullet);
- writer.Write(body.ParticipatesInFields);
- writer.Write(body.CollisionCategoryBits);
- writer.Write(body.CollisionMaskBits);
- writer.Write(body.CollisionGroupIndex);
- }
-
- private static void WriteField(BinaryWriter writer, RadialField? field)
- {
- writer.Write(field != null);
- if (field == null)
- {
- return;
- }
- WriteString(writer, field.Id);
- Write(writer, field.Position);
- writer.Write(field.Strength);
- writer.Write(field.Radius);
- }
-
- private static void Write(BinaryWriter writer, Vec2 value)
- {
- writer.Write(value.X);
- writer.Write(value.Y);
- }
-
- private static void WriteString(BinaryWriter writer, string? value)
- {
- writer.Write(value != null);
- if (value != null)
- {
- writer.Write(value);
- }
- }
-
- private static string PairId(ContactPair pair)
- {
- var source = $"{pair.BodyA.Length}:{pair.BodyA}:{pair.BodyAGeneration}:{pair.BodyB.Length}:{pair.BodyB}:{pair.BodyBGeneration}";
- return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source))).ToLowerInvariant();
- }
-
- private static int FactKindOrder(Box3DContactKind kind) => kind switch
- {
- Box3DContactKind.Begin => 0,
- Box3DContactKind.Hit => 1,
- Box3DContactKind.End => 2,
- _ => 3
- };
-
- private static int FactKindOrder(YmirContactFactKind kind) => kind switch
- {
- YmirContactFactKind.Begin => 0,
- YmirContactFactKind.Hit => 1,
- YmirContactFactKind.End => 2,
- _ => 3
- };
-
- private sealed record LedgerEntry(string Fingerprint, object Result);
-
- private sealed record ContactPair(string BodyA, long BodyAGeneration, string BodyB, long BodyBGeneration);
-
- private sealed record ActiveEpisode(long StartStepIndex, long Ordinal, ContactPair Pair);
-
- private sealed record ProjectedFact(
- YmirContactFact Fact,
- long EpisodeStartStep,
- long EpisodeOrdinal,
- int Ordinal);
-
- private sealed record CanonicalContact(
- string BodyA,
- long BodyAGeneration,
- string BodyB,
- long BodyBGeneration,
- Vec2 Point,
- Vec2 Normal);
-}
diff --git a/src/Ymir.Core/YmirSessionCheckpointCodec.cs b/src/Ymir.Core/YmirSessionCheckpointCodec.cs
deleted file mode 100644
index 049f63d..0000000
--- a/src/Ymir.Core/YmirSessionCheckpointCodec.cs
+++ /dev/null
@@ -1,447 +0,0 @@
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Ymir.Core;
-
-public static class YmirSessionCheckpointCodec
-{
- private const uint Magic = 0x43534D59; // YMSC
- private const uint JournalMagic = 0x4A534D59; // YMSJ
- private const uint ResumeMagic = 0x52534D59; // YMSR
- private const int Version = 1;
- private const int MaximumPayloadBytes = 256 * 1024 * 1024;
- private const int MaximumCollectionCount = 4 * 1024 * 1024;
- private const int MaximumStringBytes = 1024 * 1024;
- private const int ChecksumBytes = 32;
-
- public static byte[] Encode(YmirSessionCheckpoint checkpoint)
- {
- ArgumentNullException.ThrowIfNull(checkpoint);
- using var stream = new MemoryStream();
- using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
- writer.Write(Magic);
- writer.Write(Version);
- WriteString(writer, checkpoint.FormatId);
- WriteString(writer, checkpoint.RuntimeFingerprint);
- WriteString(writer, checkpoint.SessionId);
- WriteString(writer, checkpoint.SessionGeneration);
- writer.Write(checkpoint.Revision);
- writer.Write(checkpoint.StepIndex);
- writer.Write(checkpoint.Time);
- writer.Write(checkpoint.NextBodyGeneration);
- WriteBodies(writer, checkpoint.InitialBodies);
- writer.Write(checkpoint.InitialTime);
- WriteJournal(writer, checkpoint.Journal);
- WriteString(writer, checkpoint.JournalDigest);
- WriteWorld(writer, checkpoint.World);
- WriteEpisodes(writer, checkpoint.ActiveContactEpisodes);
- writer.Flush();
- if (stream.Length > MaximumPayloadBytes - ChecksumBytes)
- throw new InvalidOperationException("Ymir checkpoint exceeds the supported payload size.");
- var content = stream.ToArray();
- var checksum = SHA256.HashData(content);
- return [.. content, .. checksum];
- }
-
- public static YmirSessionCheckpoint Decode(ReadOnlySpan payload)
- {
- var content = VerifiedContent(payload);
- try
- {
- using var stream = new MemoryStream(content, writable: false);
- using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
- if (reader.ReadUInt32() != Magic || reader.ReadInt32() != Version)
- throw new InvalidDataException("Ymir checkpoint codec header is incompatible.");
- var checkpoint = new YmirSessionCheckpoint(
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- reader.ReadInt64(),
- reader.ReadInt64(),
- reader.ReadSingle(),
- reader.ReadInt64(),
- ReadBodies(reader),
- reader.ReadSingle(),
- ReadJournal(reader),
- ReadString(reader),
- ReadWorld(reader),
- ReadEpisodes(reader));
- if (stream.Position != stream.Length)
- throw new InvalidDataException("Ymir checkpoint contains trailing data.");
- return checkpoint;
- }
- catch (InvalidDataException)
- {
- throw;
- }
- catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
- {
- throw new InvalidDataException("Ymir checkpoint payload is corrupt.", error);
- }
- }
-
- public static byte[] Encode(YmirSessionJournalChunk chunk)
- {
- ArgumentNullException.ThrowIfNull(chunk);
- return EncodeChecksummed(writer =>
- {
- writer.Write(JournalMagic);
- writer.Write(Version);
- WriteString(writer, chunk.FormatId);
- WriteString(writer, chunk.RuntimeFingerprint);
- WriteString(writer, chunk.SessionId);
- WriteString(writer, chunk.SessionGeneration);
- writer.Write(chunk.FirstEntryIndex);
- WriteJournal(writer, chunk.Entries);
- });
- }
-
- public static YmirSessionJournalChunk DecodeJournalChunk(ReadOnlySpan payload)
- {
- var content = VerifiedContent(payload);
- try
- {
- using var stream = new MemoryStream(content, writable: false);
- using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
- if (reader.ReadUInt32() != JournalMagic || reader.ReadInt32() != Version)
- throw new InvalidDataException("Ymir journal chunk codec header is incompatible.");
- var chunk = new YmirSessionJournalChunk(
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- reader.ReadInt64(),
- ReadJournal(reader));
- if (stream.Position != stream.Length)
- throw new InvalidDataException("Ymir journal chunk contains trailing data.");
- return chunk;
- }
- catch (InvalidDataException)
- {
- throw;
- }
- catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
- {
- throw new InvalidDataException("Ymir journal chunk payload is corrupt.", error);
- }
- }
-
- public static byte[] Encode(YmirSessionResumeDescriptor descriptor)
- {
- ArgumentNullException.ThrowIfNull(descriptor);
- return EncodeChecksummed(writer =>
- {
- writer.Write(ResumeMagic);
- writer.Write(Version);
- WriteString(writer, descriptor.FormatId);
- WriteString(writer, descriptor.RuntimeFingerprint);
- WriteString(writer, descriptor.SessionId);
- WriteString(writer, descriptor.SessionGeneration);
- writer.Write(descriptor.Revision);
- writer.Write(descriptor.StepIndex);
- writer.Write(descriptor.Time);
- writer.Write(descriptor.NextBodyGeneration);
- WriteBodies(writer, descriptor.InitialBodies);
- writer.Write(descriptor.InitialTime);
- writer.Write(descriptor.JournalEntryCount);
- WriteString(writer, descriptor.JournalDigest);
- WriteWorld(writer, descriptor.World);
- WriteEpisodes(writer, descriptor.ActiveContactEpisodes);
- });
- }
-
- public static YmirSessionResumeDescriptor DecodeResumeDescriptor(ReadOnlySpan payload)
- {
- var content = VerifiedContent(payload);
- try
- {
- using var stream = new MemoryStream(content, writable: false);
- using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
- if (reader.ReadUInt32() != ResumeMagic || reader.ReadInt32() != Version)
- throw new InvalidDataException("Ymir resume descriptor codec header is incompatible.");
- var descriptor = new YmirSessionResumeDescriptor(
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- ReadString(reader),
- reader.ReadInt64(),
- reader.ReadInt64(),
- reader.ReadSingle(),
- reader.ReadInt64(),
- ReadBodies(reader),
- reader.ReadSingle(),
- reader.ReadInt64(),
- ReadString(reader),
- ReadWorld(reader),
- ReadEpisodes(reader));
- if (stream.Position != stream.Length)
- throw new InvalidDataException("Ymir resume descriptor contains trailing data.");
- return descriptor;
- }
- catch (InvalidDataException)
- {
- throw;
- }
- catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
- {
- throw new InvalidDataException("Ymir resume descriptor payload is corrupt.", error);
- }
- }
-
- private static byte[] EncodeChecksummed(Action write)
- {
- using var stream = new MemoryStream();
- using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
- {
- write(writer);
- writer.Flush();
- }
- if (stream.Length > MaximumPayloadBytes - ChecksumBytes)
- throw new InvalidOperationException("Ymir persistence payload exceeds the supported size.");
- var content = stream.ToArray();
- return [.. content, .. SHA256.HashData(content)];
- }
-
- private static byte[] VerifiedContent(ReadOnlySpan payload)
- {
- if (payload.Length <= ChecksumBytes || payload.Length > MaximumPayloadBytes)
- throw new InvalidDataException("Ymir persistence payload size is invalid.");
- var content = payload[..^ChecksumBytes];
- var expectedChecksum = payload[^ChecksumBytes..];
- Span actualChecksum = stackalloc byte[ChecksumBytes];
- SHA256.HashData(content, actualChecksum);
- if (!CryptographicOperations.FixedTimeEquals(actualChecksum, expectedChecksum))
- throw new InvalidDataException("Ymir persistence payload checksum is invalid.");
- return content.ToArray();
- }
-
- private static void WriteJournal(BinaryWriter writer, IReadOnlyList entries)
- {
- WriteCount(writer, entries?.Count ?? -1);
- foreach (var entry in entries!)
- {
- switch (entry)
- {
- case YmirSpawnBodyJournalEntry value:
- writer.Write((byte)1); WriteHeader(writer, value.Command.Header); WriteBody(writer, value.Command.Body); break;
- case YmirRemoveBodyJournalEntry value:
- writer.Write((byte)2); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); break;
- case YmirTeleportBodyJournalEntry value:
- writer.Write((byte)3); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.Position); WriteVec2(writer, value.Command.Direction); break;
- case YmirSetBodyVelocityJournalEntry value:
- writer.Write((byte)4); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.LinearVelocity); writer.Write(value.Command.AngularVelocity); break;
- case YmirConfigureBodyJournalEntry value:
- writer.Write((byte)5); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); writer.Write(value.Command.Radius); writer.Write(value.Command.Mass); writer.Write(value.Command.IsStatic); writer.Write(value.Command.Restitution); writer.Write(value.Command.IsKinematic); break;
- case YmirApplyForceJournalEntry value:
- writer.Write((byte)6); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.Force); break;
- case YmirApplyTorqueJournalEntry value:
- writer.Write((byte)7); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); writer.Write(value.Command.Torque); break;
- case YmirStepSessionJournalEntry value:
- writer.Write((byte)8); WriteHeader(writer, value.Command.Header); writer.Write(value.Command.DeltaTime); WriteFields(writer, value.Command.Fields); writer.Write(value.Command.SubstepCount); break;
- default:
- throw new InvalidOperationException($"Unknown Ymir checkpoint journal entry '{entry?.GetType().FullName ?? ""}'.");
- }
- }
- }
-
- private static YmirSessionJournalEntry[] ReadJournal(BinaryReader reader)
- {
- var count = ReadCount(reader);
- var values = new YmirSessionJournalEntry[count];
- for (var index = 0; index < count; index++)
- {
- values[index] = reader.ReadByte() switch
- {
- 1 => new YmirSpawnBodyJournalEntry(new YmirSpawnBodyCommand(ReadHeader(reader), ReadBody(reader)!)),
- 2 => new YmirRemoveBodyJournalEntry(new YmirRemoveBodyCommand(ReadHeader(reader), ReadString(reader))),
- 3 => new YmirTeleportBodyJournalEntry(new YmirTeleportBodyCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader), ReadVec2(reader))),
- 4 => new YmirSetBodyVelocityJournalEntry(new YmirSetBodyVelocityCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader), reader.ReadSingle())),
- 5 => new YmirConfigureBodyJournalEntry(new YmirConfigureBodyCommand(ReadHeader(reader), ReadString(reader), reader.ReadSingle(), reader.ReadSingle(), reader.ReadBoolean(), reader.ReadSingle(), reader.ReadBoolean())),
- 6 => new YmirApplyForceJournalEntry(new YmirApplyForceCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader))),
- 7 => new YmirApplyTorqueJournalEntry(new YmirApplyTorqueCommand(ReadHeader(reader), ReadString(reader), reader.ReadSingle())),
- 8 => new YmirStepSessionJournalEntry(new YmirStepSessionCommand(ReadHeader(reader), reader.ReadSingle(), ReadFields(reader)!, reader.ReadInt32())),
- var kind => throw new InvalidDataException($"Unknown Ymir checkpoint journal kind {kind}.")
- };
- }
- return values;
- }
-
- private static void WriteWorld(BinaryWriter writer, YmirWorld world)
- {
- ArgumentNullException.ThrowIfNull(world);
- writer.Write(world.Time);
- WriteBodies(writer, world.Bodies);
- WriteFields(writer, world.Fields);
- }
-
- private static YmirWorld ReadWorld(BinaryReader reader)
- {
- var time = reader.ReadSingle();
- var bodies = ReadBodies(reader);
- var fields = ReadFields(reader) ?? throw new InvalidDataException("Ymir checkpoint world fields cannot be null.");
- return new YmirWorld(time, bodies, fields);
- }
-
- private static void WriteBodies(BinaryWriter writer, IReadOnlyList bodies)
- {
- WriteCount(writer, bodies?.Count ?? -1);
- foreach (var body in bodies!) WriteBody(writer, body);
- }
-
- private static PhysicsBody[] ReadBodies(BinaryReader reader)
- {
- var count = ReadCount(reader);
- var values = new PhysicsBody[count];
- for (var index = 0; index < count; index++)
- values[index] = ReadBody(reader) ?? throw new InvalidDataException("Ymir body list contains null.");
- return values;
- }
-
- private static void WriteBody(BinaryWriter writer, PhysicsBody? body)
- {
- writer.Write(body != null);
- if (body == null) return;
- WriteString(writer, body.Id);
- WriteVec2(writer, body.Position);
- WriteVec2(writer, body.Velocity);
- writer.Write(body.Radius);
- writer.Write(body.Mass);
- writer.Write(body.IsStatic);
- writer.Write(body.Restitution);
- writer.Write(body.Direction.HasValue);
- if (body.Direction is { } direction) WriteVec2(writer, direction);
- writer.Write(body.AngularVelocity);
- writer.Write(body.Torque);
- writer.Write(body.IsKinematic);
- writer.Write(body.IsBullet);
- writer.Write(body.ParticipatesInFields);
- writer.Write(body.CollisionCategoryBits);
- writer.Write(body.CollisionMaskBits);
- writer.Write(body.CollisionGroupIndex);
- }
-
- private static PhysicsBody? ReadBody(BinaryReader reader)
- {
- if (!reader.ReadBoolean()) return null;
- var id = ReadString(reader);
- var position = ReadVec2(reader);
- var velocity = ReadVec2(reader);
- var radius = reader.ReadSingle();
- var mass = reader.ReadSingle();
- var isStatic = reader.ReadBoolean();
- var restitution = reader.ReadSingle();
- var direction = reader.ReadBoolean() ? ReadVec2(reader) : (Vec2?)null;
- return new PhysicsBody(
- id, position, velocity, radius, mass, isStatic, restitution, direction,
- reader.ReadSingle(), reader.ReadSingle(), reader.ReadBoolean(), reader.ReadBoolean(),
- reader.ReadBoolean(), reader.ReadUInt64(), reader.ReadUInt64(), reader.ReadInt32());
- }
-
- private static void WriteFields(BinaryWriter writer, IReadOnlyList? fields)
- {
- writer.Write(fields != null);
- if (fields == null) return;
- WriteCount(writer, fields.Count);
- foreach (var field in fields)
- {
- writer.Write(field != null);
- if (field == null) continue;
- WriteString(writer, field.Id);
- WriteVec2(writer, field.Position);
- writer.Write(field.Strength);
- writer.Write(field.Radius);
- }
- }
-
- private static RadialField[]? ReadFields(BinaryReader reader)
- {
- if (!reader.ReadBoolean()) return null;
- var count = ReadCount(reader);
- var values = new RadialField[count];
- for (var index = 0; index < count; index++)
- {
- if (!reader.ReadBoolean())
- {
- values[index] = null!;
- continue;
- }
- values[index] = new RadialField(ReadString(reader), ReadVec2(reader), reader.ReadSingle(), reader.ReadSingle());
- }
- return values;
- }
-
- private static void WriteEpisodes(BinaryWriter writer, IReadOnlyList episodes)
- {
- WriteCount(writer, episodes?.Count ?? -1);
- foreach (var value in episodes!)
- {
- WriteString(writer, value.BodyA); writer.Write(value.BodyAGeneration);
- WriteString(writer, value.BodyB); writer.Write(value.BodyBGeneration);
- writer.Write(value.StartStepIndex); writer.Write(value.Ordinal);
- }
- }
-
- private static YmirContactEpisodeCheckpoint[] ReadEpisodes(BinaryReader reader)
- {
- var count = ReadCount(reader);
- var values = new YmirContactEpisodeCheckpoint[count];
- for (var index = 0; index < count; index++)
- values[index] = new YmirContactEpisodeCheckpoint(
- ReadString(reader), reader.ReadInt64(), ReadString(reader), reader.ReadInt64(),
- reader.ReadInt64(), reader.ReadInt64());
- return values;
- }
-
- private static void WriteHeader(BinaryWriter writer, YmirCommandHeader header)
- {
- WriteString(writer, header.CommandId);
- writer.Write(header.ExpectedRevision);
- }
-
- private static YmirCommandHeader ReadHeader(BinaryReader reader) => new(ReadString(reader), reader.ReadInt64());
-
- private static void WriteVec2(BinaryWriter writer, Vec2 value)
- {
- writer.Write(value.X);
- writer.Write(value.Y);
- }
-
- private static Vec2 ReadVec2(BinaryReader reader) => new(reader.ReadSingle(), reader.ReadSingle());
-
- private static void WriteString(BinaryWriter writer, string value)
- {
- if (value == null) throw new InvalidOperationException("Ymir checkpoint strings cannot be null.");
- var bytes = Encoding.UTF8.GetBytes(value);
- if (bytes.Length > MaximumStringBytes)
- throw new InvalidOperationException("Ymir checkpoint string exceeds the supported size.");
- writer.Write(bytes.Length);
- writer.Write(bytes);
- }
-
- private static string ReadString(BinaryReader reader)
- {
- var length = reader.ReadInt32();
- if (length < 0 || length > MaximumStringBytes)
- throw new InvalidDataException("Ymir checkpoint string length is invalid.");
- var bytes = reader.ReadBytes(length);
- if (bytes.Length != length)
- throw new EndOfStreamException();
- return Encoding.UTF8.GetString(bytes);
- }
-
- private static void WriteCount(BinaryWriter writer, int count)
- {
- if (count < 0 || count > MaximumCollectionCount)
- throw new InvalidOperationException("Ymir checkpoint collection count is invalid.");
- writer.Write(count);
- }
-
- private static int ReadCount(BinaryReader reader)
- {
- var count = reader.ReadInt32();
- return count is < 0 or > MaximumCollectionCount
- ? throw new InvalidDataException("Ymir checkpoint collection count is invalid.")
- : count;
- }
-}
diff --git a/src/Ymir.Core/YmirSimulator.cs b/src/Ymir.Core/YmirSimulator.cs
deleted file mode 100644
index d22c4de..0000000
--- a/src/Ymir.Core/YmirSimulator.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace Ymir.Core;
-
-///
-/// Compatibility façade for the snapshot-in/snapshot-out Ymir contract.
-/// Calls are isolated by design; retained world ownership is not inferred from snapshots.
-///
-public sealed class YmirSimulator
-{
- public SimulationStepResult Step(SimulationStepRequest request)
- {
- using var session = new YmirWorldSession();
- return session.Step(request);
- }
-
- public SoASimulationStepResult Step(SoASimulationStepRequest request)
- {
- using var session = new YmirWorldSession();
- return session.Step(request);
- }
-}
diff --git a/src/Ymir.Core/YmirSoAWorld.cs b/src/Ymir.Core/YmirSoAWorld.cs
deleted file mode 100644
index 3985ca1..0000000
--- a/src/Ymir.Core/YmirSoAWorld.cs
+++ /dev/null
@@ -1,293 +0,0 @@
-using CultMath;
-
-namespace Ymir.Core;
-
-public sealed class YmirSoAWorld
-{
- public float Time { get; set; }
- public string[] BodyIds { get; set; } = [];
- public float[] PositionX { get; set; } = [];
- 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; } = [];
- public float[] FieldStrength { get; set; } = [];
- public float[] FieldRadius { get; set; } = [];
-
- public int BodyCount => BodyIds.Length;
-
- public int FieldCount => FieldIds.Length;
-
- public static YmirSoAWorld FromWorld(YmirWorld world)
- {
- var bodies = world.Bodies.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray();
- var fields = world.Fields.OrderBy(field => field.Id, StringComparer.Ordinal).ToArray();
-
- return new YmirSoAWorld
- {
- Time = world.Time,
- BodyIds = bodies.Select(body => body.Id).ToArray(),
- PositionX = bodies.Select(body => body.Position.X).ToArray(),
- 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(),
- FieldStrength = fields.Select(field => field.Strength).ToArray(),
- FieldRadius = fields.Select(field => field.Radius).ToArray()
- };
- }
-
- public YmirWorld ToWorld() => new(
- Time,
- Enumerable.Range(0, BodyCount)
- .Select(i => new PhysicsBody(
- BodyIds[i],
- new Vec2(PositionX[i], PositionY[i]),
- new Vec2(VelocityX[i], VelocityY[i]),
- Radius[i],
- Mass[i],
- DynamicMask[i] <= 0.0f,
- 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(
- FieldIds[i],
- new Vec2(FieldPositionX[i], FieldPositionY[i]),
- FieldStrength[i],
- FieldRadius[i]))
- .ToArray());
-
- public YmirSoAWorld Clone() => new()
- {
- Time = Time,
- BodyIds = (string[])BodyIds.Clone(),
- PositionX = (float[])PositionX.Clone(),
- 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(),
- FieldStrength = (float[])FieldStrength.Clone(),
- FieldRadius = (float[])FieldRadius.Clone()
- };
-
- public void Validate()
- {
- ValidateBodyLengths();
- ValidateFieldLengths();
-
- for (var i = 0; i < BodyCount; i++)
- {
- if (string.IsNullOrWhiteSpace(BodyIds[i]))
- {
- throw new ArgumentException("Ymir bodies must have stable ids.");
- }
-
- if (Radius[i] <= 0.0f)
- {
- throw new ArgumentOutOfRangeException(nameof(Radius), "Body radius must be positive.");
- }
-
- if (DynamicMask[i] > 0.0f && Mass[i] <= 0.0f)
- {
- 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.");
- }
- }
- }
-
- public float2 PositionAt(int index) => new(PositionX[index], PositionY[index]);
-
- public float2 VelocityAt(int index) => new(VelocityX[index], VelocityY[index]);
-
- public void SetPosition(int index, float2 value)
- {
- PositionX[index] = value.x;
- PositionY[index] = value.y;
- }
-
- public void SetVelocity(int index, float2 value)
- {
- VelocityX[index] = value.x;
- VelocityY[index] = value.y;
- }
-
- 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,
- KinematicMask.Length,
- BulletMask.Length,
- FieldParticipationMask.Length,
- CollisionCategoryBits.Length,
- CollisionMaskBits.Length,
- CollisionGroupIndex.Length
- })
- {
- if (length != expected)
- {
- throw new ArgumentException("Ymir body SoA arrays must have equal length.");
- }
- }
- }
-
- 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;
- foreach (var length in new[]
- {
- FieldPositionX.Length,
- FieldPositionY.Length,
- FieldStrength.Length,
- FieldRadius.Length
- })
- {
- if (length != expected)
- {
- throw new ArgumentException("Ymir field SoA arrays must have equal length.");
- }
- }
- }
-}
-
-public sealed record SoASimulationStepRequest(float DeltaTime, YmirSoAWorld World);
-
-public sealed record SoASimulationStepResult(YmirSoAWorld World, IReadOnlyList Contacts);
diff --git a/src/Ymir.Core/YmirWorldSession.cs b/src/Ymir.Core/YmirWorldSession.cs
deleted file mode 100644
index ad8f01f..0000000
--- a/src/Ymir.Core/YmirWorldSession.cs
+++ /dev/null
@@ -1,206 +0,0 @@
-using Ymir.Box3D;
-
-namespace Ymir.Core;
-
-///
-/// Owns one retained Box3D world and its stable GameCult identity projection.
-/// Callers own the session lifetime; body snapshots do not imply session identity.
-///
-internal sealed class YmirWorldSession : IDisposable
-{
- private readonly object _gate = new();
- private readonly Box3DSession _session = new();
- private readonly Dictionary _keysById = new(StringComparer.Ordinal);
- private readonly Dictionary _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(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 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 bodyIds)
- {
- var unique = new HashSet(StringComparer.Ordinal);
- foreach (var id in bodyIds)
- {
- if (!unique.Add(id))
- {
- throw new ArgumentException($"Ymir body id '{id}' occurs more than once.", nameof(bodyIds));
- }
- }
- }
-}
diff --git a/src/Ymir.Core/YmirWorldStateDocument.cs b/src/Ymir.Core/YmirWorldStateDocument.cs
deleted file mode 100644
index 8878029..0000000
--- a/src/Ymir.Core/YmirWorldStateDocument.cs
+++ /dev/null
@@ -1,273 +0,0 @@
-using GameCult.Caching;
-using GameCult.Caching.MessagePack;
-using MessagePack;
-
-namespace Ymir.Core;
-
-[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v0")]
-[MessagePackObject]
-public sealed class YmirWorldStateDocumentV0
-{
- [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; } = [];
-
- public static YmirWorldStateDocumentV0 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()
- };
-
- 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()
- };
-}
-
-[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)
- {
- var cache = await CultCacheMessagePack.OpenAsync(
- path,
- new CultCacheOpenOptions
- {
- UseDirectoryStore = true,
- FlushOnDispose = true,
- StoreFlushOnDispose = true
- }).ConfigureAwait(false);
-
- using (cache)
- {
- await cache.UpsertAsync(
- YmirWorldStateDocumentV2.FromSoA(worldId, world),
- new CultRecordHandle(new CultRecordKey($"ymir:world:{worldId}")))
- .ConfigureAwait(false);
- await cache.FlushAsync().ConfigureAwait(false);
- }
- }
-
- public static async Task LoadWorldAsync(string path, string worldId)
- {
- using var cache = await CultCacheMessagePack.OpenAsync(
- path,
- new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false);
- var key = new CultRecordKey($"ymir:world:{worldId}");
- return cache.Get(key)?.ToSoA()
- ?? cache.Get(key)?.ToSoA()
- ?? cache.Get(key)?.ToSoA();
- }
-}
diff --git a/src/ymir-daemon/Program.cs b/src/ymir-daemon/Program.cs
deleted file mode 100644
index 2d1f6ff..0000000
--- a/src/ymir-daemon/Program.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using System.Text.Json;
-using CultMath;
-using Ymir.Core;
-
-namespace Ymir.Daemon;
-
-internal static class Program
-{
- private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
- {
- WriteIndented = true
- };
-
- public static async Task Main(string[] args)
- {
- var command = args.FirstOrDefault() ?? "help";
-
- switch (command)
- {
- case "publish-service":
- await PublishServiceAsync(ValueAfter(args, "--path") ?? ".ymir/service.cc");
- return 0;
- case "step-sample":
- WriteJson(new YmirSimulator().Step(SampleRequest()));
- return 0;
- case "save-sample":
- await SaveSampleAsync(ValueAfter(args, "--path") ?? ".ymir/worlds.cc");
- return 0;
- case "step":
- return RunStep(args);
- default:
- PrintHelp();
- return command is "help" or "-h" or "--help" ? 0 : 1;
- }
- }
-
- private static int RunStep(string[] args)
- {
- var requestPath = ValueAfter(args, "--request");
- if (string.IsNullOrWhiteSpace(requestPath))
- {
- Console.Error.WriteLine("step requires --request .");
- return 1;
- }
-
- var request = JsonSerializer.Deserialize(
- File.ReadAllText(requestPath),
- JsonOptions);
-
- if (request is null)
- {
- Console.Error.WriteLine("Could not deserialize simulation step request.");
- return 1;
- }
-
- WriteJson(new YmirSimulator().Step(request));
- return 0;
- }
-
- private static SimulationStepRequest SampleRequest() => new(
- 0.1f,
- new YmirWorld(
- 0.0f,
- new[]
- {
- new PhysicsBody("projectile", new Vec2(-2.0f, 0.0f), new Vec2(4.0f, 0.0f), 0.1f, 1.0f, Restitution: 0.0f),
- new PhysicsBody("target", new Vec2(0.5f, 0.0f), Vec2.Zero, 0.5f, 1.0f, IsStatic: true)
- },
- new[]
- {
- new RadialField("gravity-well", new Vec2(0.0f, 1.0f), 2.0f, 8.0f)
- }));
-
- private static async Task SaveSampleAsync(string path)
- {
- var result = new YmirSimulator().Step(new SoASimulationStepRequest(
- SampleRequest().DeltaTime,
- YmirSoAWorld.FromWorld(SampleRequest().World)));
- await YmirCultCacheStore.SaveWorldAsync(path, "sample", result.World);
- WriteJson(new
- {
- ok = true,
- path,
- record = "ymir:world:sample",
- schema = "gamecult.ymir.world_state.v2",
- bodyCount = result.World.BodyCount,
- fieldCount = result.World.FieldCount
- });
- }
-
- private static async Task PublishServiceAsync(string path)
- {
- await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
- WriteJson(new
- {
- ok = true,
- path,
- records = new[]
- {
- "ymir:provider:ymir.physics",
- "ymir:operator:ymir.physics",
- "surface:ymir.physics.operator"
- }
- });
- }
-
- private static void WriteJson(object value) => Console.WriteLine(JsonSerializer.Serialize(value, JsonOptions));
-
- private static string? ValueAfter(string[] args, string key)
- {
- var index = Array.IndexOf(args, key);
- return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
- }
-
- private static void PrintHelp()
- {
- Console.WriteLine("""
- Ymir physics cutover CLI
-
- Commands:
- publish-service [--path .ymir/service.cc] Regenerate the derived service publication.
- step-sample
- save-sample [--path .ymir/worlds.cc]
- step --request
- """);
- }
-}
diff --git a/src/ymir-daemon/ymir-daemon.csproj b/src/ymir-daemon/ymir-daemon.csproj
deleted file mode 100644
index 9a233ea..0000000
--- a/src/ymir-daemon/ymir-daemon.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
- Exe
- net10.0
- Ymir.Daemon
- enable
- enable
- ymir-daemon
- Ymir cutover CLI; the retained Box3D daemon session is not active yet.
-
-
-
diff --git a/tests/Ymir.Box3D.Parity/Box3DOracle.cs b/tests/Ymir.Box3D.Parity/Box3DOracle.cs
deleted file mode 100644
index 4d42ca9..0000000
--- a/tests/Ymir.Box3D.Parity/Box3DOracle.cs
+++ /dev/null
@@ -1,213 +0,0 @@
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-
-namespace Ymir.Box3D.Parity;
-
-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,
- float queryRadius,
- float bodyX,
- float bodyY,
- float bodyRadius);
-
- [LibraryImport(LibraryName)]
- [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
- internal static partial Box3DOverlapResult ymir_box3d_overlap_capsule_sphere(
- float startX,
- float startY,
- float endX,
- float endY,
- float capsuleRadius,
- float bodyX,
- float bodyY,
- float bodyRadius);
-
- [LibraryImport(LibraryName)]
- [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
- internal static partial Box3DCastResult ymir_box3d_cast_sphere(
- float originX,
- float originY,
- float translationX,
- float translationY,
- float queryRadius,
- float bodyX,
- float bodyY,
- float bodyRadius,
- int canEncroach);
-
- [LibraryImport(LibraryName)]
- [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
- internal static partial void ymir_box3d_step_pair(
- in Box3DBodyInput bodyA,
- in Box3DBodyInput bodyB,
- float timeStep,
- int subStepCount,
- float restitutionThreshold,
- 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)]
-internal readonly record struct Box3DOverlapResult(int Hit, float Distance, float NormalX, float NormalY)
-{
- public bool IsHit => Hit != 0;
-}
-[StructLayout(LayoutKind.Sequential)]
-internal readonly record struct Box3DCastResult(
- int Hit,
- float Fraction,
- float PointX,
- float PointY,
- float NormalX,
- float NormalY)
-{
- public bool IsHit => Hit != 0;
-}
-
-[StructLayout(LayoutKind.Sequential)]
-internal readonly record struct Box3DBodyInput(
- float PositionX,
- float PositionY,
- float VelocityX,
- float VelocityY,
- float Radius,
- float Mass,
- float Restitution,
- int IsStatic);
-
-[StructLayout(LayoutKind.Sequential)]
-internal readonly record struct Box3DBodyOutput(
- float PositionX,
- float PositionY,
- float VelocityX,
- float VelocityY,
- float AngularVelocity);
-
-[StructLayout(LayoutKind.Sequential)]
-internal readonly record struct Box3DPairStepResult(
- Box3DBodyOutput BodyA,
- Box3DBodyOutput BodyB,
- int BeginContactCount,
- int EndContactCount,
- int HitContactCount);
-
-[StructLayout(LayoutKind.Sequential)]
-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);
diff --git a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs
deleted file mode 100644
index 93c0fa2..0000000
--- a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs
+++ /dev/null
@@ -1,249 +0,0 @@
-namespace Ymir.Box3D.Parity;
-
-public sealed class Box3DParityTests
-{
- [Fact]
- public void OracleIsPinnedBox3DRelease()
- {
- var doublePrecision = Box3DOracle.ymir_box3d_get_version(out var major, out var minor, out var revision);
-
- Assert.Equal((0, 1, 0), (major, minor, revision));
- Assert.Equal(0, doublePrecision);
- }
-
- [Theory]
- [InlineData(1.9f, true)]
- [InlineData(2.0f, true)]
- [InlineData(2.00049f, true)]
- [InlineData(2.00051f, false)]
- public void SphereOverlapClassificationMatchesBox3DSlop(float centerDistance, bool expected)
- {
- var result = Box3DOracle.ymir_box3d_overlap_spheres(0.0f, 0.0f, 1.0f, centerDistance, 0.0f, 1.0f);
-
- Assert.Equal(expected, result.IsHit);
- }
-
- [Theory]
- [InlineData(-1.00049f, true)]
- [InlineData(-1.00051f, false)]
- [InlineData(5.0f, true)]
- [InlineData(11.00049f, true)]
- [InlineData(11.00051f, false)]
- public void TractorCapsuleMembershipUsesBox3DRoundedCapsAndSlop(float pickupX, bool expected)
- {
- var result = Box3DOracle.ymir_box3d_overlap_capsule_sphere(
- 0.0f,
- 0.0f,
- 10.0f,
- 0.0f,
- 0.5f,
- pickupX,
- 0.0f,
- 0.5f);
-
- Assert.Equal(expected, result.IsHit);
- }
-
- [Fact]
- public void SphereCastReturnsBox3DFractionAndNormal()
- {
- var result = Box3DOracle.ymir_box3d_cast_sphere(
- -5.0f,
- 0.0f,
- 10.0f,
- 0.0f,
- 0.5f,
- 0.0f,
- 0.0f,
- 1.0f,
- 0);
-
- Assert.True(result.IsHit);
- Assert.Equal(0.3505f, result.Fraction, precision: 4);
- Assert.Equal(-1.0f, result.NormalX, precision: 4);
- Assert.Equal(0.0f, result.NormalY, precision: 4);
- }
-
- [Theory]
- [InlineData(-1.5f)]
- [InlineData(-1.4f)]
- [InlineData(0.0f)]
- public void SphereCastInitiallyTouchingOrOverlappingIsAHit(float originX)
- {
- var result = Box3DOracle.ymir_box3d_cast_sphere(
- originX,
- 0.0f,
- 5.0f,
- 0.0f,
- 0.5f,
- 0.0f,
- 0.0f,
- 1.0f,
- 0);
-
- Assert.True(result.IsHit);
- }
-
- [Fact]
- public void PairStepEmitsBeginContactAndSeparatesOverlappingSpheres()
- {
- var bodyA = new Box3DBodyInput(-0.9f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0);
- var bodyB = new Box3DBodyInput(0.9f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0);
-
- Box3DOracle.ymir_box3d_step_pair(in bodyA, in bodyB, 1.0f / 60.0f, 4, 0.0f, out var result);
-
- Assert.Equal(1, result.BeginContactCount);
- Assert.True(result.BodyA.PositionX < -0.9f);
- Assert.True(result.BodyB.PositionX > 0.9f);
- }
-
- [Fact]
- public void PairStepUsesMaximumRestitution()
- {
- var bodyA = new Box3DBodyInput(-1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.1f, 0);
- var bodyB = new Box3DBodyInput(1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.8f, 0);
-
- Box3DOracle.ymir_box3d_step_pair(in bodyA, in bodyB, 1.0f / 60.0f, 4, 0.0f, out var result);
-
- Assert.True(result.BodyA.VelocityX < -0.7f);
- Assert.True(result.BodyB.VelocityX > 0.7f);
- }
-
- [Fact]
- public void TorqueIsClearedAfterEachWorldStep()
- {
- var result = Box3DOracle.ymir_box3d_torque_lifetime(0.4f, 0.1f, 4);
-
- Assert.True(result.AngularVelocityAfterAppliedStep > 0.0f);
- Assert.Equal(
- result.AngularVelocityAfterAppliedStep,
- result.AngularVelocityAfterUnforcedStep,
- precision: 5);
- }
-
- [Fact]
- public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle()
- {
- Assert.Equal(5u, 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 { 1, 2 }, new HashSet { begin.StableIdA, begin.StableIdB });
- Assert.Equal(1u, begin.HasDetails);
-
- Assert.Equal(0, Box3DOracle.ymir_box3d_session_remove(session, 2));
- Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
- var end = Assert.Single(CopyEvents(session), value => value.Kind == 3);
- Assert.Equal(new HashSet { 1, 2 }, new HashSet { end.StableIdA, end.StableIdB });
- Assert.Equal(0u, end.HasDetails);
- }
- finally
- {
- Box3DOracle.ymir_box3d_session_destroy(session);
- }
- }
-
- [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 { value.StableIdA, value.StableIdB })
- .ToArray();
-
- Assert.Single(pairs);
- Assert.Equal(new HashSet { 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 { 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;
- }
-}
diff --git a/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj b/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj
deleted file mode 100644
index bd866bd..0000000
--- a/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- net10.0
- enable
- enable
- true
- false
- $(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D
- $(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\parity\$(Configuration)
- C:\Program Files\CMake\bin\cmake.exe
- cmake
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/Ymir.Tests/Ymir.Tests.csproj b/tests/Ymir.Tests/Ymir.Tests.csproj
deleted file mode 100644
index 1c5b2f7..0000000
--- a/tests/Ymir.Tests/Ymir.Tests.csproj
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
- net10.0
- enable
- enable
- false
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/Ymir.Tests/YmirServicePublicationTests.cs b/tests/Ymir.Tests/YmirServicePublicationTests.cs
deleted file mode 100644
index cef0f9a..0000000
--- a/tests/Ymir.Tests/YmirServicePublicationTests.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using GameCult.Caching;
-using GameCult.Caching.MessagePack;
-using Ymir.Core;
-
-namespace Ymir.Tests;
-
-public sealed class YmirServicePublicationTests
-{
- [Fact]
- public void PublicationAdvertisesBox3DOwnershipBoundary()
- {
- var now = DateTimeOffset.Parse("2026-07-14T12:00:00Z");
-
- var advertisement = YmirServicePublication.ProviderAdvertisement(now);
- var diagnostics = YmirServicePublication.OperatorState(now);
-
- Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal);
- 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.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("replay checkpoint v1", diagnostics.Persistence, StringComparison.Ordinal);
- Assert.Contains("host-owned private journal persistence", diagnostics.Persistence, StringComparison.Ordinal);
- Assert.Equal("box3d-retained-session", diagnostics.Status);
- }
-
- [Fact]
- public async Task PublicationPersistsAndReopensWithCombinedRegistry()
- {
- var path = TemporaryStorePath();
- try
- {
- await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
-
- using var cache = await CultCacheMessagePack.OpenAsync(path, new CultCacheOpenOptions
- {
- Registry = new CultDocumentRegistry(),
- UseDirectoryStore = true
- });
-
- Assert.NotNull(cache.Get(new CultRecordKey("ymir:operator:ymir.physics")));
- Assert.Single(cache.GetAll());
- }
- finally
- {
- DeleteStore(path);
- }
- }
-
- [Fact]
- public async Task RegenerationReplacesUnreadableLegacyDerivedStoreBeforeOpen()
- {
- var path = TemporaryStorePath();
- var recordsPath = DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(path);
- try
- {
- Directory.CreateDirectory(Path.GetDirectoryName(path)!);
- Directory.CreateDirectory(recordsPath);
- await File.WriteAllBytesAsync(path, [0xc1]);
- await File.WriteAllBytesAsync(Path.Combine(recordsPath, "legacy.msgpack"), [0xc1]);
-
- await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
-
- using var cache = await CultCacheMessagePack.OpenAsync(path, new CultCacheOpenOptions
- {
- Registry = new CultDocumentRegistry(),
- UseDirectoryStore = true
- });
- Assert.NotNull(cache.Get(new CultRecordKey("ymir:operator:ymir.physics")));
- Assert.False(File.Exists(Path.Combine(recordsPath, "legacy.msgpack")));
- }
- finally
- {
- DeleteStore(path);
- }
- }
-
- private static string TemporaryStorePath() =>
- Path.Combine(Path.GetTempPath(), "ymir-tests", Guid.NewGuid().ToString("N"), "service.cc");
-
- private static void DeleteStore(string path)
- {
- var directory = Path.GetDirectoryName(path);
- if (directory is not null && Directory.Exists(directory))
- Directory.Delete(directory, recursive: true);
- }
-}
diff --git a/tests/Ymir.Tests/YmirSessionTests.cs b/tests/Ymir.Tests/YmirSessionTests.cs
deleted file mode 100644
index ee19347..0000000
--- a/tests/Ymir.Tests/YmirSessionTests.cs
+++ /dev/null
@@ -1,485 +0,0 @@
-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 ReplayCheckpointPreservesContactLineageAndCommandLedger()
- {
- using var original = YmirSession.Create(new YmirSessionCreateRequest(
- "checkpoint-contact",
- [
- Body("ship", positionX: 0.0f, isStatic: true),
- Body("pickup", positionX: 1.5f)
- ]));
- var began = original.Step(Step("begin", 0, 0.01f));
- var firstBegin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
- var checkpoint = original.Checkpoint();
- var payload = YmirSessionCheckpointCodec.Encode(checkpoint);
- checkpoint = YmirSessionCheckpointCodec.Decode(payload);
-
- using var restored = YmirSession.Restore(checkpoint);
- var duplicate = restored.Step(Step("begin", 0, 0.01f));
- Assert.Equal(began.Receipt.ReceiptId, duplicate.Receipt.ReceiptId);
- Assert.Equal(began.Receipt.Outcome, duplicate.Receipt.Outcome);
- Assert.Equal(began.Receipt.BeforeRevision, duplicate.Receipt.BeforeRevision);
- Assert.Equal(began.Receipt.AfterRevision, duplicate.Receipt.AfterRevision);
- Assert.Equal(began.Receipt.ProducedFactIds, duplicate.Receipt.ProducedFactIds);
- Assert.Equal(began.ContactFacts.Select(value => value.FactId), duplicate.ContactFacts.Select(value => value.FactId));
- Assert.Equal(checkpoint.SessionGeneration, restored.Info.SessionGeneration);
-
- var conflict = restored.Step(Step("begin", 0, 0.02f));
- Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Receipt.Error);
- var persistent = restored.Step(Step("persistent", 1, 0.01f));
- Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
- restored.Teleport(new YmirTeleportBodyCommand(
- Header("separate", 2), "pickup", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f)));
- var ended = restored.Step(Step("end", 3, 0.01f));
- var end = Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End);
- Assert.Equal(firstBegin.ContactId, end.ContactId);
- restored.Teleport(new YmirTeleportBodyCommand(
- Header("return", 4), "pickup", new Vec2(1.5f, 0.0f), new Vec2(0.0f, 1.0f)));
- var beganAgain = restored.Step(Step("begin-again", 5, 0.01f));
- var secondBegin = Assert.Single(beganAgain.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
- Assert.NotEqual(firstBegin.ContactId, secondBegin.ContactId);
- }
-
- [Fact]
- public void ReplayCheckpointRestoresPendingForceAndRejectsCorruptJournal()
- {
- using var original = YmirSession.Create(new YmirSessionCreateRequest(
- "checkpoint-force", [Body("ship")]));
- original.ApplyForce(new YmirApplyForceCommand(Header("force", 0), "ship", new Vec2(10.0f, 0.0f)));
- var checkpoint = original.Checkpoint();
-
- using var restored = YmirSession.Restore(checkpoint);
- var stepped = restored.Step(Step("step", 1, 0.1f));
- Assert.True(stepped.World.Bodies.Single().Velocity.X > 0.0f);
-
- var corrupt = checkpoint with { Journal = [] };
- Assert.Throws(() => YmirSession.Restore(corrupt));
- var wrongRuntime = checkpoint with { RuntimeFingerprint = "some-other-solver" };
- Assert.Throws(() => YmirSession.Restore(wrongRuntime));
- var corruptIdentity = YmirSessionCheckpointCodec.Encode(checkpoint);
- corruptIdentity[32] ^= 0xff;
- Assert.Throws(() => YmirSessionCheckpointCodec.Decode(corruptIdentity));
- Assert.Throws(() =>
- YmirSessionCheckpointCodec.Decode(YmirSessionCheckpointCodec.Encode(checkpoint).Concat(new byte[] { 1 }).ToArray()));
- }
-
- [Fact]
- public void IncrementalPersistenceWritesOnlyNewJournalEntriesAndRestoresBoundary()
- {
- using var original = YmirSession.Create(new YmirSessionCreateRequest(
- "incremental-contact",
- [Body("ship", positionX: 0.0f, isStatic: true), Body("pickup", positionX: 1.5f)]));
- var began = original.Step(Step("begin", 0, 0.01f));
- var begin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
-
- var first = original.CapturePersistence(0);
- var firstChunk = Assert.IsType(first.JournalChunk);
- Assert.Equal(0, firstChunk.FirstEntryIndex);
- Assert.Single(firstChunk.Entries);
- var firstChunkBytes = YmirSessionCheckpointCodec.Encode(firstChunk);
- var firstDescriptorBytes = YmirSessionCheckpointCodec.Encode(first.ResumeDescriptor);
-
- var persistent = original.Step(Step("persistent", 1, 0.01f));
- Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
- var second = original.CapturePersistence(first.ResumeDescriptor.JournalEntryCount);
- var secondChunk = Assert.IsType(second.JournalChunk);
- Assert.Equal(1, secondChunk.FirstEntryIndex);
- Assert.Single(secondChunk.Entries);
-
- var chunks = new[]
- {
- YmirSessionCheckpointCodec.DecodeJournalChunk(firstChunkBytes),
- YmirSessionCheckpointCodec.DecodeJournalChunk(YmirSessionCheckpointCodec.Encode(secondChunk))
- };
- var descriptor = YmirSessionCheckpointCodec.DecodeResumeDescriptor(
- YmirSessionCheckpointCodec.Encode(second.ResumeDescriptor));
- using var restored = YmirSession.Restore(descriptor, chunks);
- restored.Teleport(new YmirTeleportBodyCommand(
- Header("separate", 2), "pickup", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f)));
- var ended = restored.Step(Step("end", 3, 0.01f));
- Assert.Equal(begin.ContactId, Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End).ContactId);
-
- Assert.Throws(() => YmirSession.Restore(descriptor, [chunks[1]]));
- var corruptDescriptor = firstDescriptorBytes.ToArray();
- corruptDescriptor[24] ^= 0xff;
- Assert.Throws(() => YmirSessionCheckpointCodec.DecodeResumeDescriptor(corruptDescriptor));
- }
-
- [Fact]
- public void QuiescentSessionCanRollToAnEmptyPersistenceGeneration()
- {
- using var original = YmirSession.Create(new YmirSessionCreateRequest(
- "compact-quiescent", [Body("ship", velocityX: 2.0f)]));
- original.Step(Step("step-1", 0, 0.1f));
- original.Step(Step("step-2", 1, 0.1f));
- var expectedWorld = original.Snapshot();
-
- Assert.True(original.TryReplaceWithCompactedPersistenceBaseline(out var compacted));
- using (compacted!)
- {
- var baseline = compacted!;
- Assert.NotEqual(original.Info.SessionGeneration, baseline.Info.SessionGeneration);
- Assert.True(original.Info.IsDisposed);
- Assert.Equal(0, baseline.Info.Revision);
- Assert.Equal(0, baseline.PersistenceJournalEntryCount);
- AssertWorldEqual(expectedWorld, baseline.Snapshot());
-
- var capture = baseline.CapturePersistence(0);
- Assert.Null(capture.JournalChunk);
- Assert.Equal(0, capture.ResumeDescriptor.JournalEntryCount);
- using var restored = YmirSession.Restore(capture.ResumeDescriptor, []);
- AssertWorldEqual(baseline.Snapshot(), restored.Snapshot());
- }
- }
-
- [Fact]
- public void PersistenceRolloverRefusesActiveContactsAndUnsteppedMutations()
- {
- using var touching = YmirSession.Create(new YmirSessionCreateRequest(
- "compact-contact",
- [Body("ship", positionX: 0.0f, isStatic: true), Body("pickup", positionX: 1.5f)]));
- touching.Step(Step("begin", 0, 0.01f));
- Assert.False(touching.TryReplaceWithCompactedPersistenceBaseline(out var contactBaseline));
- Assert.Null(contactBaseline);
-
- using var pendingForce = YmirSession.Create(new YmirSessionCreateRequest(
- "compact-force", [Body("ship")]));
- pendingForce.ApplyForce(new YmirApplyForceCommand(
- Header("force", 0), "ship", new Vec2(10.0f, 0.0f)));
- Assert.False(pendingForce.TryReplaceWithCompactedPersistenceBaseline(out var forceBaseline));
- Assert.Null(forceBaseline);
- }
-
- [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 { "source", "other-payload" }, new HashSet { 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));
-
- private static void AssertWorldEqual(YmirWorld expected, YmirWorld actual)
- {
- Assert.Equal(expected.Time, actual.Time);
- Assert.Equal(expected.Bodies, actual.Bodies);
- Assert.Equal(expected.Fields, actual.Fields);
- }
-}
diff --git a/tests/Ymir.Tests/YmirSimulatorTests.cs b/tests/Ymir.Tests/YmirSimulatorTests.cs
deleted file mode 100644
index 19e2f1a..0000000
--- a/tests/Ymir.Tests/YmirSimulatorTests.cs
+++ /dev/null
@@ -1,300 +0,0 @@
-using Ymir.Core;
-using GameCult.Caching;
-using GameCult.Caching.MessagePack;
-
-namespace Ymir.Tests;
-
-public sealed class YmirSimulatorTests
-{
- [Fact]
- public void StepIntegratesDynamicBodies()
- {
- var result = Step(new PhysicsBody("projectile", Vec2.Zero, new Vec2(10.0f, 0.0f), 0.1f, 1.0f));
-
- Assert.Equal(1.0f, result.World.Bodies[0].Position.X, precision: 5);
- Assert.Equal(0.0f, result.World.Bodies[0].Position.Y, precision: 5);
- }
-
- [Fact]
- public void RadialFieldAcceleratesBodyTowardWell()
- {
- var simulator = new YmirSimulator();
- var request = new SimulationStepRequest(
- 1.0f,
- new YmirWorld(
- 0.0f,
- new[] { new PhysicsBody("ship", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f) },
- new[] { new RadialField("well", new Vec2(10.0f, 0.0f), 10.0f, 20.0f) }));
-
- var result = simulator.Step(request);
-
- Assert.True(result.World.Bodies[0].Velocity.X > 0.0f);
- }
-
- [Fact]
- public void OverlappingCirclesEmitContactAndSeparate()
- {
- var simulator = new YmirSimulator();
- var request = new SimulationStepRequest(
- 0.1f,
- new YmirWorld(
- 0.0f,
- new[]
- {
- new PhysicsBody("a", new Vec2(0.0f, 0.0f), new Vec2(1.0f, 0.0f), 1.0f, 1.0f),
- new PhysicsBody("b", new Vec2(1.5f, 0.0f), new Vec2(-1.0f, 0.0f), 1.0f, 1.0f)
- },
- Array.Empty()));
-
- var result = simulator.Step(request);
-
- var contact = Assert.Single(result.Contacts);
- Assert.Equal("a", contact.BodyA);
- Assert.Equal("b", contact.BodyB);
- Assert.True(contact.Penetration > 0.0f);
- Assert.True(result.World.Bodies[0].Position.X < 0.1f);
- Assert.True(result.World.Bodies[1].Position.X > 1.4f);
- }
-
- [Fact]
- public void ContactOrderingIsStableByBodyId()
- {
- var simulator = new YmirSimulator();
- var request = new SimulationStepRequest(
- 0.1f,
- new YmirWorld(
- 0.0f,
- new[]
- {
- new PhysicsBody("zeta", new Vec2(0.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f),
- new PhysicsBody("alpha", new Vec2(1.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f)
- },
- Array.Empty()));
-
- var contact = Assert.Single(simulator.Step(request).Contacts);
-
- Assert.Equal("alpha", contact.BodyA);
- Assert.Equal("zeta", contact.BodyB);
- }
-
- [Fact]
- 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
- {
- BodyIds = ["ship", "anchor"],
- PositionX = [0.0f, 10.0f],
- PositionY = [0.0f, 0.0f],
- VelocityX = [1.0f, 0.0f],
- VelocityY = [0.0f, 0.0f],
- Radius = [0.5f, 0.5f],
- Mass = [1.0f, 1.0f],
- DynamicMask = [1.0f, 0.0f],
- Restitution = [0.2f, 0.2f],
- FieldIds = ["well"],
- FieldPositionX = [10.0f],
- FieldPositionY = [0.0f],
- FieldStrength = [10.0f],
- FieldRadius = [20.0f]
- };
-
- var result = simulator.Step(new SoASimulationStepRequest(1.0f, world));
-
- Assert.True(result.World.PositionX[0] > 1.0f);
- Assert.Equal(10.0f, result.World.PositionX[1], precision: 5);
- Assert.Equal(1.0f, result.World.Time, precision: 5);
- }
-
- [Fact]
- public async Task CultCacheStoreRoundTripsSoAWorldState()
- {
- var path = Path.Combine(Path.GetTempPath(), $"ymir-tests-{Guid.NewGuid():N}.cc");
- var recordsPath = $"{path}.records";
-
- try
- {
- 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, 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);
- var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
-
- Assert.NotNull(loaded);
- 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
- {
- if (File.Exists(path))
- {
- File.Delete(path);
- }
-
- if (Directory.Exists(recordsPath))
- {
- Directory.Delete(recordsPath, recursive: true);
- }
- }
- }
-
- [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(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();
- return simulator.Step(new SimulationStepRequest(
- 0.1f,
- new YmirWorld(0.0f, bodies, Array.Empty())));
- }
-}