diff --git a/docs/soa-world.md b/docs/soa-world.md index 4d49d4d..f45bfc5 100644 --- a/docs/soa-world.md +++ b/docs/soa-world.md @@ -7,14 +7,14 @@ 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, never changed by `step`: sphere {radius}, capsule {radius, half_length} along local Y, box and static box - {half_x, half_y, half_z}; unused components 0; shapes are centred on the body origin, so a renderer draws - every body from kind and size), position xyz, rotation quaternion xyzw, linear and angular + {half_x, half_y, half_z}; unused components 0; dynamic and static box shapes are centred on the body origin, whereas + `StaticHeightField` (kind 6, anchored at grid `(0, 0)`) and `StaticMesh` (kind 7, local vertex coordinates) leave `size_0..2 = 0`), position xyz, rotation quaternion xyzw, linear and angular velocity xyz. One contiguous array per component, indexed by body. - Write lanes: per-body world `force` (at the centre of mass) and `torque`, xyz, mutable through the view. `step` applies them to the dynamic bodies and clears them, so a lane holds one step's intent. A @@ -265,7 +265,7 @@ Box3D decides every physical outcome; Ymir creates bodies, steps the world and e `rederive_wet`); a fluid particle keeps its material friction. Body-body contact goes through the GameCult Box3D fork's `b3World_SetContactFrictionCallback`: `b3UpdateConvexContact` calls the hook right after the mix (`sqrt(frictionA frictionB)`) with the mean of the manifold points in each body's frame (one point per manifold), both bodies' user data (lane + 1) and the mixed value, and the world's hook returns `wet_mu` on B of `wet_mu` on A of it: it only lowers. The read is race-free (patches change only between steps) and a world with no settled liquid steps byte for - byte as before. Mesh contacts are not hooked (Ymir makes none). The fork runs the hook on a recycled contact too (Box3D skips a recycled contact's update, and with it the friction mix): it mixes again and calls the hook, only when a hook is installed, so friction follows a patch settled or removed under a body at rest. The lookup is culled: `rederive_wet` indexes the live body patches by body then centre x with each body's box and largest radius (`wet_order`, `wet_body_start`, `wet_body_count`, `wet_body_box`), so a point outside the body's box is a constant check and one inside binary-searches the x window; the lowest lane still decides. The fork's own tests: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at the fork's base as well). No ABI change (14). + byte as before. Box3D skips `contactFrictionFcn` for `b3_simMeshContact` (so wet friction does not apply to `StaticHeightField` or `StaticMesh` contacts). The fork runs the hook on a recycled contact too (Box3D skips a recycled contact's update, and with it the friction mix): it mixes again and calls the hook, only when a hook is installed, so friction follows a patch settled or removed under a body at rest. The lookup is culled: `rederive_wet` indexes the live body patches by body then centre x with each body's box and largest radius (`wet_order`, `wet_body_start`, `wet_body_count`, `wet_body_box`), so a point outside the body's box is a constant check and one inside binary-searches the x window; the lowest lane still decides. The fork's own tests: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at the fork's base as well). No ABI change (14). Fluid holds no constraint: `create_distances` and `attach` refuse a fluid particle, so `create_bends` (over distances) can never name one; a thing that holds liquid is cloth around free fluid (a balloon), as in Flex sec. 8. Every `create_particles` and every `destroy_particles` of particles that held no distance derives only the isolated lanes @@ -307,6 +307,8 @@ no allocation across 100 steps with fact reads. `Box3DSoaImpulseTests`: `contact `Box3DSoaCouplingTests` (also the batch file): a 256-attachment sheet attached one by one and as one batch ends with equal lanes, generations and state after 120 steps; a batch with one bad desc (a fluid particle, a removed body, `STATIC` with `ONE_WAY` or `LIMB`), more descs than free lanes, or a derivation past the tether capacity changes no lane; `ONE_WAY` leaves its box at speed 0 with a 0 impulse lane while the particle holds its point; spawn cost lines for 256 attachments and for one and four Fellas. A sphere thrown at 5 m/s with a 48 x 20 g rope from rest keeps x momentum within 0.1% and gains no energy, at 5 and 70 kg; thrown up it reaches the apex momentum allows; 5 kg snapping a taut rope at 6 m/s keeps at most 5% of its energy and 70 kg is still within a tick; a 45 degree pendulum for 12 s gains no energy and loses at most 1.25 times a heavy-particle control, and a hung body keeps its spin about the vertical; removing the body attachment or destroying the rope's particles frees a held 70 kg body in the step after, with no upward impulse; `particle_impulse` equals M dv minus M g dt every tick, hung and thrown; material friction 0.6 holds a rope on a 20 degree slope and friction 0 does not; no particle is farther from a tethered point than its rest path; an attached end stays on its body point; a world whose only body is static still steps the particles (a dropped rope falls g t^2 / 2 within 2%) and rests; and a cost line with 16 ropes x 48 and one 16 x 16 sheet at 4 substeps, one body and forty (printed, not asserted). +`Box3DSoaTerrainTests`: a bowl `StaticHeightField` catching a dropped sphere (sliding into the bowl centre with zero tunneling) and box (resting flat at bowl height), a `StaticMesh` box-prism roof drop and horizontal wall drive without penetration, `CastRayClosest` returning accurate hit point, surface normal, lane, and stable id on both `StaticHeightField` and `StaticMesh`, 10 x 20 repeated add/step/remove/dispose churn cycles with live particles (verifying `BodiesRemoved` and `End` touch facts), and clean refusal without slot consumption on invalid grid/mesh inputs (all-degenerate collinear or repeated-index triangles, out-of-bounds `>= 50000f` / `> 1e5f` vertex coordinates, overflowing `min_height = -2e38f, max_height = +2e38f` or scaled extents `>= 1e5f`, and oversized `count_x * count_z > 64M`, `triangle_count > 16M`, or `vertex_count > 32M`). + ## Not done `Box3DSoaFluidTests`: the refusals (a distance or attachment naming fluid, a viscosity below 0 or not finite; a batch of fluid past the fluid capacity, refused whole); 64 fluid particles created and destroyed a tick on the 20-pin sheet leaving every tether lane byte-equal; an 8 x 8 x 16 column in a box well (max density, mean density, nothing outside); fluid thrown into a free sheet and rope at fluid : solid mass 64 : 20, 1 : 30, 30 : 1 and 100 : 1 (momentum drift, energy on every row); a 343-particle fluid block dropped 15 cm onto a floor of immovable solid particles at 4 substeps (penetration, nothing through the floor's interior bar the one particle over a lattice hole); probe scene 3, the 343-particle pour on a tilted sheet and a sloped rope at 4 substeps, printed as readings with the same block flagged solid as the control, asserting nothing; fluid pushing a free box with the impulse lane equal to its M dv; a 3 r lattice not clumping; XSPH damping a shear field; the kernel reaching a larger solid beyond two contact radii; the pour's six checkpoint hashes (two runs, a one-ulp nudge, eight concurrent worlds). Each bound states its readings and the mutant it separates from. `Fluid_cost_line` prints 512 and 2000 fluid particles on the sheet scene at viscosity 0 and 0.01. Overflow is asserted 0 in the column, the floor and the pour. diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index 9fbc076..dbd614d 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,225 @@ 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 > 64LL * 1024 * 1024 || !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; + } + float height_range = max_height - min_height; + float extent_x = scale_x * (float)(count_x - 1); + float extent_z = scale_z * (float)(count_z - 1); + float scaled_min_y = scale_y * min_height; + float scaled_max_y = scale_y * max_height; + float scaled_range_y = scale_y * height_range; + if (!ymir_soa_finite(height_range) || !ymir_soa_finite(extent_x) || !ymir_soa_finite(extent_z) || + !ymir_soa_finite(scaled_min_y) || !ymir_soa_finite(scaled_max_y) || !ymir_soa_finite(scaled_range_y) || + fabsf(extent_x) >= 1e5f || fabsf(extent_z) >= 1e5f || fabsf(scaled_range_y) >= 1e5f) + { + 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 || + vertex_count > 32 * 1024 * 1024 || triangle_count > 16 * 1024 * 1024 || + !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) + { + float v = vertices_xyz[k]; + if (!ymir_soa_finite(v) || fabsf(v) >= 50000.0f) + { + 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; + } + } + int has_valid_triangle = 0; + for (int32_t t = 0; t < triangle_count; ++t) + { + int32_t i0 = triangle_indices[(size_t)t * 3 + 0]; + int32_t i1 = triangle_indices[(size_t)t * 3 + 1]; + int32_t i2 = triangle_indices[(size_t)t * 3 + 2]; + if (i0 == i1 || i1 == i2 || i2 == i0) + { + continue; + } + const float* p0 = &vertices_xyz[(size_t)i0 * 3]; + const float* p1 = &vertices_xyz[(size_t)i1 * 3]; + const float* p2 = &vertices_xyz[(size_t)i2 * 3]; + float e1x = p1[0] - p0[0]; + float e1y = p1[1] - p0[1]; + float e1z = p1[2] - p0[2]; + float e2x = p2[0] - p0[0]; + float e2y = p2[1] - p0[1]; + float e2z = p2[2] - p0[2]; + float cx = e1y * e2z - e1z * e2y; + float cy = e1z * e2x - e1x * e2z; + float cz = e1x * e2y - e1y * e2x; + float len_sq = cx * cx + cy * cy + cz * cz; + if (ymir_soa_finite(cx) && ymir_soa_finite(cy) && ymir_soa_finite(cz) && + ymir_soa_finite(len_sq) && len_sq > 1e-10f) + { + has_valid_triangle = 1; + break; + } + } + if (!has_valid_triangle) + { + 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 +1573,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 +1848,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..aa31020 --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs @@ -0,0 +1,308 @@ +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 unsafe 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)); + // Height range and scaled-bound float overflow / >= 1e5f limits. + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), -2e38f, 2e38f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1e5f, 1f, 1f), -1f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1e5f), -1f, 1f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1e4f, 1f), -10f, 10f)); + Assert.Throws(() => + world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1e20f, 1f), 1e20f, 1e20f)); + + 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])); + // Degenerate meshes (collinear or repeated-index triangles) and out-of-bounds vertex coordinates must be refused before b3CreateMesh. + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, Vector3.UnitX, new(2f, 0f, 0f)], [0, 1, 2])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, Vector3.UnitX, Vector3.UnitZ], [0, 1, 0, 1, 2, 2])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(1.5e5f, 0f, 0f), Vector3.UnitZ], [0, 1, 2])); + Assert.Throws(() => + world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(50000f, 0f, 0f), Vector3.UnitZ], [0, 1, 2])); + + // Native cap refusals (YMIR_SOA_INVALID_ARGUMENT == 1) without allocating 200+ MB in tests. + var nativeHandle = (nint)typeof(Box3DSoaWorld) + .GetField("_handle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! + .GetValue(world)!; + fixed (float* hPtr = heights) + fixed (Vector3* vPtr = vertices) + fixed (int* iPtr = indices) + { + Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_heightfield( + nativeHandle, 3, 0f, 0f, 0f, hPtr, 8192, 8193, 1f, 1f, 1f, -1f, 1f, 0.6f, 0f, 0, out _)); + Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_mesh( + nativeHandle, 4, 0f, 0f, 0f, (float*)vPtr, vertices.Length, iPtr, 16 * 1024 * 1024 + 1, 0.6f, 0f, 0, out _)); + Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_mesh( + nativeHandle, 5, 0f, 0f, 0f, (float*)vPtr, 32 * 1024 * 1024 + 1, iPtr, 1, 0.6f, 0f, 0, out _)); + } + + // 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 + } +}