Replace managed physics with Box3D runtime boundary
This commit is contained in:
parent
658db6c986
commit
721eee0656
26 changed files with 2167 additions and 200 deletions
183
src/Ymir.Box3D/Box3DNative.cs
Normal file
183
src/Ymir.Box3D/Box3DNative.cs
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal enum Box3DStatus
|
||||
{
|
||||
Ok = 0,
|
||||
InvalidArgument = 1,
|
||||
DuplicateId = 2,
|
||||
BufferTooSmall = 3,
|
||||
OutOfMemory = 4,
|
||||
InternalError = 5
|
||||
}
|
||||
|
||||
internal static partial class Box3DNative
|
||||
{
|
||||
internal const string LibraryName = "ymir_box3d";
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial uint ymir_box3d_get_abi_version();
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_get_abi_layout(
|
||||
out uint bodyInputSize,
|
||||
out uint fieldInputSize,
|
||||
out uint bodyOutputSize,
|
||||
out uint contactOutputSize);
|
||||
|
||||
[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_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);
|
||||
}
|
||||
|
||||
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,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
uint IsStatic);
|
||||
|
||||
[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 Box3DCastOutput(
|
||||
int Hit,
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DOverlapOutput(
|
||||
int Hit,
|
||||
float Distance,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
65
src/Ymir.Box3D/Box3DQueries.cs
Normal file
65
src/Ymir.Box3D/Box3DQueries.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DSphereCastHit(
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
internal readonly record struct Box3DSphereOverlapHit(float Distance, float NormalX, float NormalZ);
|
||||
|
||||
internal static class Box3DQueries
|
||||
{
|
||||
internal static Box3DSphereOverlapHit? OverlapSpheres(
|
||||
float queryX,
|
||||
float queryZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_overlap_spheres(
|
||||
queryX,
|
||||
queryZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereOverlapHit(output.Distance, output.NormalX, output.NormalZ);
|
||||
}
|
||||
|
||||
internal static Box3DSphereCastHit? CastSphere(
|
||||
float originX,
|
||||
float originZ,
|
||||
float translationX,
|
||||
float translationZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_cast_sphere(
|
||||
originX,
|
||||
originZ,
|
||||
translationX,
|
||||
translationZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius,
|
||||
canEncroach: 0);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereCastHit(
|
||||
output.Fraction,
|
||||
output.PointX,
|
||||
output.PointZ,
|
||||
output.NormalX,
|
||||
output.NormalZ);
|
||||
}
|
||||
}
|
||||
240
src/Ymir.Box3D/Box3DSession.cs
Normal file
240
src/Ymir.Box3D/Box3DSession.cs
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DBody(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
bool IsStatic);
|
||||
|
||||
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 sealed class Box3DSession : IDisposable
|
||||
{
|
||||
internal const uint AbiVersion = 2;
|
||||
internal const int DefaultSubstepCount = 4;
|
||||
|
||||
private readonly Box3DSessionHandle _handle;
|
||||
private bool _disposed;
|
||||
|
||||
internal Box3DSession()
|
||||
{
|
||||
EnsureCompatibleNativeLibrary();
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_create(out var value), "create session");
|
||||
if (value == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned a null Ymir session.");
|
||||
}
|
||||
|
||||
_handle = new Box3DSessionHandle(value);
|
||||
}
|
||||
|
||||
internal unsafe void SyncBodies(ReadOnlySpan<Box3DBody> bodies)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var native = new Box3DBodyInput[bodies.Length];
|
||||
for (var i = 0; i < bodies.Length; i++)
|
||||
{
|
||||
var body = bodies[i];
|
||||
native[i] = new Box3DBodyInput(
|
||||
body.StableId,
|
||||
body.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);
|
||||
}
|
||||
|
||||
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 Step(float deltaTime, ReadOnlySpan<Box3DField> fields, int substepCount = DefaultSubstepCount)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (!float.IsFinite(deltaTime) || deltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(deltaTime), "Delta time must be finite and positive.");
|
||||
}
|
||||
|
||||
if (substepCount <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(substepCount), "Substep count must be positive.");
|
||||
}
|
||||
|
||||
var native = new Box3DRadialField[fields.Length];
|
||||
for (var i = 0; i < fields.Length; i++)
|
||||
{
|
||||
native[i] = new Box3DRadialField(fields[i].PositionX, fields[i].PositionZ, fields[i].Strength, fields[i].Radius);
|
||||
}
|
||||
|
||||
fixed (Box3DRadialField* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(
|
||||
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();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_handle.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
internal static void EnsureCompatibleNativeLibrary()
|
||||
{
|
||||
var abi = Box3DNative.ymir_box3d_get_abi_version();
|
||||
if (abi != AbiVersion)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir Box3D ABI mismatch. Managed expects {AbiVersion}, native provides {abi}.");
|
||||
}
|
||||
|
||||
ThrowIfFailed(
|
||||
Box3DNative.ymir_box3d_get_abi_layout(
|
||||
out var bodyInputSize,
|
||||
out var fieldInputSize,
|
||||
out var bodyOutputSize,
|
||||
out var contactOutputSize),
|
||||
"read native ABI layout");
|
||||
EnsureSize<Box3DBodyInput>(bodyInputSize);
|
||||
EnsureSize<Box3DRadialField>(fieldInputSize);
|
||||
EnsureSize<Box3DBodyOutput>(bodyOutputSize);
|
||||
EnsureSize<Box3DContactOutput>(contactOutputSize);
|
||||
|
||||
Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision);
|
||||
if (major != 0 || minor != 1 || revision != 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir requires Box3D 0.1.0, but loaded {major}.{minor}.{revision}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureSize<T>(uint nativeSize) where T : struct
|
||||
{
|
||||
var managedSize = checked((uint)Marshal.SizeOf<T>());
|
||||
if (managedSize != nativeSize)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Ymir Box3D ABI layout mismatch for {typeof(T).Name}. Managed expects {managedSize} bytes, native provides {nativeSize}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ThrowIfFailed(Box3DStatus status, string operation)
|
||||
{
|
||||
if (status != Box3DStatus.Ok)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir could not {operation}: native Box3D status {status}.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
3
src/Ymir.Box3D/Properties/AssemblyInfo.cs
Normal file
3
src/Ymir.Box3D/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Core")]
|
||||
13
src/Ymir.Box3D/README.md
Normal file
13
src/Ymir.Box3D/README.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# GameCult.Ymir.Box3D
|
||||
|
||||
This is Ymir's private managed/native boundary for pinned Box3D v0.1.0. It is
|
||||
installed transitively by Ymir; products and clients should reference Ymir's
|
||||
typed session contracts instead of this package.
|
||||
|
||||
The package includes the compiled native facade under `runtimes/<rid>/native`.
|
||||
Package consumers do not need CMake, a C compiler, or the Box3D submodule.
|
||||
Missing or ABI-incompatible native assets fail closed when Ymir opens a physics
|
||||
session.
|
||||
|
||||
Source builds of Ymir use CMake to compile the pinned submodule. Box3D is MIT
|
||||
licensed; its license is included in the package.
|
||||
58
src/Ymir.Box3D/Ymir.Box3D.csproj
Normal file
58
src/Ymir.Box3D/Ymir.Box3D.csproj
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>Ymir.Box3D</RootNamespace>
|
||||
<AssemblyName>Ymir.Box3D</AssemblyName>
|
||||
<Description>Native ABI boundary between Ymir sessions and pinned Box3D.</Description>
|
||||
<PackageId>GameCult.Ymir.Box3D</PackageId>
|
||||
<Version>0.1.0</Version>
|
||||
<Authors>GameCult</Authors>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\production\$(Configuration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(NativeBuildDir)\bin\$(Configuration)\ymir_box3d.dll"
|
||||
Link="ymir_box3d.dll"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/win-x64/native/ymir_box3d.dll"
|
||||
Condition="'$(OS)' == 'Windows_NT'" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.so"
|
||||
Link="libymir_box3d.so"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/linux-x64/native/libymir_box3d.so"
|
||||
Condition="'$(OS)' != 'Windows_NT' and !$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.dylib"
|
||||
Link="libymir_box3d.dylib"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/osx-x64/native/libymir_box3d.dylib"
|
||||
Condition="$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="..\..\extern\box3d\LICENSE"
|
||||
Link="box3d-MIT.txt"
|
||||
Pack="true"
|
||||
PackagePath="licenses" />
|
||||
<None Include="README.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="BuildYmirBox3DNative"
|
||||
BeforeTargets="PrepareForBuild;GetCopyToOutputDirectoryItems;GetCopyToPublishDirectoryItems"
|
||||
Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DBUILD_SHARED_LIBS=OFF" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(Configuration) --target ymir_box3d" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
|
@ -18,7 +18,10 @@ public sealed record PhysicsBody(
|
|||
float Radius,
|
||||
float Mass,
|
||||
bool IsStatic = false,
|
||||
float Restitution = 0.2f);
|
||||
float Restitution = 0.2f,
|
||||
Vec2? Direction = null,
|
||||
float AngularVelocity = 0.0f,
|
||||
float Torque = 0.0f);
|
||||
|
||||
public sealed record RadialField(
|
||||
string Id,
|
||||
|
|
@ -46,3 +49,31 @@ public sealed record ContactEvent(
|
|||
public sealed record SimulationStepResult(
|
||||
YmirWorld World,
|
||||
IReadOnlyList<ContactEvent> Contacts);
|
||||
|
||||
public sealed record CircleCastQueryRequest(
|
||||
Vec2 Origin,
|
||||
Vec2 Direction,
|
||||
float Distance,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleCastHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleCastQueryResult(IReadOnlyList<CircleCastHit> Hits);
|
||||
|
||||
public sealed record CircleOverlapQueryRequest(
|
||||
Vec2 Center,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleOverlapHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleOverlapQueryResult(IReadOnlyList<CircleOverlapHit> Hits);
|
||||
|
|
|
|||
3
src/Ymir.Core/Properties/AssemblyInfo.cs
Normal file
3
src/Ymir.Core/Properties/AssemblyInfo.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Tests")]
|
||||
|
|
@ -6,6 +6,7 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Ymir.Box3D\Ymir.Box3D.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
|
||||
<ProjectReference Include="$(EveUnityRoot)\packages\org.gamecult.eve.surface\GameCult.Eve.Surface.csproj" />
|
||||
|
|
@ -18,7 +19,7 @@
|
|||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Ymir.Core</RootNamespace>
|
||||
<AssemblyName>Ymir.Core</AssemblyName>
|
||||
<Description>GameCult physics/world substrate engine built on CultMath.</Description>
|
||||
<Description>GameCult physics session daemon and contracts backed by pinned Box3D.</Description>
|
||||
<Authors>GameCult</Authors>
|
||||
</PropertyGroup>
|
||||
|
||||
|
|
|
|||
116
src/Ymir.Core/YmirQueries.cs
Normal file
116
src/Ymir.Core/YmirQueries.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public static class YmirQueries
|
||||
{
|
||||
public static CircleOverlapQueryResult OverlapCircle(CircleOverlapQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Center.X) || !float.IsFinite(request.Center.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap center must be finite.");
|
||||
}
|
||||
|
||||
var hits = new List<CircleOverlapHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
var hit = Box3DQueries.OverlapSpheres(
|
||||
request.Center.X,
|
||||
request.Center.Y,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleOverlapHit(
|
||||
body.Id,
|
||||
request.Center,
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Distance));
|
||||
}
|
||||
|
||||
return new CircleOverlapQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
public static CircleCastQueryResult CastCircle(CircleCastQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Distance) || request.Distance < 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast distance must be finite and non-negative.");
|
||||
}
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Origin.X) || !float.IsFinite(request.Origin.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast origin must be finite.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = request.Direction.X * request.Direction.X + request.Direction.Y * request.Direction.Y;
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
var inverseLength = 1.0f / MathF.Sqrt(directionLengthSquared);
|
||||
var translationX = request.Direction.X * inverseLength * request.Distance;
|
||||
var translationY = request.Direction.Y * inverseLength * request.Distance;
|
||||
var hits = new List<CircleCastHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
|
||||
var hit = Box3DQueries.CastSphere(
|
||||
request.Origin.X,
|
||||
request.Origin.Y,
|
||||
translationX,
|
||||
translationY,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleCastHit(
|
||||
body.Id,
|
||||
new Vec2(value.PointX, value.PointZ),
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Fraction * request.Distance));
|
||||
}
|
||||
|
||||
return new CircleCastQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
private static void ValidateQueryBody(PhysicsBody body, object request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(body.Id) ||
|
||||
!float.IsFinite(body.Position.X) ||
|
||||
!float.IsFinite(body.Position.Y) ||
|
||||
!float.IsFinite(body.Radius) ||
|
||||
body.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentException("Query bodies require stable ids and finite positive radii.", nameof(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ public sealed class YmirProviderAdvertisementDocument
|
|||
public string Title { get; set; } = "Ymir Physics";
|
||||
|
||||
[Key(2)]
|
||||
public string Description { get; set; } = "GameCult authoritative Box3D session wrapper and physics daemon.";
|
||||
public string Description { get; set; } = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface.";
|
||||
|
||||
[Key(3)]
|
||||
public string[] Owns { get; set; } = [];
|
||||
|
|
@ -44,7 +44,7 @@ public sealed class YmirOperatorStateDocument
|
|||
public string Status { get; set; } = "mvp";
|
||||
|
||||
[Key(2)]
|
||||
public string StateOwner { get; set; } = "Ymir world sessions and typed GameCult projections";
|
||||
public string StateOwner { get; set; } = "Isolated Box3D snapshot steps and typed diagnostic projections";
|
||||
|
||||
[Key(3)]
|
||||
public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)";
|
||||
|
|
@ -53,7 +53,7 @@ public sealed class YmirOperatorStateDocument
|
|||
public string BatchKernel { get; set; } = "";
|
||||
|
||||
[Key(5)]
|
||||
public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover";
|
||||
public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration";
|
||||
|
||||
[Key(6)]
|
||||
public string UpdatedAtUtc { get; set; } = "";
|
||||
|
|
@ -81,18 +81,21 @@ public static class YmirServicePublication
|
|||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Title = "Ymir Physics",
|
||||
Description = "GameCult authoritative Box3D session wrapper and physics daemon.",
|
||||
Description = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface.",
|
||||
Owns =
|
||||
[
|
||||
"authoritative physics session lifecycle",
|
||||
"stable GameCult id to Box3D handle projection",
|
||||
"typed physics commands and facts",
|
||||
"Box3D-only isolated snapshot stepping",
|
||||
"stable GameCult id to transient Box3D handle projection",
|
||||
"Box3D-backed circle overlap and cast queries over submitted bodies",
|
||||
"deterministic result ordering",
|
||||
"CultCache checkpoint reconstruction",
|
||||
"CultMesh and Eve service publication"
|
||||
"CultCache world snapshot v1 with explicit v0 read migration",
|
||||
"diagnostic Eve publication"
|
||||
],
|
||||
DoesNotOwn =
|
||||
[
|
||||
"public retained session lifecycle yet",
|
||||
"typed command receipts or begin/end/hit lifecycle facts yet",
|
||||
"complete checkpoint reconstruction yet",
|
||||
"physics algorithm invention",
|
||||
"Box3D solver and collision semantics",
|
||||
"Unity scene truth",
|
||||
|
|
@ -108,10 +111,10 @@ public static class YmirServicePublication
|
|||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Status = "mvp",
|
||||
StateOwner = "Ymir world sessions and typed GameCult projections",
|
||||
StateOwner = "Isolated Box3D snapshot steps and typed diagnostic projections",
|
||||
NumericSubstrate = "Box3D v0.1.0 (C17)",
|
||||
BatchKernel = "Box3D native solver; Ymir does not own physics algorithms",
|
||||
Persistence = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover",
|
||||
Persistence = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration",
|
||||
UpdatedAtUtc = FormatUtc(now)
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,144 +1,20 @@
|
|||
using CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Compatibility façade for the snapshot-in/snapshot-out Ymir contract.
|
||||
/// Calls are isolated by design; retained world ownership is not inferred from snapshots.
|
||||
/// </summary>
|
||||
public sealed class YmirSimulator
|
||||
{
|
||||
private const float MinimumMass = 0.0001f;
|
||||
private const float MinimumDistance = 0.0001f;
|
||||
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
var result = Step(new SoASimulationStepRequest(
|
||||
request.DeltaTime,
|
||||
YmirSoAWorld.FromWorld(request.World)));
|
||||
|
||||
return new SimulationStepResult(result.World.ToWorld(), result.Contacts);
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
if (request.DeltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be positive.");
|
||||
}
|
||||
|
||||
var world = request.World.Clone();
|
||||
world.Validate();
|
||||
|
||||
var accelerationX = new float[world.BodyCount];
|
||||
var accelerationY = new float[world.BodyCount];
|
||||
for (var i = 0; i < world.FieldCount; i++)
|
||||
{
|
||||
BatchMath.AddRadialFalloffAcceleration2D(
|
||||
world.PositionX,
|
||||
world.PositionY,
|
||||
world.FieldPositionX[i],
|
||||
world.FieldPositionY[i],
|
||||
world.FieldStrength[i],
|
||||
world.FieldRadius[i],
|
||||
accelerationX,
|
||||
accelerationY);
|
||||
}
|
||||
|
||||
BatchMath.IntegrateSemiImplicitEuler2D(
|
||||
request.DeltaTime,
|
||||
world.DynamicMask,
|
||||
world.PositionX,
|
||||
world.PositionY,
|
||||
world.VelocityX,
|
||||
world.VelocityY,
|
||||
accelerationX,
|
||||
accelerationY);
|
||||
|
||||
var contacts = new List<ContactEvent>();
|
||||
ResolveCircleContacts(world, contacts);
|
||||
|
||||
world.Time += request.DeltaTime;
|
||||
return new SoASimulationStepResult(
|
||||
world,
|
||||
contacts);
|
||||
}
|
||||
|
||||
private static void ResolveCircleContacts(YmirSoAWorld world, List<ContactEvent> contacts)
|
||||
{
|
||||
for (var i = 0; i < world.BodyCount; i++)
|
||||
{
|
||||
for (var j = i + 1; j < world.BodyCount; j++)
|
||||
{
|
||||
var delta = world.PositionAt(j) - world.PositionAt(i);
|
||||
var distance = length(delta);
|
||||
var combinedRadius = world.Radius[i] + world.Radius[j];
|
||||
var penetration = combinedRadius - distance;
|
||||
|
||||
if (penetration <= 0.0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normal = distance <= MinimumDistance ? float2(1.0f, 0.0f) : delta / distance;
|
||||
var point = world.PositionAt(i) + normal * (world.Radius[i] - penetration * 0.5f);
|
||||
var relativeVelocity = world.VelocityAt(j) - world.VelocityAt(i);
|
||||
var relativeSpeed = dot(relativeVelocity, normal);
|
||||
|
||||
contacts.Add(new ContactEvent(
|
||||
world.BodyIds[i],
|
||||
world.BodyIds[j],
|
||||
Vec2.FromCultMath(point),
|
||||
Vec2.FromCultMath(normal),
|
||||
penetration,
|
||||
relativeSpeed));
|
||||
|
||||
ResolveImpulse(world, i, j, normal, penetration, relativeSpeed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResolveImpulse(
|
||||
YmirSoAWorld world,
|
||||
int left,
|
||||
int right,
|
||||
float2 normal,
|
||||
float penetration,
|
||||
float relativeSpeed)
|
||||
{
|
||||
var leftInvMass = world.DynamicMask[left] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[left], MinimumMass);
|
||||
var rightInvMass = world.DynamicMask[right] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[right], MinimumMass);
|
||||
var invMassSum = leftInvMass + rightInvMass;
|
||||
if (invMassSum <= 0.0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var correction = normal * (penetration / invMassSum);
|
||||
if (leftInvMass > 0.0f)
|
||||
{
|
||||
world.SetPosition(left, world.PositionAt(left) - correction * leftInvMass);
|
||||
}
|
||||
|
||||
if (rightInvMass > 0.0f)
|
||||
{
|
||||
world.SetPosition(right, world.PositionAt(right) + correction * rightInvMass);
|
||||
}
|
||||
|
||||
if (relativeSpeed >= 0.0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var restitution = min(world.Restitution[left], world.Restitution[right]);
|
||||
var impulseMagnitude = -(1.0f + restitution) * relativeSpeed / invMassSum;
|
||||
var impulse = normal * impulseMagnitude;
|
||||
|
||||
if (leftInvMass > 0.0f)
|
||||
{
|
||||
world.SetVelocity(left, world.VelocityAt(left) - impulse * leftInvMass);
|
||||
}
|
||||
|
||||
if (rightInvMass > 0.0f)
|
||||
{
|
||||
world.SetVelocity(right, world.VelocityAt(right) + impulse * rightInvMass);
|
||||
}
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,10 @@ public sealed class YmirSoAWorld
|
|||
public float[] PositionY { get; set; } = [];
|
||||
public float[] VelocityX { get; set; } = [];
|
||||
public float[] VelocityY { get; set; } = [];
|
||||
public float[] DirectionX { get; set; } = [];
|
||||
public float[] DirectionY { get; set; } = [];
|
||||
public float[] AngularVelocity { get; set; } = [];
|
||||
public float[] Torque { get; set; } = [];
|
||||
public float[] Radius { get; set; } = [];
|
||||
public float[] Mass { get; set; } = [];
|
||||
public float[] DynamicMask { get; set; } = [];
|
||||
|
|
@ -37,6 +41,10 @@ public sealed class YmirSoAWorld
|
|||
PositionY = bodies.Select(body => body.Position.Y).ToArray(),
|
||||
VelocityX = bodies.Select(body => body.Velocity.X).ToArray(),
|
||||
VelocityY = bodies.Select(body => body.Velocity.Y).ToArray(),
|
||||
DirectionX = bodies.Select(body => DirectionOrDefault(body.Direction).X).ToArray(),
|
||||
DirectionY = bodies.Select(body => DirectionOrDefault(body.Direction).Y).ToArray(),
|
||||
AngularVelocity = bodies.Select(body => body.AngularVelocity).ToArray(),
|
||||
Torque = bodies.Select(body => body.Torque).ToArray(),
|
||||
Radius = bodies.Select(body => body.Radius).ToArray(),
|
||||
Mass = bodies.Select(body => body.Mass).ToArray(),
|
||||
DynamicMask = bodies.Select(body => body.IsStatic ? 0.0f : 1.0f).ToArray(),
|
||||
|
|
@ -59,7 +67,10 @@ public sealed class YmirSoAWorld
|
|||
Radius[i],
|
||||
Mass[i],
|
||||
DynamicMask[i] <= 0.0f,
|
||||
Restitution[i]))
|
||||
Restitution[i],
|
||||
new Vec2(DirectionX[i], DirectionY[i]),
|
||||
AngularVelocity[i],
|
||||
Torque[i]))
|
||||
.ToArray(),
|
||||
Enumerable.Range(0, FieldCount)
|
||||
.Select(i => new RadialField(
|
||||
|
|
@ -77,6 +88,10 @@ public sealed class YmirSoAWorld
|
|||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone(),
|
||||
Torque = (float[])Torque.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
|
|
@ -109,6 +124,17 @@ public sealed class YmirSoAWorld
|
|||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Mass), "Dynamic body mass must be positive.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = DirectionX[i] * DirectionX[i] + DirectionY[i] * DirectionY[i];
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(DirectionX), "Body direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
if (!float.IsFinite(AngularVelocity[i]) || !float.IsFinite(Torque[i]))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(AngularVelocity), "Body angular state must be finite.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,12 +157,17 @@ public sealed class YmirSoAWorld
|
|||
private void ValidateBodyLengths()
|
||||
{
|
||||
var expected = BodyIds.Length;
|
||||
FillMissingAngularState(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,
|
||||
|
|
@ -150,6 +181,40 @@ public sealed class YmirSoAWorld
|
|||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
|
|
|||
200
src/Ymir.Core/YmirWorldSession.cs
Normal file
200
src/Ymir.Core/YmirWorldSession.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Owns one retained Box3D world and its stable GameCult identity projection.
|
||||
/// Callers own the session lifetime; body snapshots do not imply session identity.
|
||||
/// </summary>
|
||||
internal sealed class YmirWorldSession : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Box3DSession _session = new();
|
||||
private readonly Dictionary<string, ulong> _keysById = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<ulong, string> _idsByKey = new();
|
||||
private ulong _nextKey = 1;
|
||||
private bool _disposed;
|
||||
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var result = Step(new SoASimulationStepRequest(
|
||||
request.DeltaTime,
|
||||
YmirSoAWorld.FromWorld(request.World)));
|
||||
|
||||
return new SimulationStepResult(result.World.ToWorld(), result.Contacts);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.DeltaTime) || request.DeltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be finite and positive.");
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var world = request.World.Clone();
|
||||
world.Validate();
|
||||
ValidateStableIds(world.BodyIds);
|
||||
|
||||
var indicesByKey = new Dictionary<ulong, int>(world.BodyCount);
|
||||
foreach (var id in world.BodyIds.OrderBy(id => id, StringComparer.Ordinal))
|
||||
{
|
||||
GetOrCreateKey(id);
|
||||
}
|
||||
|
||||
var bodies = new Box3DBody[world.BodyCount];
|
||||
for (var i = 0; i < world.BodyCount; i++)
|
||||
{
|
||||
var key = GetOrCreateKey(world.BodyIds[i]);
|
||||
indicesByKey.Add(key, i);
|
||||
bodies[i] = new Box3DBody(
|
||||
key,
|
||||
world.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);
|
||||
}
|
||||
|
||||
Array.Sort(bodies, static (left, right) => left.StableId.CompareTo(right.StableId));
|
||||
|
||||
var fields = Enumerable.Range(0, world.FieldCount)
|
||||
.OrderBy(index => world.FieldIds[index], StringComparer.Ordinal)
|
||||
.Select(index => new Box3DField(
|
||||
world.FieldPositionX[index],
|
||||
world.FieldPositionY[index],
|
||||
world.FieldStrength[index],
|
||||
world.FieldRadius[index]))
|
||||
.ToArray();
|
||||
|
||||
_session.SyncBodies(bodies);
|
||||
_session.Step(request.DeltaTime, fields);
|
||||
|
||||
foreach (var body in _session.CopyBodies())
|
||||
{
|
||||
if (!indicesByKey.TryGetValue(body.StableId, out var index))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {body.StableId}.");
|
||||
}
|
||||
|
||||
world.PositionX[index] = body.PositionX;
|
||||
world.PositionY[index] = body.PositionZ;
|
||||
world.VelocityX[index] = body.VelocityX;
|
||||
world.VelocityY[index] = body.VelocityZ;
|
||||
world.DirectionX[index] = body.DirectionX;
|
||||
world.DirectionY[index] = body.DirectionZ;
|
||||
world.AngularVelocity[index] = body.AngularVelocity;
|
||||
world.Torque[index] = 0.0f;
|
||||
}
|
||||
|
||||
var contacts = _session.CopyContacts()
|
||||
.Select(ProjectContact)
|
||||
.OrderBy(contact => contact.BodyA, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.BodyB, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.Point.X)
|
||||
.ThenBy(contact => contact.Point.Y)
|
||||
.ToArray();
|
||||
|
||||
PruneInactiveIds(world.BodyIds);
|
||||
|
||||
world.Time += request.DeltaTime;
|
||||
return new SoASimulationStepResult(world, contacts);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_session.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private ulong GetOrCreateKey(string id)
|
||||
{
|
||||
if (_keysById.TryGetValue(id, out var existing))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (_nextKey == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Ymir exhausted its stable native body key space.");
|
||||
}
|
||||
|
||||
var key = _nextKey++;
|
||||
_keysById.Add(id, key);
|
||||
_idsByKey.Add(key, id);
|
||||
return key;
|
||||
}
|
||||
|
||||
private ContactEvent ProjectContact(Box3DContact contact)
|
||||
{
|
||||
var bodyA = ResolveId(contact.StableIdA);
|
||||
var bodyB = ResolveId(contact.StableIdB);
|
||||
var normal = new Vec2(contact.NormalX, contact.NormalZ);
|
||||
if (StringComparer.Ordinal.Compare(bodyA, bodyB) > 0)
|
||||
{
|
||||
(bodyA, bodyB) = (bodyB, bodyA);
|
||||
normal = new Vec2(-normal.X, -normal.Y);
|
||||
}
|
||||
|
||||
return new ContactEvent(
|
||||
bodyA,
|
||||
bodyB,
|
||||
new Vec2(contact.PointX, contact.PointZ),
|
||||
normal,
|
||||
contact.Penetration,
|
||||
contact.RelativeSpeed);
|
||||
}
|
||||
|
||||
private string ResolveId(ulong key)
|
||||
{
|
||||
if (!_idsByKey.TryGetValue(key, out var id))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {key}.");
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private void PruneInactiveIds(IReadOnlyList<string> activeIds)
|
||||
{
|
||||
var active = activeIds.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var id in _keysById.Keys.Where(id => !active.Contains(id)).ToArray())
|
||||
{
|
||||
var key = _keysById[id];
|
||||
_keysById.Remove(id);
|
||||
_idsByKey.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateStableIds(IReadOnlyList<string> bodyIds)
|
||||
{
|
||||
var unique = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var id in bodyIds)
|
||||
{
|
||||
if (!unique.Add(id))
|
||||
{
|
||||
throw new ArgumentException($"Ymir body id '{id}' occurs more than once.", nameof(bodyIds));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ namespace Ymir.Core;
|
|||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v0")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocument
|
||||
public sealed class YmirWorldStateDocumentV0
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
|
|
@ -57,7 +57,7 @@ public sealed class YmirWorldStateDocument
|
|||
[Key(15)]
|
||||
public float[] FieldRadius { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocument FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
public static YmirWorldStateDocumentV0 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
|
|
@ -97,6 +97,76 @@ public sealed class YmirWorldStateDocument
|
|||
};
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV1
|
||||
{
|
||||
[Key(0), CultName] public string WorldId { get; set; } = "default";
|
||||
[Key(1)] public float Time { get; set; }
|
||||
[Key(2)] public string[] BodyIds { get; set; } = [];
|
||||
[Key(3)] public float[] PositionX { get; set; } = [];
|
||||
[Key(4)] public float[] PositionY { get; set; } = [];
|
||||
[Key(5)] public float[] VelocityX { get; set; } = [];
|
||||
[Key(6)] public float[] VelocityY { get; set; } = [];
|
||||
[Key(7)] public float[] Radius { get; set; } = [];
|
||||
[Key(8)] public float[] Mass { get; set; } = [];
|
||||
[Key(9)] public float[] DynamicMask { get; set; } = [];
|
||||
[Key(10)] public float[] Restitution { get; set; } = [];
|
||||
[Key(11)] public string[] FieldIds { get; set; } = [];
|
||||
[Key(12)] public float[] FieldPositionX { get; set; } = [];
|
||||
[Key(13)] public float[] FieldPositionY { get; set; } = [];
|
||||
[Key(14)] public float[] FieldStrength { get; set; } = [];
|
||||
[Key(15)] public float[] FieldRadius { get; set; } = [];
|
||||
[Key(16)] public float[] DirectionX { get; set; } = [];
|
||||
[Key(17)] public float[] DirectionY { get; set; } = [];
|
||||
[Key(18)] public float[] AngularVelocity { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV1 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(),
|
||||
PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(),
|
||||
VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(),
|
||||
Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(),
|
||||
Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(),
|
||||
FieldRadius = (float[])world.FieldRadius.Clone(),
|
||||
DirectionX = (float[])world.DirectionX.Clone(),
|
||||
DirectionY = (float[])world.DirectionY.Clone(),
|
||||
AngularVelocity = (float[])world.AngularVelocity.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time,
|
||||
BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(),
|
||||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(),
|
||||
FieldRadius = (float[])FieldRadius.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
public static class YmirCultCacheStore
|
||||
{
|
||||
public static async Task SaveWorldAsync(string path, string worldId, YmirSoAWorld world)
|
||||
|
|
@ -113,8 +183,8 @@ public static class YmirCultCacheStore
|
|||
using (cache)
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
YmirWorldStateDocument.FromSoA(worldId, world),
|
||||
new CultRecordHandle<YmirWorldStateDocument>(new CultRecordKey($"ymir:world:{worldId}")))
|
||||
YmirWorldStateDocumentV1.FromSoA(worldId, world),
|
||||
new CultRecordHandle<YmirWorldStateDocumentV1>(new CultRecordKey($"ymir:world:{worldId}")))
|
||||
.ConfigureAwait(false);
|
||||
await cache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
|
@ -125,6 +195,8 @@ public static class YmirCultCacheStore
|
|||
using var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false);
|
||||
return cache.Get<YmirWorldStateDocument>(new CultRecordKey($"ymir:world:{worldId}"))?.ToSoA();
|
||||
var key = new CultRecordKey($"ymir:world:{worldId}");
|
||||
return cache.Get<YmirWorldStateDocumentV1>(key)?.ToSoA()
|
||||
?? cache.Get<YmirWorldStateDocumentV0>(key)?.ToSoA();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ internal static class Program
|
|||
ok = true,
|
||||
path,
|
||||
record = "ymir:world:sample",
|
||||
schema = "gamecult.ymir.world_state.v0",
|
||||
schema = "gamecult.ymir.world_state.v1",
|
||||
bodyCount = result.World.BodyCount,
|
||||
fieldCount = result.World.FieldCount
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue