From 5fbb4c0adbaf2bd7fcaf9e2fe0021a3850d1e08a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Dec 2026 21:29:24 +0100 Subject: [PATCH] Ymir: expose static heightfield and triangle mesh shapes on Box3DSoaWorld --- docs/soa-world.md | 4 +- native/Ymir.Box3D/ymir_box3d_soa.c | 280 +++++++++++++++++- src/Ymir.Box3D/Box3DSoaWorld.cs | 74 ++++- .../Box3DSoaTerrainTests.cs | 272 +++++++++++++++++ 4 files changed, 621 insertions(+), 9 deletions(-) create mode 100644 tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs diff --git a/docs/soa-world.md b/docs/soa-world.md index 4d49d4d..6a839b9 100644 --- a/docs/soa-world.md +++ b/docs/soa-world.md @@ -7,8 +7,8 @@ Box3D decides every physical outcome; Ymir creates bodies, steps the world and e - Native (ABI 21): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) / create_particles / destroy_particles / create_distances / create_bends / create_sensors / take_wet(n, sensors, volumes, taken) / attach(n, desc*) / set_pinned(n, handles, pinned) / remove / set_material / free_slots / - add_body / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / set_joint_thresholds / remove_body / free_joint_slots / free_body_slots / apply_impulse / cast_ray_closest / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box, anchor; position, - rotation, velocity, size, density, friction, restitution, rolling resistance, material id, parent, limb). Capacities are fixed at creation, + add_body / add_static_heightfield / add_static_mesh / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / set_joint_thresholds / remove_body / free_joint_slots / free_body_slots / apply_impulse / cast_ray_closest / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box, anchor; position, + rotation, velocity, size, density, friction, restitution, rolling resistance, material id, parent, limb). `add_static_heightfield` (kind 6) and `add_static_mesh` (kind 7) create static terrain/mesh bodies whose native `b3HeightFieldData` / `b3MeshData` allocations are owned per body slot and destroyed after `b3DestroyBody` / `b3DestroyWorld` on `remove_body` / `destroy` (particle proxies treat both as `YMIR_PROXY_NONE`). Capacities are fixed at creation, so lane pointers never move. - Body lanes (`ymir_box3d_soa_view`): `stable_id`, `kind`, `parent` and `limb` (set at creation, not read by Box3D: the limb tree for the consumer), `size_0`, `size_1`, `size_2` (read-only shape size set at creation, diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index 9fbc076..560d431 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -82,7 +82,9 @@ enum YMIR_SOA_KIND_CAPSULE = 2, YMIR_SOA_KIND_BOX = 3, YMIR_SOA_KIND_ANCHOR = 4, - YMIR_SOA_KIND_REMOVED = 5 // a removed body's lane (remove_body): never accepted by add_body + YMIR_SOA_KIND_REMOVED = 5, // a removed body's lane (remove_body): never accepted by add_body + YMIR_SOA_KIND_STATIC_HEIGHTFIELD = 6, + YMIR_SOA_KIND_STATIC_MESH = 7 }; enum @@ -493,6 +495,8 @@ typedef struct ymir_box3d_soa_world int32_t joint_capacity; uint64_t step_count; b3BodyId* bodies; + b3HeightFieldData** heightfields; // `capacity` entries: owned per slot for YMIR_SOA_KIND_STATIC_HEIGHTFIELD + b3MeshData** meshes; // `capacity` entries: owned per slot for YMIR_SOA_KIND_STATIC_MESH uint64_t* stable_id; uint32_t* kind; int32_t* parent; @@ -678,6 +682,28 @@ YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_facts_size(void) static void ymir_soa_free(ymir_box3d_soa_world* world) { + if (world->heightfields != NULL) + { + for (int i = 0; i < world->capacity; ++i) + { + if (world->heightfields[i] != NULL) + { + b3DestroyHeightField(world->heightfields[i]); + } + } + free(world->heightfields); + } + if (world->meshes != NULL) + { + for (int i = 0; i < world->capacity; ++i) + { + if (world->meshes[i] != NULL) + { + b3DestroyMesh(world->meshes[i]); + } + } + free(world->meshes); + } free(world->bodies); free(world->stable_id); free(world->kind); @@ -752,6 +778,8 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( size_t n = (size_t)capacity; size_t m = (size_t)joint_capacity > 0 ? (size_t)joint_capacity : 1; // calloc(0) may return NULL world->bodies = (b3BodyId*)calloc(n, sizeof(b3BodyId)); + world->heightfields = (b3HeightFieldData**)calloc(n, sizeof(b3HeightFieldData*)); + world->meshes = (b3MeshData**)calloc(n, sizeof(b3MeshData*)); world->stable_id = (uint64_t*)calloc(n, sizeof(uint64_t)); world->kind = (uint32_t*)calloc(n, sizeof(uint32_t)); world->parent = (int32_t*)calloc(n, sizeof(int32_t)); @@ -800,7 +828,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( world->end_facts == NULL || world->touching_facts == NULL || world->hit_facts == NULL || world->overload_facts == NULL || world->contact_scratch == NULL || world->body_removed_facts == NULL || world->body_removed_pending == NULL || world->joint_removed_facts == NULL || world->joint_removed_pending == NULL || world->retired_shapes == NULL || - world->bodies == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL || + world->bodies == NULL || world->heightfields == NULL || world->meshes == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL || world->limb == NULL || world->size == NULL || world->lanes == NULL || world->joints == NULL || world->joint_kind == NULL || world->joint_body_a == NULL || world->joint_body_b == NULL || world->joint_local_a == NULL || world->joint_local_origin_a == NULL || world->joint_local_b == NULL || world->joint_lanes == NULL || world->joint_removed_at == NULL || @@ -940,6 +968,64 @@ static int32_t ymir_soa_check_body(const ymir_box3d_soa_world* world, const ymir return YMIR_SOA_OK; } +static int32_t ymir_soa_check_static_slot(const ymir_box3d_soa_world* world, uint64_t stable_id) +{ + if (ymir_soa_body_slot(world) < 0) + { + return YMIR_SOA_FULL; + } + for (int i = 0; i < world->count; ++i) + { + if (world->kind[i] != YMIR_SOA_KIND_REMOVED && world->stable_id[i] == stable_id) + { + return YMIR_SOA_DUPLICATE_ID; + } + } + return YMIR_SOA_OK; +} + +static b3ShapeDef ymir_soa_static_shape_def( + uint64_t stable_id, float friction, float restitution, uint64_t material_id) +{ + b3ShapeDef shape_def = b3DefaultShapeDef(); + shape_def.userData = (void*)(uintptr_t)stable_id; + shape_def.enableContactEvents = true; // off by default in Box3D + shape_def.enableHitEvents = true; + shape_def.baseMaterial.userMaterialId = material_id; + shape_def.baseMaterial.friction = friction; + shape_def.baseMaterial.restitution = restitution; + return shape_def; +} + +static void ymir_soa_commit_static_slot( + ymir_box3d_soa_world* world, int slot, b3BodyId body, uint32_t kind, uint64_t stable_id, uint64_t material_id, + b3HeightFieldData* hf, b3MeshData* mesh, int32_t* index) +{ + if (slot == world->count) + { + world->count++; + } + world->bodies[slot] = body; + world->heightfields[slot] = hf; + world->meshes[slot] = mesh; + world->stable_id[slot] = stable_id; + world->kind[slot] = kind; + world->parent[slot] = -1; + world->limb[slot] = 0; + world->contact_count[slot] = 0; + world->material_id[slot] = material_id; + world->mass[slot] = 0.0f; + for (int k = 0; k < 3; k++) + { + world->size[(size_t)k * (size_t)world->capacity + (size_t)slot] = 0.0f; + } + ymir_soa_refresh(world, slot); + if (index != NULL) + { + *index = slot; + } +} + // Creates one body from a descriptor. Box3D owns mass: it follows from `density` and the shape. YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_body( ymir_box3d_soa_world* world, const ymir_box3d_soa_body_desc* d, int32_t* index) @@ -1034,6 +1120,178 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_body( return YMIR_SOA_OK; } +// Creates a static heightfield body at `origin` with CCW top-facing triangles (`clockwiseWinding = false`). +// `ymir_box3d_soa_world` owns the `b3HeightFieldData*` for the slot's life and destroys it after the body on remove/destroy. +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_static_heightfield( + ymir_box3d_soa_world* world, uint64_t stable_id, float origin_x, float origin_y, float origin_z, + const float* heights, int32_t count_x, int32_t count_z, float scale_x, float scale_y, float scale_z, + float min_height, float max_height, float friction, float restitution, uint64_t material_id, int32_t* index) +{ + if (world == NULL || heights == NULL || count_x < 2 || count_z < 2 || + (int64_t)count_x * (int64_t)count_z > (int64_t)INT32_MAX / 2 || !ymir_soa_finite(origin_x) || + !ymir_soa_finite(origin_y) || !ymir_soa_finite(origin_z) || !ymir_soa_finite(scale_x) || + !ymir_soa_finite(scale_y) || !ymir_soa_finite(scale_z) || scale_x <= 0.0f || scale_y <= 0.0f || + scale_z <= 0.0f || !ymir_soa_finite(min_height) || !ymir_soa_finite(max_height) || + min_height > max_height || !ymir_soa_finite(friction) || !ymir_soa_finite(restitution) || + friction < 0.0f || restitution < 0.0f) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + int32_t height_count = count_x * count_z; + for (int32_t k = 0; k < height_count; ++k) + { + if (!ymir_soa_finite(heights[k])) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + } + int32_t status = ymir_soa_check_static_slot(world, stable_id); + if (status != YMIR_SOA_OK) + { + return status; + } + + float* heights_copy = (float*)malloc((size_t)height_count * sizeof(float)); + if (heights_copy == NULL) + { + return YMIR_SOA_OUT_OF_MEMORY; + } + memcpy(heights_copy, heights, (size_t)height_count * sizeof(float)); + + b3HeightFieldDef hf_def = {0}; + hf_def.heights = heights_copy; + hf_def.materialIndices = NULL; + hf_def.scale = (b3Vec3){scale_x, scale_y, scale_z}; + hf_def.countX = count_x; + hf_def.countZ = count_z; + hf_def.globalMinimumHeight = min_height; + hf_def.globalMaximumHeight = max_height; + hf_def.clockwiseWinding = false; + b3HeightFieldData* hf = b3CreateHeightField(&hf_def); + free(heights_copy); + if (hf == NULL) + { + return YMIR_SOA_INTERNAL_ERROR; + } + + int slot = ymir_soa_body_slot(world); + b3BodyDef body_def = b3DefaultBodyDef(); + body_def.type = b3_staticBody; + body_def.position = (b3Vec3){origin_x, origin_y, origin_z}; + body_def.enableSleep = false; + body_def.userData = (void*)((uintptr_t)slot + 1u); + b3BodyId body = b3CreateBody(world->world_id, &body_def); + if (B3_IS_NULL(body)) + { + b3DestroyHeightField(hf); + return YMIR_SOA_INTERNAL_ERROR; + } + + b3ShapeDef shape_def = ymir_soa_static_shape_def(stable_id, friction, restitution, material_id); + b3ShapeId shape = b3CreateHeightFieldShape(body, &shape_def, hf); + if (B3_IS_NULL(shape)) + { + b3DestroyBody(body); + b3DestroyHeightField(hf); + return YMIR_SOA_INTERNAL_ERROR; + } + + ymir_soa_commit_static_slot( + world, slot, body, YMIR_SOA_KIND_STATIC_HEIGHTFIELD, stable_id, material_id, hf, NULL, index); + return YMIR_SOA_OK; +} + +// Creates a static triangle mesh body at `origin` with CCW outward-facing triangles. +// `ymir_box3d_soa_world` owns the `b3MeshData*` for the slot's life and destroys it after the body on remove/destroy. +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_static_mesh( + ymir_box3d_soa_world* world, uint64_t stable_id, float origin_x, float origin_y, float origin_z, + const float* vertices_xyz, int32_t vertex_count, const int32_t* triangle_indices, int32_t triangle_count, + float friction, float restitution, uint64_t material_id, int32_t* index) +{ + if (world == NULL || vertices_xyz == NULL || triangle_indices == NULL || vertex_count < 3 || triangle_count <= 0 || + (int64_t)vertex_count * 3 > (int64_t)INT32_MAX || (int64_t)triangle_count * 3 > (int64_t)INT32_MAX || + !ymir_soa_finite(origin_x) || !ymir_soa_finite(origin_y) || !ymir_soa_finite(origin_z) || + !ymir_soa_finite(friction) || !ymir_soa_finite(restitution) || friction < 0.0f || restitution < 0.0f) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + int32_t float_count = vertex_count * 3; + for (int32_t k = 0; k < float_count; ++k) + { + if (!ymir_soa_finite(vertices_xyz[k])) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + } + int32_t index_count = triangle_count * 3; + for (int32_t k = 0; k < index_count; ++k) + { + if (triangle_indices[k] < 0 || triangle_indices[k] >= vertex_count) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + } + int32_t status = ymir_soa_check_static_slot(world, stable_id); + if (status != YMIR_SOA_OK) + { + return status; + } + + b3Vec3* verts = (b3Vec3*)malloc((size_t)vertex_count * sizeof(b3Vec3)); + int32_t* indices = (int32_t*)malloc((size_t)index_count * sizeof(int32_t)); + if (verts == NULL || indices == NULL) + { + free(verts); + free(indices); + return YMIR_SOA_OUT_OF_MEMORY; + } + for (int32_t k = 0; k < vertex_count; ++k) + { + verts[k] = (b3Vec3){vertices_xyz[(size_t)k * 3 + 0], vertices_xyz[(size_t)k * 3 + 1], vertices_xyz[(size_t)k * 3 + 2]}; + } + memcpy(indices, triangle_indices, (size_t)index_count * sizeof(int32_t)); + + b3MeshDef mesh_def = {0}; + mesh_def.vertices = verts; + mesh_def.indices = indices; + mesh_def.vertexCount = vertex_count; + mesh_def.triangleCount = triangle_count; + mesh_def.identifyEdges = true; + b3MeshData* mesh = b3CreateMesh(&mesh_def, NULL, 0); + free(verts); + free(indices); + if (mesh == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + + int slot = ymir_soa_body_slot(world); + b3BodyDef body_def = b3DefaultBodyDef(); + body_def.type = b3_staticBody; + body_def.position = (b3Vec3){origin_x, origin_y, origin_z}; + body_def.enableSleep = false; + body_def.userData = (void*)((uintptr_t)slot + 1u); + b3BodyId body = b3CreateBody(world->world_id, &body_def); + if (B3_IS_NULL(body)) + { + b3DestroyMesh(mesh); + return YMIR_SOA_INTERNAL_ERROR; + } + + b3ShapeDef shape_def = ymir_soa_static_shape_def(stable_id, friction, restitution, material_id); + b3ShapeId shape = b3CreateMeshShape(body, &shape_def, mesh, (b3Vec3){1.0f, 1.0f, 1.0f}); + if (B3_IS_NULL(shape)) + { + b3DestroyBody(body); + b3DestroyMesh(mesh); + return YMIR_SOA_INTERNAL_ERROR; + } + + ymir_soa_commit_static_slot( + world, slot, body, YMIR_SOA_KIND_STATIC_MESH, stable_id, material_id, NULL, mesh, index); + return YMIR_SOA_OK; +} + // The lane a new joint takes: the lowest tombstone whose destroying step has completed, else the next fresh // slot, else -1. A destroyed lane is not reused within the step that destroyed it, so lanes a caller read // that step stay meaningful. @@ -1268,6 +1526,16 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_remove_body(ymir_box3d_soa_world* w world->body_removed_pending[world->body_removed_pending_count++] = (ymir_box3d_soa_body_removed_fact){ .lane = lane, .generation = generation, .stable_id = world->stable_id[lane], .wet_patches = patches, .wet_volume = volume}; b3DestroyBody(world->bodies[lane]); + if (world->heightfields[lane] != NULL) + { + b3DestroyHeightField(world->heightfields[lane]); + world->heightfields[lane] = NULL; + } + if (world->meshes[lane] != NULL) + { + b3DestroyMesh(world->meshes[lane]); + world->meshes[lane] = NULL; + } world->bodies[lane] = (b3BodyId){0}; world->kind[lane] = YMIR_SOA_KIND_REMOVED; world->stable_id[lane] = 0; @@ -1533,10 +1801,10 @@ static void ymir_soa_gather_proxies(ymir_box3d_soa_world* world) b3Vec3 v = b3Body_GetLinearVelocity(body); b3Vec3 w = b3Body_GetAngularVelocity(body); memset(b, 0, sizeof(*b)); - b->shape = kind == YMIR_SOA_KIND_SPHERE ? YMIR_PROXY_SPHERE - : kind == YMIR_SOA_KIND_CAPSULE ? YMIR_PROXY_CAPSULE - : ymir_soa_is_anchor(kind) ? YMIR_PROXY_NONE - : YMIR_PROXY_BOX; + b->shape = kind == YMIR_SOA_KIND_SPHERE ? YMIR_PROXY_SPHERE + : kind == YMIR_SOA_KIND_CAPSULE ? YMIR_PROXY_CAPSULE + : (kind == YMIR_SOA_KIND_STATIC_BOX || kind == YMIR_SOA_KIND_BOX) ? YMIR_PROXY_BOX + : YMIR_PROXY_NONE; for (int k = 0; k < 3; ++k) { b->size[k] = world->size[(size_t)k * (size_t)world->capacity + (size_t)i]; diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 5e52077..0a0f005 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -1,4 +1,6 @@ using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Ymir.Box3D; @@ -12,7 +14,11 @@ public enum Box3DSoaKind : uint /// A kinematic body with no shape: it never collides or is hit, and only moves it. Anchor = 4, /// The kind lane of a removed body (a tombstone, from RemoveBody): every other lane reads 0 and the parent -1. - Removed = 5 + Removed = 5, + /// A static heightfield terrain body whose native heightfield data is owned by the world until removed or disposed. + StaticHeightField = 6, + /// A static triangle mesh body whose native mesh data is owned by the world until removed or disposed. + StaticMesh = 7 } public enum Box3DSoaJointKind : uint @@ -603,6 +609,20 @@ internal static unsafe partial class Box3DSoaNative [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_add_body(nint world, in Box3DSoaBodyDesc desc, out int index); + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_add_static_heightfield( + nint world, ulong stableId, float originX, float originY, float originZ, + float* heights, int countX, int countZ, float scaleX, float scaleY, float scaleZ, + float minHeight, float maxHeight, float friction, float restitution, ulong materialId, out int index); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_add_static_mesh( + nint world, ulong stableId, float originX, float originY, float originZ, + float* verticesXyz, int vertexCount, int* triangleIndices, int triangleCount, + float friction, float restitution, ulong materialId, out int index); + [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_add_joint(nint world, in Box3DSoaJointDesc desc, out int index); @@ -1086,6 +1106,53 @@ public sealed class Box3DSoaWorld : IDisposable AddBody(Describe(Box3DSoaKind.StaticBox, stableId, position, default, halfExtents, 0f, default, friction, restitution, -1, 0, 0f, materialId)); + /// + /// Adds a static heightfield body at with columns along X + /// and rows along Z (heights[z * countX + x]), scaled by + /// with CCW top-facing triangles. The native world owns the compiled heightfield until removed or disposed. + /// + public unsafe Box3DSoaBodyHandle AddStaticHeightField( + ulong stableId, (float X, float Y, float Z) origin, ReadOnlySpan heights, int countX, int countZ, + (float X, float Y, float Z) scale, float minHeight, float maxHeight, + float friction = 0.6f, float restitution = 0f, ulong materialId = 0) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + if (countX >= 2 && countZ >= 2 && (long)heights.Length != (long)countX * countZ) + throw new ArgumentException("Heights length must equal countX * countZ.", nameof(heights)); + fixed (float* h = heights) + { + Check(Box3DSoaNative.ymir_box3d_soa_add_static_heightfield( + _handle, stableId, origin.X, origin.Y, origin.Z, + countX >= 2 && countZ >= 2 ? h : null, countX, countZ, + scale.X, scale.Y, scale.Z, minHeight, maxHeight, friction, restitution, materialId, out var index)); + return BodyHandleOf(index); + } + } + + /// + /// Adds a static triangle mesh body at with CCW outward-facing triangles. + /// The native world owns the compiled mesh BVH until removed or disposed. + /// + public unsafe Box3DSoaBodyHandle AddStaticMesh( + ulong stableId, (float X, float Y, float Z) origin, ReadOnlySpan vertices, + ReadOnlySpan triangleIndices, float friction = 0.6f, float restitution = 0f, ulong materialId = 0) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + if (Unsafe.SizeOf() != sizeof(float) * 3) + throw new InvalidOperationException("Unexpected Vector3 layout."); + if (triangleIndices.Length % 3 != 0) + throw new ArgumentException("Triangle indices length must be a multiple of 3.", nameof(triangleIndices)); + fixed (Vector3* v = vertices) + fixed (int* idx = triangleIndices) + { + Check(Box3DSoaNative.ymir_box3d_soa_add_static_mesh( + _handle, stableId, origin.X, origin.Y, origin.Z, + (float*)v, vertices.Length, idx, triangleIndices.Length / 3, + friction, restitution, materialId, out var index)); + return BodyHandleOf(index); + } + } + /// /// Adds a dynamic capsule: a segment of either side of the centre along /// the body's local Y, swept by . is a unit quaternion @@ -1522,6 +1589,11 @@ public sealed class Box3DSoaWorld : IDisposable { ObjectDisposedException.ThrowIf(_handle == 0, this); Check(Box3DSoaNative.ymir_box3d_soa_add_body(_handle, desc, out var index)); + return BodyHandleOf(index); + } + + private unsafe Box3DSoaBodyHandle BodyHandleOf(int index) + { Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v)); return new Box3DSoaBodyHandle(index, v.BodyGeneration[index]); } diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs new file mode 100644 index 0000000..9900ecb --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs @@ -0,0 +1,272 @@ +using System.Numerics; +using Ymir.Box3D; + +namespace Ymir.Box3D.Soa.Tests; + +public sealed class Box3DSoaTerrainTests +{ + private const float Dt = 1f / 60f; + private const float G = 10f; + + /// + /// Smooth bowl heightfield: h(x, z) = 0.04 * (dx^2 + dz^2) where dx = x - cx, dz = z - cz. + /// Grid vertex (gx, gz) sits in world space at origin + (gx * scaleX, h(gx, gz) * scaleY, gz * scaleZ). + /// + private static float[] BuildBowlHeights(int countX, int countZ, float scaleX, float scaleZ, out float minH, out float maxH) + { + var cx = 0.5f * (countX - 1) * scaleX; + var cz = 0.5f * (countZ - 1) * scaleZ; + var heights = new float[countX * countZ]; + minH = float.PositiveInfinity; + maxH = float.NegativeInfinity; + for (var gz = 0; gz < countZ; gz++) + { + for (var gx = 0; gx < countX; gx++) + { + var dx = gx * scaleX - cx; + var dz = gz * scaleZ - cz; + var h = 0.04f * (dx * dx + dz * dz); + heights[gz * countX + gx] = h; + if (h < minH) minH = h; + if (h > maxH) maxH = h; + } + } + return heights; + } + + private static (Vector3[] Vertices, int[] Indices) BuildBoxPrismMesh(float hx, float hy, float hz) + { + // CCW outward winding matching Box3D b3CreateBoxMesh. + var vertices = new Vector3[] + { + new( hx, hy, hz), // 0: +x +y +z + new(-hx, hy, hz), // 1: -x +y +z + new(-hx, -hy, hz), // 2: -x -y +z + new( hx, -hy, hz), // 3: +x -y +z + new( hx, hy, -hz), // 4: +x +y -z + new(-hx, hy, -hz), // 5: -x +y -z + new(-hx, -hy, -hz), // 6: -x -y -z + new( hx, -hy, -hz), // 7: +x -y -z + }; + var indices = new[] + { + 0, 1, 3, 1, 2, 3, // +Z front + 0, 4, 1, 1, 4, 5, // +Y top + 0, 3, 7, 4, 0, 7, // +X right + 4, 7, 5, 6, 5, 7, // -Z back + 1, 5, 2, 6, 2, 5, // -X left + 3, 2, 7, 6, 7, 2, // -Y bottom + }; + return (vertices, indices); + } + + [Fact] + public void Dynamic_box_and_sphere_dropped_20m_onto_bowl_heightfield_land_and_rest_at_expected_elevation() + { + const int countX = 25; + const int countZ = 25; + const float scaleX = 1f; + const float scaleZ = 1f; + const float scaleY = 1f; + var origin = (-12f, 2f, -12f); // bowl centre sits at world (0, 2, 0) + var heights = BuildBowlHeights(countX, countZ, scaleX, scaleZ, out var minH, out var maxH); + + using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G); + var terrain = world.AddStaticHeightField( + 1001, origin, heights, countX, countZ, (scaleX, scaleY, scaleZ), minH, maxH, friction: 0.25f); + const float sphereRadius = 0.5f; + const float boxHalfY = 0.4f; + // Sphere dropped off-centre at x = 4, z = 0 from y = 22 (20 m above the bowl base y = 2): + // it lands on the slope and slides down into the bowl centre (x = 0, z = 0, terrain y = 2). + var sphere = world.AddSphere(2001, (4f, 22f, 0f), sphereRadius, density: 1f, friction: 0.25f); + // Box dropped straight onto the bowl centre at (0, 22, 0): rests flat at y = 2 + boxHalfY. + var box = world.AddBox(2002, (0f, 22f, 0f), (0.5f, boxHalfY, 0.5f), density: 1f, friction: 0.8f); + + var view = world.View; + Assert.Equal((uint)Box3DSoaKind.StaticHeightField, view.Kind[terrain]); + Assert.Equal(0f, view.Mass[terrain]); + Assert.Equal(origin, (view.PositionX[terrain], view.PositionY[terrain], view.PositionZ[terrain])); + + var minSphereY = float.PositiveInfinity; + var minBoxY = float.PositiveInfinity; + for (var i = 0; i < 600; i++) + { + world.Step(Dt); + if (view.PositionY[sphere] < minSphereY) minSphereY = view.PositionY[sphere]; + if (view.PositionY[box] < minBoxY) minBoxY = view.PositionY[box]; + } + + // Zero tunneling: neither body ever fell below the bowl floor. + Assert.True(minSphereY >= origin.Item2 + sphereRadius - 0.1f, $"sphere tunneled: minY={minSphereY}"); + Assert.True(minBoxY >= origin.Item2 + boxHalfY - 0.1f, $"box tunneled: minY={minBoxY}"); + + // Sphere slid down the slope toward the bowl centre and sits on the terrain surface. + Assert.True(MathF.Abs(view.PositionX[sphere]) < 1.5f, $"sphere did not slide toward bowl centre: x={view.PositionX[sphere]}"); + var sphereTerrainY = origin.Item2 + 0.04f * (view.PositionX[sphere] * view.PositionX[sphere] + view.PositionZ[sphere] * view.PositionZ[sphere]); + Assert.InRange(view.PositionY[sphere], sphereTerrainY + sphereRadius - 0.05f, sphereTerrainY + sphereRadius + 0.1f); + + // Box rests on the bowl centre at y = 2 + boxHalfY (slightly lifted at corners by bowl curvature). + Assert.InRange(view.PositionY[box], origin.Item2 + boxHalfY - 0.02f, origin.Item2 + boxHalfY + 0.08f); + Assert.True(MathF.Abs(view.VelocityY[box]) < 0.05f); + Assert.True(view.ContactCount[terrain] >= 1); + } + + [Fact] + public void Dynamic_box_collides_cleanly_with_static_mesh_roof_and_wall_without_penetrating() + { + var (vertices, indices) = BuildBoxPrismMesh(hx: 2f, hy: 2f, hz: 2f); + var buildingOrigin = (10f, 2f, 0f); // occupies x in [8, 12], y in [0, 4], z in [-2, 2] + + using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G); + world.AddStaticBox(1, (0f, -0.5f, 0f), (40f, 0.5f, 40f)); // floor top y = 0 + var building = world.AddStaticMesh(1002, buildingOrigin, vertices, indices, friction: 0.6f); + + // Roof drop: box dropped onto the mesh roof (y = 4) from y = 10. + var roofBox = world.AddBox(2001, (10f, 10f, 0f), (0.5f, 0.5f, 0.5f), density: 1f); + // Wall drive: box on the floor at x = 4 pushed in +X toward the building's -X wall at x = 8. + var wallBox = world.AddBox(2002, (4f, 0.5f, 0f), (0.5f, 0.5f, 0.5f), density: 1f, friction: 0.1f); + + var view = world.View; + Assert.Equal((uint)Box3DSoaKind.StaticMesh, view.Kind[building]); + Assert.Equal(0f, view.Mass[building]); + + for (var i = 0; i < 240; i++) + { + if (i < 120) + { + view.ForceX[wallBox] = 80f; + } + world.Step(Dt); + // Wall box must never penetrate past the building's -X wall (x = 8 - 0.5 = 7.5). + Assert.True(view.PositionX[wallBox] <= 7.5f + 0.03f, $"wall penetration at step {i}: x={view.PositionX[wallBox]}"); + } + + // Roof box rests cleanly on top of the mesh roof (y = 4 + 0.5 = 4.5). + Assert.InRange(view.PositionY[roofBox], 4.5f - 0.03f, 4.5f + 0.03f); + Assert.True(MathF.Abs(view.VelocityY[roofBox]) < 0.05f); + // Wall box stopped flush against the -X wall. + Assert.InRange(view.PositionX[wallBox], 7.4f, 7.53f); + } + + [Fact] + public void CastRayClosest_hits_both_static_heightfield_and_static_mesh_with_accurate_point_normal_and_identity() + { + // Sloped plane heightfield: h(x, z) = 0.5 * x, so surface normal is (-0.5, 1, 0) / sqrt(1.25). + const int countX = 5; + const int countZ = 5; + var heights = new float[countX * countZ]; + for (var gz = 0; gz < countZ; gz++) + { + for (var gx = 0; gx < countX; gx++) + { + heights[gz * countX + gx] = 0.5f * gx; + } + } + var hfOrigin = (-2f, 1f, -2f); + const ulong hfStableId = 7001ul; + + var (vertices, indices) = BuildBoxPrismMesh(hx: 1.5f, hy: 2f, hz: 1.5f); + var meshOrigin = (20f, 2f, 0f); // -X face at x = 18.5, normal (-1, 0, 0) + const ulong meshStableId = 7002ul; + + using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G); + var hf = world.AddStaticHeightField(hfStableId, hfOrigin, heights, countX, countZ, (1f, 1f, 1f), 0f, 2f); + var mesh = world.AddStaticMesh(meshStableId, meshOrigin, vertices, indices); + + // Ray straight down at world (0.25, 10, 0.25) -> local (2.25, 9, 2.25) -> terrain height = 1 + 0.5 * 2.25 = 2.125. + var hfHit = world.CastRayClosest((0.25f, 10f, 0.25f), (0f, -20f, 0f)); + Assert.True(hfHit.Hit); + Assert.Equal(hf.Lane, hfHit.Lane); + Assert.Equal(hfStableId, hfHit.StableId); + Assert.InRange(hfHit.Point.X, 0.249f, 0.251f); + Assert.InRange(hfHit.Point.Y, 2.125f - 0.002f, 2.125f + 0.002f); + Assert.InRange(hfHit.Point.Z, 0.249f, 0.251f); + var invLen = 1f / MathF.Sqrt(1.25f); + Assert.InRange(hfHit.Normal.X, -0.5f * invLen - 0.005f, -0.5f * invLen + 0.005f); + Assert.InRange(hfHit.Normal.Y, 1.0f * invLen - 0.005f, 1.0f * invLen + 0.005f); + Assert.InRange(hfHit.Normal.Z, -0.005f, 0.005f); + + // Ray in +X toward the mesh's -X face at x = 18.5. + var meshHit = world.CastRayClosest((15f, 2f, 0.25f), (10f, 0f, 0f)); + Assert.True(meshHit.Hit); + Assert.Equal(mesh.Lane, meshHit.Lane); + Assert.Equal(meshStableId, meshHit.StableId); + Assert.InRange(meshHit.Point.X, 18.499f, 18.501f); + Assert.InRange(meshHit.Point.Y, 1.999f, 2.001f); + Assert.InRange(meshHit.Normal.X, -1.001f, -0.999f); + Assert.InRange(meshHit.Normal.Y, -0.001f, 0.001f); + Assert.InRange(meshHit.Normal.Z, -0.001f, 0.001f); + } + + [Fact] + public void Repeated_add_step_remove_and_dispose_cycles_leave_no_crashes_or_stale_handles() + { + var flatHeights = new float[9]; + var (vertices, indices) = BuildBoxPrismMesh(hx: 1f, hy: 1f, hz: 1f); + + for (var worldCycle = 0; worldCycle < 10; worldCycle++) + { + using var world = new Box3DSoaWorld( + capacity: 6, gravityY: -G, + particles: new Box3DSoaParticleCapacities(4, 0, 0, 0, 0, 1)); + // Live particle ensures ymir_soa_gather_proxies walks static heightfield & mesh lanes safely. + world.CreateParticles([new((10f, 5f, 0f), 0.1f, 0.05f)]); + + for (var cycle = 0; cycle < 20; cycle++) + { + var hfId = (ulong)(100 + cycle * 2); + var meshId = (ulong)(101 + cycle * 2); + var hf = world.AddStaticHeightField(hfId, (-1f, 0f, -1f), flatHeights, 3, 3, (1f, 1f, 1f), -1f, 1f); + var mesh = world.AddStaticMesh(meshId, (5f, 1f, 0f), vertices, indices); + var ball = world.AddSphere((ulong)(1000 + cycle), (0f, 0.4f, 0f), 0.5f, density: 1f); + + world.Step(Dt); + Assert.True(world.View.ContactCount[hf] >= 1); + + world.RemoveBody(hf); + world.RemoveBody(mesh); + world.RemoveBody(ball); + Assert.Throws(() => world.RemoveBody(hf)); + Assert.Throws(() => world.RemoveBody(mesh)); + + world.Step(Dt); + Assert.Equal(3, world.Facts.BodiesRemoved.Length); + Assert.Contains(world.Facts.End.ToArray(), e => e.StableIdA == hfId || e.StableIdB == hfId); + } + } + } + + [Fact] + public void Invalid_heightfield_and_mesh_inputs_are_refused_cleanly() + { + using var world = new Box3DSoaWorld(capacity: 2); + var heights = new float[4]; + var (vertices, indices) = BuildBoxPrismMesh(1f, 1f, 1f); + + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 1, 4, (1f, 1f, 1f), -1f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (0f, 1f, 1f), -1f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), 2f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), [0f, float.NaN, 0f, 0f], 2, 2, (1f, 1f, 1f), -1f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), new float[3], 2, 2, (1f, 1f, 1f), -1f, 1f)); + + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), vertices.AsSpan(0, 2), [0, 1, 0])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), vertices, [0, 1, 99])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(float.NaN, 0f, 0f), Vector3.UnitZ], [0, 1, 2])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), vertices, [0, 1])); + + // Valid additions still fit because refusals consumed no slots. + world.AddStaticHeightField(10, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), -1f, 1f); + world.AddStaticMesh(11, (10f, 0f, 0f), vertices, indices); + Assert.Throws(() => + world.AddStaticMesh(12, (20f, 0f, 0f), vertices, indices)); // full + } +}