diff --git a/native/Ymir.Box3D/CMakeLists.txt b/native/Ymir.Box3D/CMakeLists.txt index 48ff838..84505c6 100644 --- a/native/Ymir.Box3D/CMakeLists.txt +++ b/native/Ymir.Box3D/CMakeLists.txt @@ -11,7 +11,7 @@ set(BOX3D_VALIDATE ON CACHE BOOL "" FORCE) add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d" "${CMAKE_CURRENT_BINARY_DIR}/box3d") -add_library(ymir_box3d SHARED ymir_box3d.c ymir_box3d_soa.c) +add_library(ymir_box3d SHARED ymir_box3d.c ymir_box3d_soa.c ymir_particles.c) target_link_libraries(ymir_box3d PRIVATE box3d::box3d) target_include_directories(ymir_box3d PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d/include") target_compile_features(ymir_box3d PRIVATE c_std_17) @@ -28,3 +28,7 @@ if(MINGW) # MinGW would emit libymir_box3d.dll; the managed side loads ymir_box3d.dll. set_property(TARGET ymir_box3d PROPERTY PREFIX "") endif() + +# The particle solver's bytes must not depend on whether the compiler fuses a multiply and an add. +set_source_files_properties(ymir_particles.c PROPERTIES COMPILE_OPTIONS + "$,/fp:precise,-ffp-contract=off>") diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index 74fe316..b14e1c5 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -14,6 +14,7 @@ #include #include +#include "ymir_particles.h" #include "ymir_world_lock.h" #include @@ -57,7 +58,7 @@ enum YMIR_SOA_JOINT_REMOVED = 4 // a destroyed joint's lane: never accepted by add_joint }; -#define YMIR_SOA_ABI_VERSION 8u +#define YMIR_SOA_ABI_VERSION 9u // A body to create. `size` by kind: sphere {radius}, capsule {radius, half_length} (segment along // local Y), box and static box {half_x, half_y, half_z}. `parent` is the lane index of an earlier body @@ -123,6 +124,14 @@ typedef struct ymir_box3d_soa_view int32_t joint_capacity; uint32_t reserved; uint64_t step_count; + // Particle high-water counts and capacities (all 0 for a world created without particle capacity). + int32_t particle_count; + int32_t particle_capacity; + int32_t chain_count; + int32_t chain_capacity; + int32_t attachment_count; + int32_t attachment_capacity; + uint32_t reserved_particles[2]; // bodies const uint64_t* stable_id; const uint32_t* kind; @@ -183,6 +192,48 @@ typedef struct ymir_box3d_soa_view // Per joint slot: counts the destroys of that slot. A grab's handle is (lane, generation); destroy_joint refuses // a handle whose generation is not the slot's, so a stale release cannot destroy a later grab in a reused slot. const uint32_t* joint_generation; + // The impulse (N s, world) the particle phase delivered to the body over the last step, 0 for a body it did not + // touch. Notification only: Box3D already applied it. + const float* particle_impulse_x; + const float* particle_impulse_y; + const float* particle_impulse_z; + // Particle lanes (read-only; only `step` and the chain and attachment commands change them), indexed by + // particle up to particle_count. A free slot reads chain -1 and every lane 0. link_tension (N) is the load the + // link from this particle to the next carries, mean over the substeps: a sensor, Ymir never splits on it. + const float* particle_x; + const float* particle_y; + const float* particle_z; + const float* particle_vx; + const float* particle_vy; + const float* particle_vz; + const float* particle_radius; + const float* particle_inv_mass; + const float* particle_link_tension; + const int32_t* particle_chain; + // Chain lanes, indexed by chain lane up to chain_count. kind: 0 live, 1 removed (a tombstone keeps its last range). + const uint64_t* chain_stable_id; + const uint32_t* chain_kind; + const uint32_t* chain_generation; + const int32_t* chain_first; + const int32_t* chain_size; + const uint64_t* chain_removed_at; + const uint64_t* chain_material_id; + const float* chain_stretch_compliance; + const float* chain_bend_compliance; + const float* chain_friction; + // Attachment lanes, indexed by attachment lane up to attachment_count. force (N) is what the attachment exerts on + // the chain, mean over the substeps, tether load included: a sensor. + const uint32_t* attachment_kind; + const uint32_t* attachment_generation; + const int32_t* attachment_particle; + const int32_t* attachment_body; + const float* attachment_point_x; + const float* attachment_point_y; + const float* attachment_point_z; + const float* attachment_compliance; + const float* attachment_force_x; + const float* attachment_force_y; + const float* attachment_force_z; } ymir_box3d_soa_view; // A begin or end of touch between two bodies: their lane indices and the shapes' stable ids. @@ -245,7 +296,8 @@ typedef struct ymir_box3d_soa_ray_hit #define YMIR_SOA_STATE_LANES 13 #define YMIR_SOA_WRITE_LANES 6 #define YMIR_SOA_CONTACT_IMPULSE_LANE (YMIR_SOA_STATE_LANES + YMIR_SOA_WRITE_LANES) -#define YMIR_SOA_BODY_FLOAT_LANES (YMIR_SOA_CONTACT_IMPULSE_LANE + 1) +#define YMIR_SOA_PARTICLE_IMPULSE_LANE (YMIR_SOA_CONTACT_IMPULSE_LANE + 1) // 3 lanes: x y z +#define YMIR_SOA_BODY_FLOAT_LANES (YMIR_SOA_PARTICLE_IMPULSE_LANE + 3) #define YMIR_SOA_JOINT_FLOAT_LANES 15 typedef struct ymir_box3d_soa_world @@ -281,6 +333,8 @@ typedef struct ymir_box3d_soa_world ymir_box3d_soa_touch_fact* end_facts; ymir_box3d_soa_hit_fact* hit_facts; b3ContactData* contact_scratch; // `capacity` entries: a body has one shape, so at most capacity - 1 contacts + b3Vec3 gravity; + ymir_particles* particles; // NULL when created without particle capacity: the step then runs exactly as ABI 8 } ymir_box3d_soa_world; static float* ymir_soa_lane(const ymir_box3d_soa_world* world, int lane) @@ -434,12 +488,14 @@ static void ymir_soa_free(ymir_box3d_soa_world* world) free(world->end_facts); free(world->hit_facts); free(world->contact_scratch); + ymir_particles_free(world->particles); free(world); } YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( int32_t capacity, int32_t joint_capacity, float gravity_x, float gravity_y, float gravity_z, - int32_t fact_capacity, float hit_threshold, ymir_box3d_soa_world** output) + int32_t fact_capacity, float hit_threshold, int32_t particle_capacity, int32_t chain_capacity, + int32_t attachment_capacity, ymir_box3d_soa_world** output) { if (output == NULL) { @@ -448,7 +504,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( *output = NULL; if (capacity <= 0 || joint_capacity < 0 || fact_capacity <= 0 || !ymir_soa_finite(gravity_x) || !ymir_soa_finite(gravity_y) || !ymir_soa_finite(gravity_z) || !ymir_soa_finite(hit_threshold) || - hit_threshold < 0.0f) + hit_threshold < 0.0f || particle_capacity < 0 || chain_capacity < 0 || attachment_capacity < 0) { return YMIR_SOA_INVALID_ARGUMENT; } @@ -486,6 +542,16 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( world->end_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact)); world->hit_facts = (ymir_box3d_soa_hit_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_hit_fact)); world->contact_scratch = (b3ContactData*)calloc(n, sizeof(b3ContactData)); + world->gravity = (b3Vec3){gravity_x, gravity_y, gravity_z}; + if (particle_capacity > 0 || chain_capacity > 0 || attachment_capacity > 0) + { + world->particles = ymir_particles_create(particle_capacity, chain_capacity, attachment_capacity, capacity); + if (world->particles == NULL) + { + ymir_soa_free(world); + return YMIR_SOA_OUT_OF_MEMORY; + } + } if (world->contact_count == NULL || world->material_id == NULL || world->begin_facts == NULL || world->end_facts == NULL || world->hit_facts == NULL || world->contact_scratch == NULL || world->bodies == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL || @@ -995,6 +1061,74 @@ static void ymir_soa_collect_contact_lanes(ymir_box3d_soa_world* world) } } +// The particle phase's view of the bodies, after Box3D's step: pose, velocity, shape and the real inverse mass and +// world inverse inertia of each dynamic body (0 for static, kinematic and anchor bodies). Every shape is centred on +// the body origin, so the origin is the centre of mass. +static void ymir_soa_gather_proxies(ymir_box3d_soa_world* world) +{ + ymir_particles* pt = world->particles; + pt->body_count = world->count; + for (int i = 0; i < world->count; ++i) + { + ymir_particle_proxy* b = pt->proxies + i; + uint32_t kind = world->kind[i]; + b3BodyId body = world->bodies[i]; + b3Pos p = b3Body_GetPosition(body); + b3Quat q = b3Body_GetRotation(body); + 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; + for (int k = 0; k < 3; ++k) + { + b->size[k] = world->size[(size_t)k * (size_t)world->capacity + (size_t)i]; + } + b->position[0] = p.x; b->position[1] = p.y; b->position[2] = p.z; + b->rotation[0] = q.v.x; b->rotation[1] = q.v.y; b->rotation[2] = q.v.z; b->rotation[3] = q.s; + b->velocity[0] = v.x; b->velocity[1] = v.y; b->velocity[2] = v.z; + b->angular_velocity[0] = w.x; b->angular_velocity[1] = w.y; b->angular_velocity[2] = w.z; + if (ymir_soa_is_dynamic(kind)) + { + b3Matrix3 m = b3Body_GetWorldInverseRotationalInertia(body); + b->inv_mass = 1.0f / b3Body_GetMass(body); + b->inv_inertia[0] = m.cx.x; b->inv_inertia[1] = m.cy.x; b->inv_inertia[2] = m.cz.x; + b->inv_inertia[3] = m.cy.y; b->inv_inertia[4] = m.cz.y; b->inv_inertia[5] = m.cz.z; + } + } +} + +// What the particle phase delivered to each dynamic body, as the impulse Box3D applies now (a velocity change, never +// a teleport) and the lane a consumer reads. +static void ymir_soa_apply_particle_impulses(ymir_box3d_soa_world* world) +{ + const ymir_particles* pt = world->particles; + for (int i = 0; i < world->count; ++i) + { + const ymir_particle_proxy* b = pt->proxies + i; + for (int k = 0; k < 3; ++k) + { + ymir_soa_lane(world, YMIR_SOA_PARTICLE_IMPULSE_LANE + k)[i] = b->impulse[k]; + } + if (!ymir_soa_is_dynamic(world->kind[i])) + { + continue; + } + b3Vec3 linear = {b->impulse[0], b->impulse[1], b->impulse[2]}; + b3Vec3 angular = {b->angular_impulse[0], b->angular_impulse[1], b->angular_impulse[2]}; + if (linear.x != 0.0f || linear.y != 0.0f || linear.z != 0.0f) + { + b3Body_ApplyLinearImpulseToCenter(world->bodies[i], linear, true); + } + if (angular.x != 0.0f || angular.y != 0.0f || angular.z != 0.0f) + { + b3Body_ApplyAngularImpulse(world->bodies[i], angular, true); + } + } +} + YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_step(ymir_box3d_soa_world* world, float time_step, int32_t sub_step_count) { if (world == NULL || !ymir_soa_finite(time_step) || time_step <= 0.0f || sub_step_count <= 0) @@ -1017,6 +1151,14 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_step(ymir_box3d_soa_world* world, f b3Body_SetAngularVelocity(world->bodies[i], b3Vec3_zero); } } + if (world->particles != NULL) + { + // Box3D has stepped: the particles now move against the bodies' new poses and hand back what they pushed. + ymir_soa_gather_proxies(world); + ymir_particles_step( + world->particles, time_step, sub_step_count, world->gravity.x, world->gravity.y, world->gravity.z); + ymir_soa_apply_particle_impulses(world); + } ymir_soa_collect_facts(world); ymir_soa_collect_contact_lanes(world); for (int i = 0; i < world->count; ++i) @@ -1114,6 +1256,86 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_cast_ray_closest( return YMIR_SOA_OK; } +// Particle chains and attachments. Each command is the whole of its effect: Ymir never splits, destroys or detaches +// on a threshold, so tear, cut, gib and release are the caller's say-so. Every refusal changes nothing. A world made +// without particle capacity refuses them all. + +YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_chain_desc_size(void) +{ + return (uint32_t)sizeof(ymir_chain_desc); +} + +YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_attachment_desc_size(void) +{ + return (uint32_t)sizeof(ymir_attachment_desc); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_chain( + ymir_box3d_soa_world* world, const ymir_chain_desc* d, int32_t* chain, uint32_t* generation) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_create_chain(world->particles, d, world->step_count, chain, generation); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_split_chain( + ymir_box3d_soa_world* world, int32_t chain, uint32_t generation, int32_t link, uint64_t tail_stable_id, int32_t* tail, + uint32_t* tail_generation) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_split_chain( + world->particles, chain, generation, link, tail_stable_id, world->step_count, tail, tail_generation); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_chain(ymir_box3d_soa_world* world, int32_t chain, uint32_t generation) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_destroy_chain(world->particles, chain, generation, world->step_count); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_attach( + ymir_box3d_soa_world* world, const ymir_attachment_desc* d, int32_t* attachment, uint32_t* generation) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_attach(world->particles, d, world->count, world->step_count, attachment, generation); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_detach(ymir_box3d_soa_world* world, int32_t attachment, uint32_t generation) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_detach(world->particles, attachment, generation, world->step_count); +} + +// The largest run of particle slots a new chain could take right now. +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_particle_slots(const ymir_box3d_soa_world* world) +{ + return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_particle_slots(world->particles, world->step_count); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_chain_slots(const ymir_box3d_soa_world* world) +{ + return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_chain_slots(world->particles, world->step_count); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_attachment_slots(const ymir_box3d_soa_world* world) +{ + return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_attachment_slots(world->particles, world->step_count); +} + YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world* world, ymir_box3d_soa_view* view) { if (world == NULL || view == NULL) @@ -1124,13 +1346,20 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world size_t n = (size_t)world->capacity; float* jb = world->joint_lanes; size_t m = (size_t)world->joint_capacity; - *view = (ymir_box3d_soa_view){ + const ymir_particles* pt = world->particles; + *view =(ymir_box3d_soa_view){ .abi_version = YMIR_SOA_ABI_VERSION, .count = world->count, .capacity = world->capacity, .joint_count = world->joint_count, .joint_capacity = world->joint_capacity, .step_count = world->step_count, + .particle_count = pt != NULL ? pt->particle_count : 0, + .particle_capacity = pt != NULL ? pt->particle_capacity : 0, + .chain_count = pt != NULL ? pt->chain_count : 0, + .chain_capacity = pt != NULL ? pt->chain_capacity : 0, + .attachment_count = pt != NULL ? pt->attachment_count : 0, + .attachment_capacity = pt != NULL ? pt->attachment_capacity : 0, .stable_id = world->stable_id, .kind = world->kind, .parent = world->parent, @@ -1179,7 +1408,44 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world .contact_count = world->contact_count, .material_id = world->material_id, .joint_generation = world->joint_generation, + .particle_impulse_x = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 0) * n, + .particle_impulse_y = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 1) * n, + .particle_impulse_z = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 2) * n, }; + if (pt != NULL) + { + view->particle_x = pt->pos_x; + view->particle_y = pt->pos_y; + view->particle_z = pt->pos_z; + view->particle_vx = pt->vel_x; + view->particle_vy = pt->vel_y; + view->particle_vz = pt->vel_z; + view->particle_radius = pt->radius; + view->particle_inv_mass = pt->inv_mass; + view->particle_link_tension = pt->link_tension; + view->particle_chain = pt->chain; + view->chain_stable_id = pt->chain_stable_id; + view->chain_kind = pt->chain_kind; + view->chain_generation = pt->chain_generation; + view->chain_first = pt->chain_first; + view->chain_size = pt->chain_size; + view->chain_removed_at = pt->chain_removed_at; + view->chain_material_id = pt->chain_material_id; + view->chain_stretch_compliance = pt->chain_stretch; + view->chain_bend_compliance = pt->chain_bend; + view->chain_friction = pt->chain_friction; + view->attachment_kind = pt->att_kind; + view->attachment_generation = pt->att_generation; + view->attachment_particle = pt->att_particle; + view->attachment_body = pt->att_body; + view->attachment_point_x = pt->att_point_x; + view->attachment_point_y = pt->att_point_y; + view->attachment_point_z = pt->att_point_z; + view->attachment_compliance = pt->att_compliance; + view->attachment_force_x = pt->att_force_x; + view->attachment_force_y = pt->att_force_y; + view->attachment_force_z = pt->att_force_z; + } return YMIR_SOA_OK; } diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c new file mode 100644 index 0000000..d1d1871 --- /dev/null +++ b/native/Ymir.Box3D/ymir_particles.c @@ -0,0 +1,1150 @@ +// Particle chains: XPBD with small steps (Macklin 2019), long-range tethers (Kim 2012) and two-way coupling +// to rigid bodies through proxies with real mass (Mueller 2007, Detailed Rigid XPBD 2020). The file calls no +// Box3D and spawns nothing: one thread, every sum in a fixed order. See ymir_particles.h. + +#include "ymir_particles.h" + +#include +#include +#include + +typedef struct v3 +{ + float x, y, z; +} v3; + +static v3 vadd(v3 a, v3 b) { return (v3){a.x + b.x, a.y + b.y, a.z + b.z}; } +static v3 vsub(v3 a, v3 b) { return (v3){a.x - b.x, a.y - b.y, a.z - b.z}; } +static v3 vmul(v3 a, float s) { return (v3){a.x * s, a.y * s, a.z * s}; } +static float vdot(v3 a, v3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +static v3 vcross(v3 a, v3 b) { return (v3){a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } +static float vlen(v3 a) { return sqrtf(vdot(a, a)); } +static float vmin(float a, float b) { return a < b ? a : b; } +static float vmax(float a, float b) { return a > b ? a : b; } +static float vclamp(float a, float lo, float hi) { return a < lo ? lo : a > hi ? hi : a; } + +static v3 qrot(const float* q, v3 v) +{ + v3 u = {q[0], q[1], q[2]}; + v3 t = vmul(vcross(u, v), 2.0f); + return vadd(vadd(v, vmul(t, q[3])), vcross(u, t)); +} + +static v3 qrot_inv(const float* q, v3 v) +{ + float c[4] = {-q[0], -q[1], -q[2], q[3]}; + return qrot(c, v); +} + +static v3 mat_mul(const float* m, v3 v) // symmetric xx xy xz yy yz zz +{ + return (v3){m[0] * v.x + m[1] * v.y + m[2] * v.z, m[1] * v.x + m[3] * v.y + m[4] * v.z, m[2] * v.x + m[4] * v.y + m[5] * v.z}; +} + +static int finite3(const float* v) +{ + return isfinite(v[0]) && isfinite(v[1]) && isfinite(v[2]); +} + +static v3 P(const ymir_particles* p, const float* x, const float* y, const float* z, int i) +{ + (void)p; + return (v3){x[i], y[i], z[i]}; +} + +static void put(float* x, float* y, float* z, int i, v3 v) +{ + x[i] = v.x; + y[i] = v.y; + z[i] = v.z; +} + +// ---- memory: one block, laid out once at create ------------------------------------------------------------- + +static size_t layout(ymir_particles* p, unsigned char* base) +{ + size_t off = 0; + int64_t np = p->particle_capacity, nc = p->chain_capacity, na = p->attachment_capacity, nb = p->body_capacity; + size_t table = (size_t)p->table_mask + 1; +#define CARVE(field, type, count) \ + do \ + { \ + off = (off + 15u) & ~(size_t)15u; \ + if (base != NULL) \ + p->field = (type*)(base + off); \ + off += sizeof(type) * (size_t)(count); \ + } while (0) + CARVE(proxies, ymir_particle_proxy, nb); + CARVE(pos_x, float, np); CARVE(pos_y, float, np); CARVE(pos_z, float, np); + CARVE(vel_x, float, np); CARVE(vel_y, float, np); CARVE(vel_z, float, np); + CARVE(radius, float, np); CARVE(inv_mass, float, np); CARVE(link_tension, float, np); + CARVE(chain, int32_t, np); + CARVE(chain_stable_id, uint64_t, nc); CARVE(chain_kind, uint32_t, nc); CARVE(chain_generation, uint32_t, nc); + CARVE(chain_first, int32_t, nc); CARVE(chain_size, int32_t, nc); CARVE(chain_removed_at, uint64_t, nc); + CARVE(chain_material_id, uint64_t, nc); + CARVE(chain_stretch, float, nc); CARVE(chain_bend, float, nc); CARVE(chain_friction, float, nc); + CARVE(att_kind, uint32_t, na); CARVE(att_generation, uint32_t, na); CARVE(att_particle, int32_t, na); + CARVE(att_body, int32_t, na); + CARVE(att_point_x, float, na); CARVE(att_point_y, float, na); CARVE(att_point_z, float, na); + CARVE(att_compliance, float, na); + CARVE(att_force_x, float, na); CARVE(att_force_y, float, na); CARVE(att_force_z, float, na); + CARVE(att_removed_at, uint64_t, na); + CARVE(pp_x, float, np); CARVE(pp_y, float, np); CARVE(pp_z, float, np); + CARVE(dp_x, float, np); CARVE(dp_y, float, np); CARVE(dp_z, float, np); + CARVE(rest_link, float, np); CARVE(rest_bend, float, np); CARVE(rest_pos, float, np); + CARVE(tension_acc, float, np); CARVE(tension_diff, float, np + 1); + CARVE(skip_body, int32_t, np); CARVE(cell_x, int32_t, np); CARVE(cell_y, int32_t, np); CARVE(cell_z, int32_t, np); + CARVE(cell_start, int32_t, table + 1); CARVE(cell_fill, int32_t, table); CARVE(sorted, int32_t, np); + CARVE(mark, uint8_t, np); +#undef CARVE + return off + 16; +} + +ymir_particles* ymir_particles_create(int32_t particle_capacity, int32_t chain_capacity, int32_t attachment_capacity, int32_t body_capacity) +{ + if (particle_capacity < 0 || chain_capacity < 0 || attachment_capacity < 0 || body_capacity < 0) + { + return NULL; + } + ymir_particles* p = (ymir_particles*)calloc(1, sizeof(ymir_particles)); + if (p == NULL) + { + return NULL; + } + p->particle_capacity = particle_capacity; + p->chain_capacity = chain_capacity; + p->attachment_capacity = attachment_capacity; + p->body_capacity = body_capacity; + uint32_t table = 16; + while (table < 2u * (uint32_t)particle_capacity) + { + table <<= 1; + } + p->table_mask = table - 1; + size_t bytes = layout(p, NULL); + p->arena = calloc(1, bytes); + if (p->arena == NULL) + { + free(p); + return NULL; + } + layout(p, (unsigned char*)p->arena); + for (int32_t i = 0; i < particle_capacity; ++i) + { + p->chain[i] = -1; + } + return p; +} + +void ymir_particles_free(ymir_particles* p) +{ + if (p != NULL) + { + free(p->arena); + free(p); + } +} + +// ---- slots --------------------------------------------------------------------------------------------------- + +static int lane_reusable(uint64_t step_count, uint64_t removed_at) +{ + return step_count > removed_at; +} + +// Marks the particle slots a new chain may not take: occupied ones, and the range of a chain destroyed in this +// very step (its lanes were read this step and stay meaningful until a step has passed). +static void mark_slots(const ymir_particles* p, uint64_t step_count) +{ + for (int32_t i = 0; i < p->particle_capacity; ++i) + { + p->mark[i] = (uint8_t)(i < p->particle_count && p->chain[i] >= 0); + } + for (int32_t c = 0; c < p->chain_count; ++c) + { + if (p->chain_kind[c] == YMIR_CHAIN_REMOVED && !lane_reusable(step_count, p->chain_removed_at[c])) + { + for (int32_t i = p->chain_first[c]; i < p->chain_first[c] + p->chain_size[c]; ++i) + { + p->mark[i] = 1; + } + } + } +} + +// First fit, lowest index. Returns -1 when no run of `n` slots is free. +static int32_t find_range(const ymir_particles* p, int32_t n, uint64_t step_count) +{ + mark_slots(p, step_count); + int32_t run = 0; + for (int32_t i = 0; i < p->particle_capacity; ++i) + { + run = p->mark[i] ? 0 : run + 1; + if (run == n) + { + return i - n + 1; + } + } + return -1; +} + +int32_t ymir_particles_free_particle_slots(const ymir_particles* p, uint64_t step_count) +{ + mark_slots(p, step_count); + int32_t best = 0, run = 0; + for (int32_t i = 0; i < p->particle_capacity; ++i) + { + run = p->mark[i] ? 0 : run + 1; + best = run > best ? run : best; + } + return best; +} + +static int32_t chain_slot(const ymir_particles* p, uint64_t step_count) +{ + for (int32_t c = 0; c < p->chain_count; ++c) + { + if (p->chain_kind[c] == YMIR_CHAIN_REMOVED && lane_reusable(step_count, p->chain_removed_at[c])) + { + return c; + } + } + return p->chain_count < p->chain_capacity ? p->chain_count : -1; +} + +int32_t ymir_particles_free_chain_slots(const ymir_particles* p, uint64_t step_count) +{ + int32_t free_slots = p->chain_capacity - p->chain_count; + for (int32_t c = 0; c < p->chain_count; ++c) + { + free_slots += p->chain_kind[c] == YMIR_CHAIN_REMOVED && lane_reusable(step_count, p->chain_removed_at[c]); + } + return free_slots; +} + +static int32_t attachment_slot(const ymir_particles* p, uint64_t step_count) +{ + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (p->att_kind[a] == YMIR_ATTACH_REMOVED && lane_reusable(step_count, p->att_removed_at[a])) + { + return a; + } + } + return p->attachment_count < p->attachment_capacity ? p->attachment_count : -1; +} + +int32_t ymir_particles_free_attachment_slots(const ymir_particles* p, uint64_t step_count) +{ + int32_t free_slots = p->attachment_capacity - p->attachment_count; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + free_slots += p->att_kind[a] == YMIR_ATTACH_REMOVED && lane_reusable(step_count, p->att_removed_at[a]); + } + return free_slots; +} + +static int chain_live(const ymir_particles* p, int32_t chain, uint32_t generation) +{ + return chain >= 0 && chain < p->chain_count && p->chain_kind[chain] == YMIR_CHAIN_LIVE && p->chain_generation[chain] == generation; +} + +static int stable_id_taken(const ymir_particles* p, uint64_t id) +{ + for (int32_t c = 0; c < p->chain_count; ++c) + { + if (p->chain_kind[c] == YMIR_CHAIN_LIVE && p->chain_stable_id[c] == id) + { + return 1; + } + } + return 0; +} + +// ---- commands ------------------------------------------------------------------------------------------------ + +int32_t ymir_particles_create_chain(ymir_particles* p, const ymir_chain_desc* d, uint64_t step_count, int32_t* chain, uint32_t* generation) +{ + if (p == NULL || d == NULL || d->positions == NULL || d->masses == NULL || d->count < 2 || !isfinite(d->radius) || + d->radius <= 0.0f || !isfinite(d->stretch_compliance) || d->stretch_compliance < 0.0f || + !isfinite(d->bend_compliance) || d->bend_compliance < 0.0f || !isfinite(d->friction) || d->friction < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + for (int32_t i = 0; i < d->count; ++i) + { + if (!finite3(d->positions + 3 * i) || !isfinite(d->masses[i]) || d->masses[i] < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + if (i + 1 < d->count) + { + v3 a = {d->positions[3 * i], d->positions[3 * i + 1], d->positions[3 * i + 2]}; + v3 b = {d->positions[3 * i + 3], d->positions[3 * i + 4], d->positions[3 * i + 5]}; + if (!(vlen(vsub(b, a)) > 1e-6f)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; // a link of no length has no direction + } + } + } + if (stable_id_taken(p, d->stable_id)) + { + return YMIR_PARTICLES_DUPLICATE_ID; + } + int32_t lane = chain_slot(p, step_count); + int32_t first = find_range(p, d->count, step_count); + if (lane < 0 || first < 0) + { + return YMIR_PARTICLES_FULL; + } + + if (lane == p->chain_count) + { + p->chain_count++; + } + p->live_chains++; + p->chain_kind[lane] = YMIR_CHAIN_LIVE; + p->chain_stable_id[lane] = d->stable_id; + p->chain_first[lane] = first; + p->chain_size[lane] = d->count; + p->chain_removed_at[lane] = 0; + p->chain_material_id[lane] = d->material_id; + p->chain_stretch[lane] = d->stretch_compliance; + p->chain_bend[lane] = d->bend_compliance; + p->chain_friction[lane] = d->friction; + if (first + d->count > p->particle_count) + { + p->particle_count = first + d->count; + } + float path = 0.0f; + for (int32_t k = 0; k < d->count; ++k) + { + int32_t i = first + k; + v3 x = {d->positions[3 * k], d->positions[3 * k + 1], d->positions[3 * k + 2]}; + put(p->pos_x, p->pos_y, p->pos_z, i, x); + p->vel_x[i] = p->vel_y[i] = p->vel_z[i] = 0.0f; + p->radius[i] = d->radius; + p->inv_mass[i] = d->masses[k] > 0.0f ? 1.0f / d->masses[k] : 0.0f; + p->link_tension[i] = 0.0f; + p->chain[i] = lane; + p->rest_pos[i] = path; + p->rest_link[i] = 0.0f; + p->rest_bend[i] = 0.0f; + if (k + 1 < d->count) + { + v3 y = {d->positions[3 * k + 3], d->positions[3 * k + 4], d->positions[3 * k + 5]}; + p->rest_link[i] = vlen(vsub(y, x)); + path += p->rest_link[i]; + } + if (k + 2 < d->count) + { + v3 z = {d->positions[3 * k + 6], d->positions[3 * k + 7], d->positions[3 * k + 8]}; + p->rest_bend[i] = vlen(vsub(z, x)); + } + } + if (chain != NULL) + { + *chain = lane; + } + if (generation != NULL) + { + *generation = p->chain_generation[lane]; + } + return YMIR_PARTICLES_OK; +} + +// Cuts the link between particles `link` and `link + 1`. The head keeps its lane and stable id; the tail takes a +// new chain lane and `tail_stable_id`. No particle moves lane or address, and attachments stay where they are. +int32_t ymir_particles_split_chain( + ymir_particles* p, int32_t chain, uint32_t generation, int32_t link, uint64_t tail_stable_id, uint64_t step_count, + int32_t* tail, uint32_t* tail_generation) +{ + if (p == NULL || !chain_live(p, chain, generation) || link < 0 || link + 2 > p->chain_size[chain]) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + if (stable_id_taken(p, tail_stable_id)) + { + return YMIR_PARTICLES_DUPLICATE_ID; + } + int32_t lane = chain_slot(p, step_count); + if (lane < 0) + { + return YMIR_PARTICLES_FULL; + } + if (lane == p->chain_count) + { + p->chain_count++; + } + p->live_chains++; + int32_t first = p->chain_first[chain], size = p->chain_size[chain]; + int32_t tail_first = first + link + 1; + p->chain_kind[lane] = YMIR_CHAIN_LIVE; + p->chain_stable_id[lane] = tail_stable_id; + p->chain_first[lane] = tail_first; + p->chain_size[lane] = size - link - 1; + p->chain_removed_at[lane] = 0; + p->chain_material_id[lane] = p->chain_material_id[chain]; + p->chain_stretch[lane] = p->chain_stretch[chain]; + p->chain_bend[lane] = p->chain_bend[chain]; + p->chain_friction[lane] = p->chain_friction[chain]; + p->chain_size[chain] = link + 1; + for (int32_t i = tail_first; i < first + size; ++i) + { + p->chain[i] = lane; + } + p->link_tension[tail_first - 1] = 0.0f; // the cut link carries nothing + if (tail != NULL) + { + *tail = lane; + } + if (tail_generation != NULL) + { + *tail_generation = p->chain_generation[lane]; + } + return YMIR_PARTICLES_OK; +} + +static void tombstone_attachment(ymir_particles* p, int32_t a, uint64_t step_count) +{ + p->att_kind[a] = YMIR_ATTACH_REMOVED; + p->att_removed_at[a] = step_count; + p->att_generation[a] += 1; + p->att_particle[a] = -1; + p->att_body[a] = -1; + p->att_point_x[a] = p->att_point_y[a] = p->att_point_z[a] = 0.0f; + p->att_compliance[a] = 0.0f; + p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f; +} + +// Removes the chain and, with it, every attachment that reaches one of its particles: they would dangle. A +// consequence of the command, not a decision of the solver. Particle lanes read 0 until the range is reused. +int32_t ymir_particles_destroy_chain(ymir_particles* p, int32_t chain, uint32_t generation, uint64_t step_count) +{ + if (p == NULL || !chain_live(p, chain, generation)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + int32_t lo = p->chain_first[chain], hi = lo + p->chain_size[chain]; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (p->att_kind[a] == YMIR_ATTACH_REMOVED) + { + continue; + } + int32_t q = p->att_particle[a]; + int32_t other = p->att_kind[a] == YMIR_ATTACH_PARTICLE_PARTICLE ? p->att_body[a] : -1; + if ((q >= lo && q < hi) || (other >= lo && other < hi)) + { + tombstone_attachment(p, a, step_count); + } + } + for (int32_t i = lo; i < hi; ++i) + { + p->pos_x[i] = p->pos_y[i] = p->pos_z[i] = 0.0f; + p->vel_x[i] = p->vel_y[i] = p->vel_z[i] = 0.0f; + p->radius[i] = p->inv_mass[i] = p->link_tension[i] = 0.0f; + p->rest_link[i] = p->rest_bend[i] = p->rest_pos[i] = 0.0f; + p->chain[i] = -1; + } + p->chain_kind[chain] = YMIR_CHAIN_REMOVED; // first and size stay: the range is held until a step has passed + p->chain_stable_id[chain] = 0; + p->chain_removed_at[chain] = step_count; + p->chain_generation[chain] += 1; + p->chain_material_id[chain] = 0; + p->chain_stretch[chain] = p->chain_bend[chain] = p->chain_friction[chain] = 0.0f; + p->live_chains--; + return YMIR_PARTICLES_OK; +} + +int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, int32_t* attachment, uint32_t* generation) +{ + if (p == NULL || d == NULL || d->kind > YMIR_ATTACH_PARTICLE_PARTICLE || d->particle < 0 || d->particle >= p->particle_count || + p->chain[d->particle] < 0 || !finite3(d->point) || !isfinite(d->compliance) || d->compliance < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + if (d->kind == YMIR_ATTACH_PARTICLE_BODY && (d->body < 0 || d->body >= body_count)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + if (d->kind == YMIR_ATTACH_PARTICLE_PARTICLE && + (d->body < 0 || d->body >= p->particle_count || d->body == d->particle || p->chain[d->body] < 0)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + int32_t a = attachment_slot(p, step_count); + if (a < 0) + { + return YMIR_PARTICLES_FULL; + } + if (a == p->attachment_count) + { + p->attachment_count++; + } + p->att_kind[a] = d->kind; + p->att_particle[a] = d->particle; + p->att_body[a] = d->kind == YMIR_ATTACH_PARTICLE_STATIC ? -1 : d->body; + p->att_point_x[a] = d->point[0]; + p->att_point_y[a] = d->point[1]; + p->att_point_z[a] = d->point[2]; + p->att_compliance[a] = d->compliance; + p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f; + if (attachment != NULL) + { + *attachment = a; + } + if (generation != NULL) + { + *generation = p->att_generation[a]; + } + return YMIR_PARTICLES_OK; +} + +int32_t ymir_particles_detach(ymir_particles* p, int32_t attachment, uint32_t generation, uint64_t step_count) +{ + if (p == NULL || attachment < 0 || attachment >= p->attachment_count || p->att_kind[attachment] == YMIR_ATTACH_REMOVED || + p->att_generation[attachment] != generation) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + tombstone_attachment(p, attachment, step_count); + return YMIR_PARTICLES_OK; +} + +// ---- the particle phase -------------------------------------------------------------------------------------- + +typedef struct phase +{ + ymir_particles* p; + float dt, h, inv_dt; + float k_particle; // force of a correction made once per substep: lambda / h^2 + float k_body; // force of a correction that moves a body once per tick: summed over the substeps / dt^2 +} phase; + +// Generalised inverse mass of a proxy along unit `n` at world point `at`. +static float proxy_w(const ymir_particle_proxy* b, v3 at, v3 n) +{ + if (b->inv_mass == 0.0f) + { + return 0.0f; + } + v3 r = vsub(at, (v3){b->position[0], b->position[1], b->position[2]}); + v3 rn = vcross(r, n); + return b->inv_mass + vdot(rn, mat_mul(b->inv_inertia, rn)); +} + +// Applies a position-level impulse `imp` (kg m) at `at` to a proxy: moves its pose and books the velocity-level +// impulse (imp / dt) the tick will hand back to Box3D. +static void proxy_push(const phase* f, ymir_particle_proxy* b, v3 at, v3 imp) +{ + if (b->inv_mass == 0.0f) + { + return; + } + v3 r = vsub(at, (v3){b->position[0], b->position[1], b->position[2]}); + v3 torque = vcross(r, imp); + v3 dtheta = mat_mul(b->inv_inertia, torque); + b->position[0] += imp.x * b->inv_mass; + b->position[1] += imp.y * b->inv_mass; + b->position[2] += imp.z * b->inv_mass; + float* q = b->rotation; + float dq[4] = { + 0.5f * (dtheta.x * q[3] + dtheta.y * q[2] - dtheta.z * q[1]), + 0.5f * (dtheta.y * q[3] + dtheta.z * q[0] - dtheta.x * q[2]), + 0.5f * (dtheta.z * q[3] + dtheta.x * q[1] - dtheta.y * q[0]), + 0.5f * (-dtheta.x * q[0] - dtheta.y * q[1] - dtheta.z * q[2])}; + float n2 = 0.0f; + for (int k = 0; k < 4; ++k) + { + q[k] += dq[k]; + n2 += q[k] * q[k]; + } + float inv = 1.0f / sqrtf(n2); + for (int k = 0; k < 4; ++k) + { + q[k] *= inv; + } + b->impulse[0] += imp.x * f->inv_dt; + b->impulse[1] += imp.y * f->inv_dt; + b->impulse[2] += imp.z * f->inv_dt; + b->angular_impulse[0] += torque.x * f->inv_dt; + b->angular_impulse[1] += torque.y * f->inv_dt; + b->angular_impulse[2] += torque.z * f->inv_dt; +} + +// The world point an attachment holds, and the inverse mass of what it holds it to along `n`. +static v3 end_point(const ymir_particles* p, int32_t a) +{ + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY) + { + const ymir_particle_proxy* b = p->proxies + p->att_body[a]; + v3 local = {p->att_point_x[a], p->att_point_y[a], p->att_point_z[a]}; + return vadd((v3){b->position[0], b->position[1], b->position[2]}, qrot(b->rotation, local)); + } + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_PARTICLE) + { + return P(p, p->pp_x, p->pp_y, p->pp_z, p->att_body[a]); + } + return (v3){p->att_point_x[a], p->att_point_y[a], p->att_point_z[a]}; +} + +static float end_w(const ymir_particles* p, int32_t a, v3 at, v3 n) +{ + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY) + { + return proxy_w(p->proxies + p->att_body[a], at, n); + } + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_PARTICLE) + { + return p->inv_mass[p->att_body[a]]; + } + return 0.0f; +} + +static void end_push(const phase* f, int32_t a, v3 at, v3 imp) +{ + ymir_particles* p = f->p; + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY) + { + proxy_push(f, p->proxies + p->att_body[a], at, imp); + } + else if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_PARTICLE) + { + int32_t q = p->att_body[a]; + put(p->pp_x, p->pp_y, p->pp_z, q, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, q), vmul(imp, p->inv_mass[q]))); + } +} + +// A correction that moves a dynamic body happens once per tick, not once per substep, so its force is the sum +// of the substeps' lambdas over dt^2; every other correction is lambda / h^2 each substep. Both are written as +// per-substep terms that the step averages. +static float end_force_scale(const phase* f, int32_t a) +{ + const ymir_particles* p = f->p; + int dynamic_body = p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY && p->proxies[p->att_body[a]].inv_mass > 0.0f; + return dynamic_body ? f->k_body : f->k_particle; +} + +// Adds a force (N) the attachment `a` exerts on the chain to its sensor lane. +static void add_force(ymir_particles* p, int32_t a, v3 force) +{ + p->att_force_x[a] += force.x; + p->att_force_y[a] += force.y; + p->att_force_z[a] += force.z; +} + +// Books a load of `force` N carried along the chain between particles `from` and `to` (same chain): every link +// between them transmits it, so a tether that carries the load past the links is still read by the links. +static void add_link_load(ymir_particles* p, int32_t from, int32_t to, float force) +{ + int32_t lo = from < to ? from : to, hi = from < to ? to : from; + p->tension_diff[lo] += force; + p->tension_diff[hi] -= force; +} + +// ---- grid and particle-particle contact ---------------------------------------------------------------------- + +static uint32_t cell_hash(int32_t a, int32_t b, int32_t c, uint32_t mask) +{ + return (((uint32_t)a * 73856093u) ^ ((uint32_t)b * 19349663u) ^ ((uint32_t)c * 83492791u)) & mask; +} + +static int32_t cell_of(float v, float inv_cell) +{ + return (int32_t)vclamp(floorf(v * inv_cell), -1.0e6f, 1.0e6f); +} + +// Counting sort of the live particles' predicted positions into a hash grid. Within a bucket particles keep +// index order, so every neighbour walk is the same on every run. +static float build_grid(ymir_particles* p) +{ + float rmax = 0.0f; + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] >= 0) + { + rmax = vmax(rmax, p->radius[i]); + } + } + float inv_cell = 1.0f / (2.0f * rmax); + int32_t buckets = (int32_t)p->table_mask + 1; + memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1)); + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] < 0) + { + continue; + } + p->cell_x[i] = cell_of(p->pp_x[i], inv_cell); + p->cell_y[i] = cell_of(p->pp_y[i], inv_cell); + p->cell_z[i] = cell_of(p->pp_z[i], inv_cell); + p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask) + 1]++; + } + for (int32_t c = 0; c < buckets; ++c) + { + p->cell_start[c + 1] += p->cell_start[c]; + p->cell_fill[c] = 0; + } + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] >= 0) + { + uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask); + p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i; + } + } + return rmax; +} + +// Particles of different chains, or of one chain more than two links apart, push each other apart. Gather +// form: particle i reads its neighbours' predicted positions and writes only its own correction. +static void particle_contacts(ymir_particles* p) +{ + for (int32_t i = 0; i < p->particle_count; ++i) + { + p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f; + if (p->chain[i] < 0 || p->inv_mass[i] == 0.0f) + { + continue; + } + v3 xi = P(p, p->pp_x, p->pp_y, p->pp_z, i); + v3 sum = {0.0f, 0.0f, 0.0f}; + int32_t contacts = 0; + for (int32_t da = -1; da <= 1; ++da) + { + for (int32_t db = -1; db <= 1; ++db) + { + for (int32_t dc = -1; dc <= 1; ++dc) + { + int32_t ca = p->cell_x[i] + da, cb = p->cell_y[i] + db, cc = p->cell_z[i] + dc; + uint32_t bucket = cell_hash(ca, cb, cc, p->table_mask); + for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q) + { + int32_t j = p->sorted[q]; + if (j == i || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc) + { + continue; // another cell sharing the bucket + } + if (p->chain[j] == p->chain[i] && (j - i <= 2 && i - j <= 2)) + { + continue; + } + v3 d = vsub(xi, P(p, p->pp_x, p->pp_y, p->pp_z, j)); + float md = p->radius[i] + p->radius[j]; + float r2 = vdot(d, d); + float wsum = p->inv_mass[i] + p->inv_mass[j]; + if (r2 >= md * md || r2 < 1e-12f || wsum == 0.0f) + { + continue; + } + float rr = sqrtf(r2); + sum = vadd(sum, vmul(d, (p->inv_mass[i] / wsum) * (md - rr) / rr)); + contacts++; + } + } + } + } + if (contacts > 0) + { + put(p->dp_x, p->dp_y, p->dp_z, i, vmul(sum, 1.0f / (float)contacts)); // averaged: a Jacobi sum overshoots + } + } + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] >= 0) + { + p->pp_x[i] += p->dp_x[i]; + p->pp_y[i] += p->dp_y[i]; + p->pp_z[i] += p->dp_z[i]; + } + } +} + +// ---- particle-body contact ----------------------------------------------------------------------------------- + +// Signed distance from `x` to the proxy's surface, the outward normal there and the nearest surface point. +static float proxy_distance(const ymir_particle_proxy* b, v3 x, v3* normal, v3* surface) +{ + v3 c = {b->position[0], b->position[1], b->position[2]}; + v3 n; + float d; + if (b->shape == YMIR_PROXY_BOX) + { + v3 l = qrot_inv(b->rotation, vsub(x, c)); + v3 half = {b->size[0], b->size[1], b->size[2]}; + v3 q = {fabsf(l.x) - half.x, fabsf(l.y) - half.y, fabsf(l.z) - half.z}; + v3 nl; + if (q.x > 0.0f || q.y > 0.0f || q.z > 0.0f) + { + v3 out = {vmax(q.x, 0.0f), vmax(q.y, 0.0f), vmax(q.z, 0.0f)}; + d = vlen(out); + nl = (v3){l.x < 0.0f ? -out.x : out.x, l.y < 0.0f ? -out.y : out.y, l.z < 0.0f ? -out.z : out.z}; + nl = vmul(nl, 1.0f / d); + } + else + { + d = vmax(q.x, vmax(q.y, q.z)); // inside: the nearest face + nl = d == q.x ? (v3){l.x < 0.0f ? -1.0f : 1.0f, 0.0f, 0.0f} + : d == q.y ? (v3){0.0f, l.y < 0.0f ? -1.0f : 1.0f, 0.0f} + : (v3){0.0f, 0.0f, l.z < 0.0f ? -1.0f : 1.0f}; + } + n = qrot(b->rotation, nl); + } + else + { + v3 centre = c; + if (b->shape == YMIR_PROXY_CAPSULE) + { + v3 axis = qrot(b->rotation, (v3){0.0f, 1.0f, 0.0f}); + centre = vadd(c, vmul(axis, vclamp(vdot(vsub(x, c), axis), -b->size[1], b->size[1]))); + } + v3 v = vsub(x, centre); + float l = vlen(v); + n = l > 1e-9f ? vmul(v, 1.0f / l) : (v3){0.0f, 1.0f, 0.0f}; + d = l - b->size[0]; + } + *normal = n; + *surface = vsub(x, vmul(n, d)); + return d; +} + +static float proxy_reach(const ymir_particle_proxy* b) +{ + if (b->shape == YMIR_PROXY_SPHERE) + { + return b->size[0]; + } + if (b->shape == YMIR_PROXY_CAPSULE) + { + return b->size[0] + b->size[1]; + } + return sqrtf(b->size[0] * b->size[0] + b->size[1] * b->size[1] + b->size[2] * b->size[2]); +} + +// Each particle against each shaped body in ascending lane order. The correction is split by inverse mass between +// the particle and the body at the contact point; Coulomb friction removes the tangential slip up to mu times the +// push. The body the particle is attached to is skipped: the attachment already ties them. +static void body_contacts(phase* f) +{ + ymir_particles* p = f->p; + for (int32_t i = 0; i < p->particle_count; ++i) + { + int32_t chain = p->chain[i]; + if (chain < 0 || p->inv_mass[i] == 0.0f) + { + continue; + } + float mu = p->chain_friction[chain]; + float r = p->radius[i]; + float wi = p->inv_mass[i]; + for (int32_t k = 0; k < p->body_count; ++k) + { + ymir_particle_proxy* b = p->proxies + k; + if (b->shape == YMIR_PROXY_NONE || k == p->skip_body[i]) + { + continue; + } + v3 x = P(p, p->pp_x, p->pp_y, p->pp_z, i); + v3 c = {b->position[0], b->position[1], b->position[2]}; + float reach = proxy_reach(b) + r; + v3 dc = vsub(x, c); + if (vdot(dc, dc) > reach * reach) + { + continue; + } + v3 n, s; + float d = proxy_distance(b, x, &n, &s); + if (d >= r) + { + continue; + } + float depth = r - d; + float wb = proxy_w(b, s, n); + float w = wi + wb; + x = vadd(x, vmul(n, depth * wi / w)); + proxy_push(f, b, s, vmul(n, -depth / w)); + if (mu > 0.0f) + { + // Slip of the particle against the body point over this substep, tangential part. + v3 rb = vsub(s, (v3){b->position[0], b->position[1], b->position[2]}); + v3 vb = vadd((v3){b->velocity[0], b->velocity[1], b->velocity[2]}, + vcross((v3){b->angular_velocity[0], b->angular_velocity[1], b->angular_velocity[2]}, rb)); + v3 slip = vsub(vsub(x, P(p, p->pos_x, p->pos_y, p->pos_z, i)), vmul(vb, f->h)); // (x - x_prev) - v_body h + slip = vsub(slip, vmul(n, vdot(slip, n))); + float sl = vlen(slip); + if (sl > 1e-9f) + { + v3 t = vmul(slip, 1.0f / sl); + float move = vmin(sl, mu * depth); + float wt = wi + proxy_w(b, s, t); + x = vsub(x, vmul(t, move * wi / wt)); + proxy_push(f, b, s, vmul(t, move / wt)); + } + } + put(p->pp_x, p->pp_y, p->pp_z, i, x); + } + } +} + +// ---- attachments, chain constraints, tethers ----------------------------------------------------------------- + +// Pulls an attached particle onto the point it is attached to (rest length 0), by inverse mass. +static void solve_attachments(phase* f) +{ + ymir_particles* p = f->p; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (p->att_kind[a] == YMIR_ATTACH_REMOVED) + { + continue; + } + int32_t i = p->att_particle[a]; + v3 at = end_point(p, a); + v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at); + float len = vlen(d); + if (len < 1e-9f) + { + continue; + } + v3 n = vmul(d, 1.0f / len); + float den = p->inv_mass[i] + end_w(p, a, at, n) + p->att_compliance[a] / (f->h * f->h); + if (den == 0.0f) + { + continue; + } + float dl = -len / den; + put(p->pp_x, p->pp_y, p->pp_z, i, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, i), vmul(n, p->inv_mass[i] * dl))); + end_push(f, a, at, vmul(n, -dl)); + add_force(p, a, vmul(n, dl * end_force_scale(f, a))); + } +} + +// One distance constraint between two particles; returns lambda (negative when it pulled them together). +static float distance_constraint(ymir_particles* p, int32_t i, int32_t j, float rest, float alpha) +{ + float wi = p->inv_mass[i], wj = p->inv_mass[j]; + v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i)); + float len = vlen(d); + if (len < 1e-9f || wi + wj + alpha == 0.0f) + { + return 0.0f; + } + v3 n = vmul(d, 1.0f / len); + float dl = -(len - rest) / (wi + wj + alpha); + put(p->pp_x, p->pp_y, p->pp_z, i, vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), vmul(n, wi * dl))); + put(p->pp_x, p->pp_y, p->pp_z, j, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, j), vmul(n, wj * dl))); + return dl; +} + +// Each chain in lane order, links in index order (Gauss-Seidel), stretch then bend. One iteration per substep: +// the small step does the converging. Stretch lambda is the link's tension (positive when stretched). +static void solve_chains(phase* f) +{ + ymir_particles* p = f->p; + float hh = f->h * f->h; + for (int32_t c = 0; c < p->chain_count; ++c) + { + if (p->chain_kind[c] != YMIR_CHAIN_LIVE) + { + continue; + } + int32_t first = p->chain_first[c], last = first + p->chain_size[c]; + for (int32_t i = first; i + 1 < last; ++i) + { + float dl = distance_constraint(p, i, i + 1, p->rest_link[i], p->chain_stretch[c] / hh); + p->tension_acc[i] += -dl * f->k_particle; + } + for (int32_t i = first; i + 2 < last; ++i) + { + distance_constraint(p, i, i + 2, p->rest_bend[i], p->chain_bend[c] / hh); + } + } +} + +static int tetherable(const ymir_particles* p, int32_t a) +{ + return p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY || p->att_kind[a] == YMIR_ATTACH_PARTICLE_STATIC; +} + +// Long-range attachments: a unilateral distance bound at the chain's rest path length from each attachment point +// to every particle of its chain, and between the attachment points of one chain. They carry load past the links, +// so the load they carry is booked on the links and on the attachments (the sensors read the load, not the path). +static void solve_tethers(phase* f) +{ + ymir_particles* p = f->p; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (!tetherable(p, a)) + { + continue; + } + int32_t i = p->att_particle[a], c = p->chain[i]; + int32_t first = p->chain_first[c], last = first + p->chain_size[c]; + for (int32_t j = first; j < last; ++j) + { + if (j == i) + { + continue; + } + float bound = fabsf(p->rest_pos[j] - p->rest_pos[i]); + v3 at = end_point(p, a); + v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), at); + float len = vlen(d); + if (len <= bound) + { + continue; + } + v3 n = vmul(d, 1.0f / len); + float den = p->inv_mass[j] + end_w(p, a, at, n); + if (den == 0.0f) + { + continue; + } + float dl = -(len - bound) / den; + put(p->pp_x, p->pp_y, p->pp_z, j, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, j), vmul(n, p->inv_mass[j] * dl))); + end_push(f, a, at, vmul(n, -dl)); + float k = end_force_scale(f, a); + add_force(p, a, vmul(n, dl * k)); // the force on particle j, toward the attachment + add_link_load(p, i, j, -dl * k); + } + } + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (!tetherable(p, a)) + { + continue; + } + for (int32_t b = a + 1; b < p->attachment_count; ++b) + { + if (!tetherable(p, b) || p->chain[p->att_particle[a]] != p->chain[p->att_particle[b]] || + p->att_particle[a] == p->att_particle[b]) + { + continue; + } + float bound = fabsf(p->rest_pos[p->att_particle[a]] - p->rest_pos[p->att_particle[b]]); + v3 pa = end_point(p, a), pb = end_point(p, b); + v3 d = vsub(pa, pb); + float len = vlen(d); + if (len <= bound) + { + continue; + } + v3 n = vmul(d, 1.0f / len); + float den = end_w(p, a, pa, n) + end_w(p, b, pb, n); + if (den == 0.0f) + { + continue; + } + float dl = -(len - bound) / den; + float k = end_force_scale(f, a) == f->k_body || end_force_scale(f, b) == f->k_body ? f->k_body : f->k_particle; + end_push(f, a, pa, vmul(n, dl)); + end_push(f, b, pb, vmul(n, -dl)); + add_force(p, a, vmul(n, -dl * k)); // each point pulls the chain away from the other + add_force(p, b, vmul(n, dl * k)); + add_link_load(p, p->att_particle[a], p->att_particle[b], -dl * k); + } + } +} + +// ---- the step ------------------------------------------------------------------------------------------------ + +void ymir_particles_step(ymir_particles* p, float dt, int32_t substeps, float gx, float gy, float gz) +{ + if (p == NULL || p->live_chains == 0) + { + return; + } + phase f = {p, dt, dt / (float)substeps, 1.0f / dt, 0.0f, 0.0f}; + f.k_particle = 1.0f / (f.h * f.h); + f.k_body = 1.0f / ((float)substeps * f.h * f.h); + v3 g = {gx, gy, gz}; + for (int32_t k = 0; k < p->body_count; ++k) + { + memset(p->proxies[k].impulse, 0, sizeof(p->proxies[k].impulse)); + memset(p->proxies[k].angular_impulse, 0, sizeof(p->proxies[k].angular_impulse)); + } + for (int32_t i = 0; i < p->particle_count; ++i) + { + p->skip_body[i] = -1; + p->tension_acc[i] = 0.0f; + } + for (int32_t a = 0; a < p->attachment_count; ++a) + { + p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f; + if (p->att_kind[a] == YMIR_ATTACH_PARTICLE_BODY) + { + p->skip_body[p->att_particle[a]] = p->att_body[a]; + } + } + + for (int32_t s = 0; s < substeps; ++s) + { + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] < 0) + { + continue; + } + v3 x = P(p, p->pos_x, p->pos_y, p->pos_z, i); + if (p->inv_mass[i] > 0.0f) + { + v3 v = vadd(P(p, p->vel_x, p->vel_y, p->vel_z, i), vmul(g, f.h)); + put(p->vel_x, p->vel_y, p->vel_z, i, v); + x = vadd(x, vmul(v, f.h)); + } + put(p->pp_x, p->pp_y, p->pp_z, i, x); + } + build_grid(p); + particle_contacts(p); + body_contacts(&f); + solve_attachments(&f); + solve_chains(&f); + solve_tethers(&f); + for (int32_t c = 0; c < p->chain_count; ++c) // the tethers' load, spread over the links it bypassed + { + if (p->chain_kind[c] != YMIR_CHAIN_LIVE) + { + continue; + } + float running = 0.0f; + for (int32_t i = p->chain_first[c]; i < p->chain_first[c] + p->chain_size[c]; ++i) + { + running += p->tension_diff[i]; + p->tension_acc[i] += running; + p->tension_diff[i] = 0.0f; + } + } + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (p->chain[i] < 0) + { + continue; + } + v3 x = P(p, p->pos_x, p->pos_y, p->pos_z, i), y = P(p, p->pp_x, p->pp_y, p->pp_z, i); + if (p->inv_mass[i] > 0.0f) + { + put(p->vel_x, p->vel_y, p->vel_z, i, vmul(vsub(y, x), 1.0f / f.h)); + } + put(p->pos_x, p->pos_y, p->pos_z, i, y); + } + } + float mean = 1.0f / (float)substeps; + for (int32_t i = 0; i < p->particle_count; ++i) + { + p->link_tension[i] = p->chain[i] >= 0 ? p->tension_acc[i] * mean : 0.0f; + } + for (int32_t c = 0; c < p->chain_count; ++c) // the last particle of a chain starts no link + { + if (p->chain_kind[c] == YMIR_CHAIN_LIVE) + { + p->link_tension[p->chain_first[c] + p->chain_size[c] - 1] = 0.0f; + } + } + for (int32_t a = 0; a < p->attachment_count; ++a) + { + p->att_force_x[a] *= mean; + p->att_force_y[a] *= mean; + p->att_force_z[a] *= mean; + } +} diff --git a/native/Ymir.Box3D/ymir_particles.h b/native/Ymir.Box3D/ymir_particles.h new file mode 100644 index 0000000..3a86044 --- /dev/null +++ b/native/Ymir.Box3D/ymir_particles.h @@ -0,0 +1,152 @@ +// Particle chains and their attachments: Ymir's own position-based solver, stepped by ymir_box3d_soa_step +// after Box3D has stepped the rigid bodies. This module knows nothing of Box3D: ymir_box3d_soa.c is the only +// Box3D caller. It fills one proxy per body (pose, velocity, shape, inverse mass and inertia) before the step, +// the particle phase moves those proxies by the constraints it solves, and the impulse each body accumulated +// comes back in the proxy for soa.c to apply. See docs/soa-world.md. +// +// Determinism: single thread; chains are Gauss-Seidel in link order; the one Jacobi pass (particle-particle +// contact) is gather-form (each particle writes only its own correction, neighbours read in cell then index +// order from a stable counting-sort grid); proxy impulses are summed per body in constraint order. Compiled +// with -ffp-contract=off (/fp:precise on MSVC) so no fused multiply-add changes a byte. + +#ifndef YMIR_PARTICLES_H +#define YMIR_PARTICLES_H + +#include + +enum +{ + YMIR_PARTICLES_OK = 0, + YMIR_PARTICLES_INVALID_ARGUMENT = 1, + YMIR_PARTICLES_DUPLICATE_ID = 2, + YMIR_PARTICLES_FULL = 3, + YMIR_PARTICLES_OUT_OF_MEMORY = 4 +}; + +enum +{ + YMIR_CHAIN_LIVE = 0, + YMIR_CHAIN_REMOVED = 1 // a destroyed chain's lane: reusable only once a step has passed +}; + +enum +{ + YMIR_ATTACH_PARTICLE_BODY = 0, // particle to a point fixed in a body (its lane) + YMIR_ATTACH_PARTICLE_STATIC = 1, // particle to a world point + YMIR_ATTACH_PARTICLE_PARTICLE = 2, // particle to another particle (its lane in `body`) + YMIR_ATTACH_REMOVED = 3 +}; + +enum +{ + YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it + YMIR_PROXY_SPHERE = 1, + YMIR_PROXY_CAPSULE = 2, // segment along local Y + YMIR_PROXY_BOX = 3 +}; + +// A chain to create: `count` >= 2 particles at `positions` (xyz interleaved) with `masses` (kg, 0 = immovable). +// Link and bend rest lengths are the creation distances. +typedef struct ymir_chain_desc +{ + uint64_t stable_id; + int32_t count; + uint32_t reserved; + const float* positions; + const float* masses; + float radius; + float stretch_compliance; // m/N, >= 0 + float bend_compliance; // m/N, >= 0 + float friction; // >= 0 + uint64_t material_id; +} ymir_chain_desc; + +// An attachment of `particle`. `body` is the body lane (particle-body), the other particle's lane +// (particle-particle) or -1. `point` is in the body's frame (particle-body) or the world (particle-static). +typedef struct ymir_attachment_desc +{ + uint32_t kind; + int32_t particle; + int32_t body; + float point[3]; + float compliance; // m/N, >= 0 + uint32_t reserved; +} ymir_attachment_desc; + +// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse` +// (N s, world, about the body position) are the totals the particle phase delivered, written by it. +typedef struct ymir_particle_proxy +{ + uint32_t shape; + float size[3]; + float position[3]; + float rotation[4]; // x y z w + float velocity[3]; + float angular_velocity[3]; + float inv_mass; // 0 for static, kinematic and anchor bodies + float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz + float impulse[3]; + float angular_impulse[3]; +} ymir_particle_proxy; + +typedef struct ymir_particles +{ + int32_t particle_capacity, chain_capacity, attachment_capacity, body_capacity; + int32_t particle_count, chain_count, attachment_count; // high-water marks + int32_t body_count; // bodies filled in `proxies` this step + int32_t live_chains; + ymir_particle_proxy* proxies; + + // particle lanes + float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass; + float* link_tension; // N, link (i, i+1) on particle i: mean over the substeps; a sensor + int32_t* chain; // chain lane, -1 for a free slot + + // chain lanes + uint64_t* chain_stable_id; + uint32_t* chain_kind; + uint32_t* chain_generation; + int32_t* chain_first; + int32_t* chain_size; + uint64_t* chain_removed_at; + uint64_t* chain_material_id; + float *chain_stretch, *chain_bend, *chain_friction; + + // attachment lanes + uint32_t* att_kind; + uint32_t* att_generation; + int32_t* att_particle; + int32_t* att_body; + float *att_point_x, *att_point_y, *att_point_z, *att_compliance; + float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on the chain (mean); a sensor + uint64_t* att_removed_at; + + // solver scratch, allocated once at create + float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z; + float *rest_link, *rest_bend, *rest_pos, *tension_acc, *tension_diff; + int32_t *skip_body, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted; + uint32_t table_mask; + uint8_t* mark; + void* arena; +} ymir_particles; + +// Creates the state for the given capacities (all >= 0) and `body_capacity` proxies; NULL on failure. +ymir_particles* ymir_particles_create(int32_t particle_capacity, int32_t chain_capacity, int32_t attachment_capacity, int32_t body_capacity); +void ymir_particles_free(ymir_particles* p); + +// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed. +// Every refusal happens before anything changes. +int32_t ymir_particles_create_chain(ymir_particles* p, const ymir_chain_desc* d, uint64_t step_count, int32_t* chain, uint32_t* generation); +int32_t ymir_particles_split_chain(ymir_particles* p, int32_t chain, uint32_t generation, int32_t link, uint64_t tail_stable_id, uint64_t step_count, int32_t* tail, uint32_t* tail_generation); +int32_t ymir_particles_destroy_chain(ymir_particles* p, int32_t chain, uint32_t generation, uint64_t step_count); +int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, int32_t* attachment, uint32_t* generation); +int32_t ymir_particles_detach(ymir_particles* p, int32_t attachment, uint32_t generation, uint64_t step_count); +int32_t ymir_particles_free_particle_slots(const ymir_particles* p, uint64_t step_count); // the largest free run +int32_t ymir_particles_free_chain_slots(const ymir_particles* p, uint64_t step_count); +int32_t ymir_particles_free_attachment_slots(const ymir_particles* p, uint64_t step_count); + +// One particle phase for a tick of `dt` seconds in `substeps` substeps, after the caller filled +// proxies[0 .. body_count). Returns nothing: it cannot fail once the commands were accepted. +void ymir_particles_step(ymir_particles* p, float dt, int32_t substeps, float gx, float gy, float gz); + +#endif diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 74b7d7a..1f16576 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -67,6 +67,62 @@ internal struct Box3DSoaRayHitNative public uint Reserved; } +/// Native layout of ymir_chain_desc. +[StructLayout(LayoutKind.Sequential)] +internal unsafe struct Box3DSoaChainDesc +{ + public ulong StableId; + public int Count; + public uint Reserved; + public float* Positions; + public float* Masses; + public float Radius, StretchCompliance, BendCompliance, Friction; + public ulong MaterialId; +} + +/// Native layout of ymir_attachment_desc. +[StructLayout(LayoutKind.Sequential)] +internal struct Box3DSoaAttachmentDesc +{ + public uint Kind; + public int Particle; + public int Body; + public float PointX, PointY, PointZ; + public float Compliance; + public uint Reserved; +} + +public enum Box3DSoaAttachKind : uint +{ + /// The particle to a point fixed in a body: target is the body lane, point is in the body's frame. + Body = 0, + /// The particle to a world point (point); target is ignored. + Static = 1, + /// The particle to another particle: target is the other particle's lane. + Particle = 2, + /// The kind lane of a detached attachment (a tombstone). + Removed = 3 +} + +public enum Box3DSoaChainKind : uint +{ + Live = 0, + /// A destroyed chain's lane: reusable once a step has passed; it keeps its last range until then. + Removed = 1 +} + +/// A chain's identity: its lane and the slot's generation when it was created or split off. +public readonly record struct Box3DSoaChainHandle(int Lane, uint Generation) +{ + public static implicit operator int(Box3DSoaChainHandle handle) => handle.Lane; +} + +/// An attachment's identity: its lane and the slot's generation when it was made. +public readonly record struct Box3DSoaAttachmentHandle(int Lane, uint Generation) +{ + public static implicit operator int(Box3DSoaAttachmentHandle handle) => handle.Lane; +} + /// /// A joint's identity: its lane and the slot's generation when it was added. Converts to the lane for reading lanes; /// takes the whole handle and refuses one from an earlier occupant of the slot. @@ -91,6 +147,14 @@ internal unsafe struct Box3DSoaViewNative public int JointCapacity; public uint Reserved; public ulong StepCount; + public int ParticleCount; + public int ParticleCapacity; + public int ChainCount; + public int ChainCapacity; + public int AttachmentCount; + public int AttachmentCapacity; + public uint ReservedParticles0; + public uint ReservedParticles1; public ulong* StableId; public uint* Kind; public int* Parent; @@ -139,6 +203,40 @@ internal unsafe struct Box3DSoaViewNative public int* ContactCount; public ulong* MaterialId; public uint* JointGeneration; + public float* ParticleImpulseX; + public float* ParticleImpulseY; + public float* ParticleImpulseZ; + public float* ParticleX; + public float* ParticleY; + public float* ParticleZ; + public float* ParticleVx; + public float* ParticleVy; + public float* ParticleVz; + public float* ParticleRadius; + public float* ParticleInvMass; + public float* ParticleLinkTension; + public int* ParticleChain; + public ulong* ChainStableId; + public uint* ChainKind; + public uint* ChainGeneration; + public int* ChainFirst; + public int* ChainSize; + public ulong* ChainRemovedAt; + public ulong* ChainMaterialId; + public float* ChainStretchCompliance; + public float* ChainBendCompliance; + public float* ChainFriction; + public uint* AttachmentKind; + public uint* AttachmentGeneration; + public int* AttachmentParticle; + public int* AttachmentBody; + public float* AttachmentPointX; + public float* AttachmentPointY; + public float* AttachmentPointZ; + public float* AttachmentCompliance; + public float* AttachmentForceX; + public float* AttachmentForceY; + public float* AttachmentForceZ; } /// Native layout of ymir_box3d_soa_facts: counts, dropped counters, then three pointers. @@ -256,7 +354,7 @@ internal static unsafe partial class Box3DSoaNative [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial int ymir_box3d_soa_create(int capacity, int jointCapacity, float gx, float gy, float gz, int factCapacity, float hitThreshold, out nint world); + internal static partial int ymir_box3d_soa_create(int capacity, int jointCapacity, float gx, float gy, float gz, int factCapacity, float hitThreshold, int particleCapacity, int chainCapacity, int attachmentCapacity, out nint world); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] @@ -301,6 +399,46 @@ internal static unsafe partial class Box3DSoaNative [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_cast_ray_closest(nint world, float* origin, float* translation, out Box3DSoaRayHitNative hit); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial uint ymir_box3d_soa_get_chain_desc_size(); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial uint ymir_box3d_soa_get_attachment_desc_size(); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_create_chain(nint world, in Box3DSoaChainDesc desc, out int chain, out uint generation); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_split_chain(nint world, int chain, uint generation, int link, ulong tailStableId, out int tail, out uint tailGeneration); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_destroy_chain(nint world, int chain, uint generation); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_attach(nint world, in Box3DSoaAttachmentDesc desc, out int attachment, out uint generation); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_detach(nint world, int attachment, uint generation); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_free_particle_slots(nint world); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_free_chain_slots(nint world); + + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_free_attachment_slots(nint world); } /// @@ -412,6 +550,55 @@ public readonly unsafe struct Box3DSoaView public ReadOnlySpan JointOriginY => Lane(_v.JointOriginY, JointCount); public ReadOnlySpan JointOriginZ => Lane(_v.JointOriginZ, JointCount); + // Particle lanes: read-only, changed only by Step and by the chain and attachment commands. Particle lanes are indexed + // by particle up to ParticleCount (a high-water mark); a free slot reads chain -1 and every lane 0. + public int ParticleCount => _v.ParticleCount; + public int ParticleCapacity => _v.ParticleCapacity; + public int ChainCount => _v.ChainCount; + public int AttachmentCount => _v.AttachmentCount; + public ReadOnlySpan ParticleX => Lane(_v.ParticleX, ParticleCount); + public ReadOnlySpan ParticleY => Lane(_v.ParticleY, ParticleCount); + public ReadOnlySpan ParticleZ => Lane(_v.ParticleZ, ParticleCount); + public ReadOnlySpan ParticleVx => Lane(_v.ParticleVx, ParticleCount); + public ReadOnlySpan ParticleVy => Lane(_v.ParticleVy, ParticleCount); + public ReadOnlySpan ParticleVz => Lane(_v.ParticleVz, ParticleCount); + public ReadOnlySpan ParticleRadius => Lane(_v.ParticleRadius, ParticleCount); + public ReadOnlySpan ParticleInvMass => Lane(_v.ParticleInvMass, ParticleCount); + /// N: the load the link from this particle to the next carries, mean over the substeps, tether load included. A sensor: Ymir never splits on it. + public ReadOnlySpan ParticleLinkTension => Lane(_v.ParticleLinkTension, ParticleCount); + /// The particle's chain lane, -1 for a free slot. + public ReadOnlySpan ParticleChain => Lane(_v.ParticleChain, ParticleCount); + + public ReadOnlySpan ChainStableId => Lane(_v.ChainStableId, ChainCount); + public ReadOnlySpan ChainKind => Lane(_v.ChainKind, ChainCount); + public ReadOnlySpan ChainGeneration => Lane(_v.ChainGeneration, ChainCount); + public ReadOnlySpan ChainFirst => Lane(_v.ChainFirst, ChainCount); + public ReadOnlySpan ChainSize => Lane(_v.ChainSize, ChainCount); + public ReadOnlySpan ChainRemovedAt => Lane(_v.ChainRemovedAt, ChainCount); + public ReadOnlySpan ChainMaterialId => Lane(_v.ChainMaterialId, ChainCount); + public ReadOnlySpan ChainStretchCompliance => Lane(_v.ChainStretchCompliance, ChainCount); + public ReadOnlySpan ChainBendCompliance => Lane(_v.ChainBendCompliance, ChainCount); + public ReadOnlySpan ChainFriction => Lane(_v.ChainFriction, ChainCount); + + public ReadOnlySpan AttachmentKind => Lane(_v.AttachmentKind, AttachmentCount); + public ReadOnlySpan AttachmentGeneration => Lane(_v.AttachmentGeneration, AttachmentCount); + public ReadOnlySpan AttachmentParticle => Lane(_v.AttachmentParticle, AttachmentCount); + /// The body lane (), the other particle's lane () or -1. + public ReadOnlySpan AttachmentBody => Lane(_v.AttachmentBody, AttachmentCount); + public ReadOnlySpan AttachmentPointX => Lane(_v.AttachmentPointX, AttachmentCount); + public ReadOnlySpan AttachmentPointY => Lane(_v.AttachmentPointY, AttachmentCount); + public ReadOnlySpan AttachmentPointZ => Lane(_v.AttachmentPointZ, AttachmentCount); + public ReadOnlySpan AttachmentCompliance => Lane(_v.AttachmentCompliance, AttachmentCount); + /// N: what the attachment exerts on the chain, mean over the substeps, tether load included. A sensor. + public ReadOnlySpan AttachmentForceX => Lane(_v.AttachmentForceX, AttachmentCount); + public ReadOnlySpan AttachmentForceY => Lane(_v.AttachmentForceY, AttachmentCount); + public ReadOnlySpan AttachmentForceZ => Lane(_v.AttachmentForceZ, AttachmentCount); + + /// N s, world: the impulse the particle phase delivered to each body over the last step (0 for a body it did not touch). Box3D has already applied it; this is notification only. + public ReadOnlySpan ParticleImpulseX => Lane(_v.ParticleImpulseX, Count); + public ReadOnlySpan ParticleImpulseY => Lane(_v.ParticleImpulseY, Count); + public ReadOnlySpan ParticleImpulseZ => Lane(_v.ParticleImpulseZ, Count); + /// Address of a lane, for tests and interop that need to prove nothing was copied. public nint PositionYAddress => (nint)_v.PositionY; } @@ -424,7 +611,7 @@ public readonly unsafe struct Box3DSoaView /// public sealed class Box3DSoaWorld : IDisposable { - private const uint ExpectedAbi = 8; + private const uint ExpectedAbi = 9; private nint _handle; /// @@ -433,7 +620,8 @@ public sealed class Box3DSoaWorld : IDisposable /// public Box3DSoaWorld( int capacity, float gravityX = 0f, float gravityY = -10f, float gravityZ = 0f, int jointCapacity = 0, - int? factCapacity = null, float hitThreshold = 1f) + int? factCapacity = null, float hitThreshold = 1f, + int particleCapacity = 0, int chainCapacity = 0, int attachmentCapacity = 0) { RequireNativeAbi(Box3DSoaNative.ymir_box3d_soa_get_abi_version()); if (Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || @@ -442,12 +630,14 @@ public sealed class Box3DSoaWorld : IDisposable Box3DSoaNative.ymir_box3d_soa_get_facts_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || Box3DSoaNative.ymir_box3d_soa_get_touch_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || Box3DSoaNative.ymir_box3d_soa_get_hit_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || - Box3DSoaNative.ymir_box3d_soa_get_ray_hit_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf()) + Box3DSoaNative.ymir_box3d_soa_get_ray_hit_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Box3DSoaNative.ymir_box3d_soa_get_chain_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Box3DSoaNative.ymir_box3d_soa_get_attachment_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf()) { throw new InvalidOperationException("The native Ymir Box3D SoA ABI does not match this build."); } - Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, out _handle)); + Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, particleCapacity, chainCapacity, attachmentCapacity, out _handle)); } /// Fails closed when the native library is not the ABI this build expects, in either direction. @@ -658,6 +848,97 @@ public sealed class Box3DSoaWorld : IDisposable return new Box3DSoaRayHit(h.Hit != 0, h.Lane, h.StableId, (h.PointX, h.PointY, h.PointZ), (h.NormalX, h.NormalY, h.NormalZ), h.Fraction); } + /// + /// Creates a particle chain of positions.Length (at least 2) particles, in a free range of the particle lanes. + /// are kg per particle (0 = immovable); link and bend rest lengths are the creation distances. + /// Compliances are m/N (0 = rigid). Returns the chain's handle. Throws for a full world, a duplicate stable id among live + /// chains, a link of no length or non-finite input; nothing changes when it throws. + /// + public unsafe Box3DSoaChainHandle CreateChain( + ulong stableId, ReadOnlySpan<(float X, float Y, float Z)> positions, ReadOnlySpan masses, float radius, + float stretchCompliance = 0f, float bendCompliance = 1e-4f, float friction = 0.3f, ulong materialId = 0) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + if (masses.Length != positions.Length) throw new ArgumentException("One mass per particle.", nameof(masses)); + var xyz = new float[positions.Length * 3]; + for (var i = 0; i < positions.Length; i++) + { + xyz[3 * i] = positions[i].X; xyz[3 * i + 1] = positions[i].Y; xyz[3 * i + 2] = positions[i].Z; + } + fixed (float* p = xyz) + fixed (float* m = masses) + { + var desc = new Box3DSoaChainDesc + { + StableId = stableId, Count = positions.Length, Positions = p, Masses = m, Radius = radius, + StretchCompliance = stretchCompliance, BendCompliance = bendCompliance, Friction = friction, MaterialId = materialId, + }; + Check(Box3DSoaNative.ymir_box3d_soa_create_chain(_handle, desc, out var lane, out var generation)); + return new Box3DSoaChainHandle(lane, generation); + } + } + + /// A chain whose particles all weigh kg. + public Box3DSoaChainHandle CreateChain( + ulong stableId, ReadOnlySpan<(float X, float Y, float Z)> positions, float massPerParticle, float radius, + float stretchCompliance = 0f, float bendCompliance = 1e-4f, float friction = 0.3f, ulong materialId = 0) + { + var masses = new float[positions.Length]; + Array.Fill(masses, massPerParticle); + return CreateChain(stableId, positions, masses, radius, stretchCompliance, bendCompliance, friction, materialId); + } + + /// + /// Cuts the link after particle (0 to size - 2): the head keeps its lane and stable id, the tail + /// takes a new chain lane and . No particle changes lane or address, attachments stay put, + /// and the cut link's tension reads 0. A command: Ymir never splits a chain on its own. + /// + public Box3DSoaChainHandle SplitChain(Box3DSoaChainHandle chain, int link, ulong tailStableId) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + Check(Box3DSoaNative.ymir_box3d_soa_split_chain(_handle, chain.Lane, chain.Generation, link, tailStableId, out var lane, out var generation)); + return new Box3DSoaChainHandle(lane, generation); + } + + /// + /// Removes a chain and every attachment that reaches its particles. Its lane becomes a tombstone (kind Removed) and its + /// particle slots read 0; both are reused only once a has completed. A stale handle is refused. + /// + public void DestroyChain(Box3DSoaChainHandle chain) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + Check(Box3DSoaNative.ymir_box3d_soa_destroy_chain(_handle, chain.Lane, chain.Generation)); + } + + /// + /// Ties to a body point (kind Body: is the body lane, in + /// its frame), a world point (Static) or another particle (Particle: is its lane). Also gives the chain + /// long-range tethers from this point. is m/N, 0 for rigid. Attach where the particle already is. + /// + public Box3DSoaAttachmentHandle Attach( + Box3DSoaAttachKind kind, int particle, int target = -1, (float X, float Y, float Z) point = default, float compliance = 0f) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + var desc = new Box3DSoaAttachmentDesc + { + Kind = (uint)kind, Particle = particle, Body = target, PointX = point.X, PointY = point.Y, PointZ = point.Z, Compliance = compliance, + }; + Check(Box3DSoaNative.ymir_box3d_soa_attach(_handle, desc, out var lane, out var generation)); + return new Box3DSoaAttachmentHandle(lane, generation); + } + + /// Releases an attachment; its lane is a tombstone (kind Removed) until a step has completed. A stale handle is refused. + public void Detach(Box3DSoaAttachmentHandle attachment) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + Check(Box3DSoaNative.ymir_box3d_soa_detach(_handle, attachment.Lane, attachment.Generation)); + } + + /// The largest run of particle slots a new chain could take right now. + public int FreeParticleSlots { get { ObjectDisposedException.ThrowIf(_handle == 0, this); return Box3DSoaNative.ymir_box3d_soa_free_particle_slots(_handle); } } + public int FreeChainSlots { get { ObjectDisposedException.ThrowIf(_handle == 0, this); return Box3DSoaNative.ymir_box3d_soa_free_chain_slots(_handle); } } + public int FreeAttachmentSlots { get { ObjectDisposedException.ThrowIf(_handle == 0, this); return Box3DSoaNative.ymir_box3d_soa_free_attachment_slots(_handle); } } + private static Box3DSoaBodyDesc Describe( Box3DSoaKind kind, ulong stableId, (float X, float Y, float Z) position, (float X, float Y, float Z, float W) rotation, (float, float, float) size, float density, diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs index fccb068..0537008 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs @@ -167,10 +167,10 @@ public sealed class Box3DSoaGrabTests [Fact] public void The_managed_side_refuses_a_native_library_of_another_abi_in_either_direction() { - Assert.Equal(8u, Box3DSoaNative.ymir_box3d_soa_get_abi_version()); - Box3DSoaWorld.RequireNativeAbi(8); - Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(7)); // an older native under this managed build - Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(9)); // a newer one + Assert.Equal(9u, Box3DSoaNative.ymir_box3d_soa_get_abi_version()); + Box3DSoaWorld.RequireNativeAbi(9); + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(8)); // an older native under this managed build + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(10)); // a newer one } [Fact]