diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index 9684637..be99f38 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -58,7 +58,7 @@ enum YMIR_SOA_JOINT_REMOVED = 4 // a destroyed joint's lane: never accepted by add_joint }; -#define YMIR_SOA_ABI_VERSION 9u +#define YMIR_SOA_ABI_VERSION 10u // 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 @@ -124,14 +124,19 @@ 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). + // Particle and constraint high-water counts and capacities (all 0 for a world created without capacities). int32_t particle_count; int32_t particle_capacity; - int32_t chain_count; - int32_t chain_capacity; + int32_t distance_count; + int32_t distance_capacity; + int32_t bend_count; + int32_t bend_capacity; int32_t attachment_count; int32_t attachment_capacity; - uint32_t reserved_particles[2]; + int32_t tether_count; + int32_t tether_capacity; + int32_t material_capacity; + int32_t reserved_particles; // bodies const uint64_t* stable_id; const uint32_t* kind; @@ -197,9 +202,9 @@ typedef struct ymir_box3d_soa_view 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. + // Particle lanes (read-only; only `step` and the particle and constraint commands change them), indexed by lane + // up to the set's count (a high-water mark). A dead lane reads live 0 and every other lane 0 except generation + // and removed_at. Handles are (lane, generation); a lane is reused once a step has passed since its removal. const float* particle_x; const float* particle_y; const float* particle_z; @@ -208,22 +213,43 @@ typedef struct ymir_box3d_soa_view 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 float* particle_rest_x; + const float* particle_rest_y; + const float* particle_rest_z; + const uint32_t* particle_phase; + const uint32_t* particle_material; + const uint32_t* particle_live; + const uint32_t* particle_generation; + const uint64_t* particle_removed_at; + // Derived by rederive_topology: the lowest lane of the particle's component of distance-connected particles. + const int32_t* particle_component; + // Distance lanes. tension (N) is the load the constraint carries, mean over the substeps: a sensor, Ymir never + // removes a constraint on it. + const int32_t* distance_a; + const int32_t* distance_b; + const float* distance_rest; + const float* distance_compliance; + const float* distance_tension; + const uint32_t* distance_live; + const uint32_t* distance_generation; + const uint64_t* distance_removed_at; + // Bend lanes: two distance lanes and the three particles (b shared); rest and limit are offsets of b from the + // centroid of a, b, c (limit < 0 = no hard limit; compliance < 0 = no soft pass). + const int32_t* bend_e1; + const int32_t* bend_e2; + const int32_t* bend_a; + const int32_t* bend_b; + const int32_t* bend_c; + const float* bend_rest; + const float* bend_limit; + const float* bend_compliance; + const uint32_t* bend_live; + const uint32_t* bend_generation; + const uint64_t* bend_removed_at; + // Attachment lanes. kind 0 body, 1 static, 2 removed (a tombstone). force (N) is what the attachment exerts + // on its particles, mean over the substeps, tether load included: a sensor. const uint32_t* attachment_kind; + const uint32_t* attachment_flags; const uint32_t* attachment_generation; const int32_t* attachment_particle; const int32_t* attachment_body; @@ -234,6 +260,17 @@ typedef struct ymir_box3d_soa_view const float* attachment_force_x; const float* attachment_force_y; const float* attachment_force_z; + const uint64_t* attachment_removed_at; + // Tether lanes, indexed up to tether_count: derived, never written by a command. + const int32_t* tether_att; + const int32_t* tether_particle; + const int32_t* tether_parent; + const int32_t* tether_edge; + const int32_t* tether_other; + const float* tether_bound; + // Material table, indexed up to material_capacity. + const float* material_friction; + const uint64_t* material_id_lane; } ymir_box3d_soa_view; // A begin or end of touch between two bodies: their lane indices and the shapes' stable ids. @@ -496,8 +533,8 @@ static void ymir_soa_free(ymir_box3d_soa_world* 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, int32_t particle_capacity, int32_t chain_capacity, - int32_t attachment_capacity, ymir_box3d_soa_world** output) + int32_t fact_capacity, float hit_threshold, const ymir_particle_capacities* particle_capacities, + ymir_box3d_soa_world** output) { if (output == NULL) { @@ -506,7 +543,9 @@ 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 || particle_capacity < 0 || chain_capacity < 0 || attachment_capacity < 0) + hit_threshold < 0.0f || (particle_capacities != NULL && (particle_capacities->particles < 0 || particle_capacities->distances < 0 || + particle_capacities->bends < 0 || particle_capacities->attachments < 0 || particle_capacities->tethers < 0 || + particle_capacities->materials < 0))) { return YMIR_SOA_INVALID_ARGUMENT; } @@ -545,9 +584,10 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( 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) + if (particle_capacities != NULL && (particle_capacities->particles > 0 || particle_capacities->distances > 0 || particle_capacities->bends > 0 || + particle_capacities->attachments > 0 || particle_capacities->tethers > 0 || particle_capacities->materials > 0)) { - world->particles = ymir_particles_create(particle_capacity, chain_capacity, attachment_capacity, capacity); + world->particles = ymir_particles_create(particle_capacities, capacity); if (world->particles == NULL) { ymir_soa_free(world); @@ -1116,7 +1156,7 @@ static void ymir_soa_particle_substep(b3WorldId world_id, int sub_step, float h, (void)sub_step; ymir_box3d_soa_world* world = (ymir_box3d_soa_world*)context; ymir_particles* pt = world->particles; - if (pt->live_chains == 0) + if (pt->live_particles == 0) { return; } @@ -1290,84 +1330,98 @@ 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. +// Particles and the constraints between them. Each command is the whole of its effect: Ymir never removes or +// releases 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) +// Sizes of the native descriptors, for the managed layout check: 0 particle, 1 distance, 2 bend, 3 attachment, +// 4 material, 5 capacities, 6 handle. +YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_particle_desc_size(uint32_t which) { - return (uint32_t)sizeof(ymir_chain_desc); + switch (which) + { + case 0: return (uint32_t)sizeof(ymir_particle_desc); + case 1: return (uint32_t)sizeof(ymir_distance_desc); + case 2: return (uint32_t)sizeof(ymir_bend_desc); + case 3: return (uint32_t)sizeof(ymir_attachment_desc); + case 4: return (uint32_t)sizeof(ymir_material_desc); + case 5: return (uint32_t)sizeof(ymir_particle_capacities); + case 6: return (uint32_t)sizeof(ymir_handle); + default: return 0; + } } -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) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_particles( + ymir_box3d_soa_world* world, int32_t n, const ymir_particle_desc* d, ymir_handle* out) { if (world == NULL || world->particles == NULL) { return YMIR_SOA_INVALID_ARGUMENT; } - return ymir_particles_create_chain(world->particles, d, world->step_count, chain, generation); + return ymir_particles_create_particles(world->particles, n, d, world->step_count, out); } -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) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_particles(ymir_box3d_soa_world* world, int32_t n, const ymir_handle* h) { 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); + return ymir_particles_destroy_particles(world->particles, n, h, world->step_count); } -YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_chain(ymir_box3d_soa_world* world, int32_t chain, uint32_t generation) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_distances( + ymir_box3d_soa_world* world, int32_t n, const ymir_distance_desc* d, ymir_handle* out) { if (world == NULL || world->particles == NULL) { return YMIR_SOA_INVALID_ARGUMENT; } - return ymir_particles_destroy_chain(world->particles, chain, generation, world->step_count); + return ymir_particles_create_distances(world->particles, n, d, world->step_count, out); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_bends( + ymir_box3d_soa_world* world, int32_t n, const ymir_bend_desc* d, ymir_handle* out) +{ + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_create_bends(world->particles, n, d, world->step_count, out); } 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) + ymir_box3d_soa_world* world, const ymir_attachment_desc* d, ymir_handle* out) { 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); + return ymir_particles_attach(world->particles, d, world->count, world->step_count, out); } -YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_detach(ymir_box3d_soa_world* world, int32_t attachment, uint32_t generation) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_remove(ymir_box3d_soa_world* world, uint32_t type, int32_t n, const ymir_handle* h) { if (world == NULL || world->particles == NULL) { return YMIR_SOA_INVALID_ARGUMENT; } - return ymir_particles_detach(world->particles, attachment, generation, world->step_count); + return ymir_particles_remove(world->particles, type, n, h, 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) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_material(ymir_box3d_soa_world* world, int32_t index, const ymir_material_desc* d) { - return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_particle_slots(world->particles, world->step_count); + if (world == NULL || world->particles == NULL) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + return ymir_particles_set_material(world->particles, index, d); } -YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_chain_slots(const ymir_box3d_soa_world* world) +// Lanes a new particle (0), distance (1), bend (2) or attachment (3) could take right now. +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_slots(const ymir_box3d_soa_world* world, uint32_t lane_set) { - 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); + return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_slots(world->particles, lane_set, 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) @@ -1390,10 +1444,15 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world .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, + .distance_count = pt != NULL ? pt->distance_count : 0, + .distance_capacity = pt != NULL ? pt->distance_capacity : 0, + .bend_count = pt != NULL ? pt->bend_count : 0, + .bend_capacity = pt != NULL ? pt->bend_capacity : 0, .attachment_count = pt != NULL ? pt->attachment_count : 0, .attachment_capacity = pt != NULL ? pt->attachment_capacity : 0, + .tether_count = pt != NULL ? pt->tether_count : 0, + .tether_capacity = pt != NULL ? pt->tether_capacity : 0, + .material_capacity = pt != NULL ? pt->material_capacity : 0, .stable_id = world->stable_id, .kind = world->kind, .parent = world->parent, @@ -1456,19 +1515,36 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world 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->particle_rest_x = pt->rest_x; + view->particle_rest_y = pt->rest_y; + view->particle_rest_z = pt->rest_z; + view->particle_phase = pt->phase; + view->particle_material = pt->material; + view->particle_live = pt->particle_live; + view->particle_generation = pt->particle_generation; + view->particle_removed_at = pt->particle_removed_at; + view->particle_component = pt->component; + view->distance_a = pt->dist_a; + view->distance_b = pt->dist_b; + view->distance_rest = pt->dist_rest; + view->distance_compliance = pt->dist_compliance; + view->distance_tension = pt->dist_tension; + view->distance_live = pt->dist_live; + view->distance_generation = pt->dist_generation; + view->distance_removed_at = pt->dist_removed_at; + view->bend_e1 = pt->bend_e1; + view->bend_e2 = pt->bend_e2; + view->bend_a = pt->bend_a; + view->bend_b = pt->bend_b; + view->bend_c = pt->bend_c; + view->bend_rest = pt->bend_rest; + view->bend_limit = pt->bend_limit; + view->bend_compliance = pt->bend_compliance; + view->bend_live = pt->bend_live; + view->bend_generation = pt->bend_generation; + view->bend_removed_at = pt->bend_removed_at; view->attachment_kind = pt->att_kind; + view->attachment_flags = pt->att_flags; view->attachment_generation = pt->att_generation; view->attachment_particle = pt->att_particle; view->attachment_body = pt->att_body; @@ -1479,6 +1555,15 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world view->attachment_force_x = pt->att_force_x; view->attachment_force_y = pt->att_force_y; view->attachment_force_z = pt->att_force_z; + view->attachment_removed_at = pt->att_removed_at; + view->tether_att = pt->tether_att; + view->tether_particle = pt->tether_particle; + view->tether_parent = pt->tether_parent; + view->tether_edge = pt->tether_edge; + view->tether_other = pt->tether_other; + view->tether_bound = pt->tether_bound; + view->material_friction = pt->mat_friction; + view->material_id_lane = pt->mat_id; } return YMIR_SOA_OK; } diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c index 938faf2..3faf053 100644 --- a/native/Ymir.Box3D/ymir_particles.c +++ b/native/Ymir.Box3D/ymir_particles.c @@ -1,6 +1,8 @@ -// 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. +// Particles and the constraint graph between them: XPBD with small steps (Macklin 2016, 2019), bending by the +// triangle-centroid form (Kelager 2010), long-range tethers derived from the graph (Kim 2012), contact by +// pair-symmetric position projection (Macklin 2014), 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" @@ -59,12 +61,15 @@ static void put(float* x, float* y, float* z, int i, v3 v) 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; + int64_t np = p->particle_capacity, nd = p->distance_capacity, nb = p->bend_capacity, na = p->attachment_capacity, + nt = p->tether_capacity, nm = p->material_capacity, nx = p->body_capacity; + int64_t heap = 2 * nd + 1; size_t table = (size_t)p->table_mask + 1; #define CARVE(field, type, count) \ do \ @@ -74,35 +79,47 @@ static size_t layout(ymir_particles* p, unsigned char* base) p->field = (type*)(base + off); \ off += sizeof(type) * (size_t)(count); \ } while (0) - CARVE(proxies, ymir_particle_proxy, nb); + CARVE(proxies, ymir_particle_proxy, nx); 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(radius, float, np); CARVE(inv_mass, float, np); + CARVE(rest_x, float, np); CARVE(rest_y, float, np); CARVE(rest_z, float, np); + CARVE(phase, uint32_t, np); CARVE(material, uint32_t, np); CARVE(particle_live, uint32_t, np); + CARVE(particle_generation, uint32_t, np); CARVE(particle_removed_at, uint64_t, np); CARVE(component, int32_t, np); + CARVE(dist_a, int32_t, nd); CARVE(dist_b, int32_t, nd); CARVE(dist_rest, float, nd); CARVE(dist_compliance, float, nd); + CARVE(dist_tension, float, nd); CARVE(dist_live, uint32_t, nd); CARVE(dist_generation, uint32_t, nd); + CARVE(dist_removed_at, uint64_t, nd); + CARVE(bend_e1, int32_t, nb); CARVE(bend_e2, int32_t, nb); CARVE(bend_a, int32_t, nb); CARVE(bend_b, int32_t, nb); + CARVE(bend_c, int32_t, nb); CARVE(bend_rest, float, nb); CARVE(bend_limit, float, nb); CARVE(bend_compliance, float, nb); + CARVE(bend_live, uint32_t, nb); CARVE(bend_generation, uint32_t, nb); CARVE(bend_removed_at, uint64_t, nb); + CARVE(att_kind, uint32_t, na); CARVE(att_flags, 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(tether_att, int32_t, nt); CARVE(tether_particle, int32_t, nt); CARVE(tether_parent, int32_t, nt); + CARVE(tether_edge, int32_t, nt); CARVE(tether_other, int32_t, nt); CARVE(tether_bound, float, nt); + CARVE(mat_friction, float, nm); CARVE(mat_id, uint64_t, nm); 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(struct_x, float, np); CARVE(struct_y, float, np); CARVE(struct_z, float, np); - 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(dist_acc, float, nd); + CARVE(tacc_x, float, nt); CARVE(tacc_y, float, nt); CARVE(tacc_z, float, nt); + CARVE(lane_list, int32_t, nd); 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); + CARVE(contacts, int32_t, np); + CARVE(adj_start, int32_t, np + 1); CARVE(adj_edge, int32_t, 2 * nd); + CARVE(heap_key, float, heap); CARVE(heap_node, int32_t, heap); CARVE(heap_edge, int32_t, heap); + CARVE(path, float, np); CARVE(prev_edge, int32_t, np); CARVE(tether_of, int32_t, np); + CARVE(queue, int32_t, np); CARVE(comp_size, int32_t, np); CARVE(done, 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) +ymir_particles* ymir_particles_create(const ymir_particle_capacities* c, int32_t body_capacity) { - if (particle_capacity < 0 || chain_capacity < 0 || attachment_capacity < 0 || body_capacity < 0) + if (c == NULL || c->particles < 0 || c->distances < 0 || c->bends < 0 || c->attachments < 0 || c->tethers < 0 || + c->materials < 0 || body_capacity < 0) { return NULL; } @@ -111,12 +128,15 @@ ymir_particles* ymir_particles_create(int32_t particle_capacity, int32_t chain_c { return NULL; } - p->particle_capacity = particle_capacity; - p->chain_capacity = chain_capacity; - p->attachment_capacity = attachment_capacity; + p->particle_capacity = c->particles; + p->distance_capacity = c->distances; + p->bend_capacity = c->bends; + p->attachment_capacity = c->attachments; + p->tether_capacity = c->tethers; + p->material_capacity = c->materials; p->body_capacity = body_capacity; uint32_t table = 16; - while (table < 2u * (uint32_t)particle_capacity) + while (table < 2u * (uint32_t)c->particles) { table <<= 1; } @@ -129,10 +149,6 @@ ymir_particles* ymir_particles_create(int32_t particle_capacity, int32_t chain_c return NULL; } layout(p, (unsigned char*)p->arena); - for (int32_t i = 0; i < particle_capacity; ++i) - { - p->chain[i] = -1; - } return p; } @@ -145,269 +161,111 @@ void ymir_particles_free(ymir_particles* p) } } -// ---- slots --------------------------------------------------------------------------------------------------- +// ---- lanes --------------------------------------------------------------------------------------------------- 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) +// The lowest free lane at or after `from`: a lane never used, or a dead one a step has passed since its removal. +// -1 when there is none. `state` is the lane set's live (or kind) lane and `dead` the value a dead lane holds. +static int32_t next_lane(const uint32_t* state, uint32_t dead, const uint64_t* removed_at, int32_t count, int32_t capacity, + int32_t from, uint64_t step_count) { - for (int32_t i = 0; i < p->particle_capacity; ++i) + for (int32_t i = from; i < 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])) + if (i >= count || (state[i] == dead && lane_reusable(step_count, removed_at[i]))) { - 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 i; } } return -1; } -int32_t ymir_particles_free_particle_slots(const ymir_particles* p, uint64_t step_count) +static int32_t free_count(const uint32_t* state, uint32_t dead, const uint64_t* removed_at, int32_t count, int32_t capacity, + 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) + int32_t n = capacity - count; + for (int32_t i = 0; i < count; ++i) { - run = p->mark[i] ? 0 : run + 1; - best = run > best ? run : best; + n += state[i] == dead && lane_reusable(step_count, removed_at[i]); } - return best; + return n; } -static int32_t chain_slot(const ymir_particles* p, uint64_t step_count) +int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count) { - for (int32_t c = 0; c < p->chain_count; ++c) + if (p == NULL) { - if (p->chain_kind[c] == YMIR_CHAIN_REMOVED && lane_reusable(step_count, p->chain_removed_at[c])) + return 0; + } + switch (lane_set) + { + case YMIR_LANES_PARTICLE: + return free_count(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, step_count); + case YMIR_LANES_DISTANCE: + return free_count(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, step_count); + case YMIR_LANES_BEND: + return free_count(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, step_count); + case YMIR_LANES_ATTACHMENT: + return free_count(p->att_kind, YMIR_ATTACH_REMOVED, p->att_removed_at, p->attachment_count, p->attachment_capacity, step_count); + default: + return 0; + } +} + +static int particle_ok(const ymir_particles* p, int32_t lane, uint32_t generation) +{ + return lane >= 0 && lane < p->particle_count && p->particle_live[lane] && p->particle_generation[lane] == generation; +} + +static int distance_ok(const ymir_particles* p, int32_t lane, uint32_t generation) +{ + return lane >= 0 && lane < p->distance_count && p->dist_live[lane] && p->dist_generation[lane] == generation; +} + +static int bend_ok(const ymir_particles* p, int32_t lane, uint32_t generation) +{ + return lane >= 0 && lane < p->bend_count && p->bend_live[lane] && p->bend_generation[lane] == generation; +} + +static int attachment_ok(const ymir_particles* p, int32_t lane, uint32_t generation) +{ + return lane >= 0 && lane < p->attachment_count && p->att_kind[lane] != YMIR_ATTACH_REMOVED && p->att_generation[lane] == generation; +} + +// Tombstones: the lane keeps its generation (advanced) and removed_at; every other lane reads 0. +static void kill_bend(ymir_particles* p, int32_t k, uint64_t step_count) +{ + p->bend_e1[k] = p->bend_e2[k] = p->bend_a[k] = p->bend_b[k] = p->bend_c[k] = 0; + p->bend_rest[k] = p->bend_limit[k] = p->bend_compliance[k] = 0.0f; + p->bend_live[k] = 0; + p->bend_generation[k] += 1; + p->bend_removed_at[k] = step_count; +} + +// A distance takes the bends over it with it. +static void kill_distance(ymir_particles* p, int32_t e, uint64_t step_count) +{ + for (int32_t k = 0; k < p->bend_count; ++k) + { + if (p->bend_live[k] && (p->bend_e1[k] == e || p->bend_e2[k] == e)) { - return c; + kill_bend(p, k, step_count); } } - return p->chain_count < p->chain_capacity ? p->chain_count : -1; + p->dist_a[e] = p->dist_b[e] = 0; + p->dist_rest[e] = p->dist_compliance[e] = p->dist_tension[e] = 0.0f; + p->dist_live[e] = 0; + p->dist_generation[e] += 1; + p->dist_removed_at[e] = step_count; } -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) +static void kill_attachment(ymir_particles* p, int32_t a, uint64_t step_count) { p->att_kind[a] = YMIR_ATTACH_REMOVED; + p->att_flags[a] = 0; p->att_removed_at[a] = step_count; p->att_generation[a] += 1; p->att_particle[a] = -1; @@ -417,98 +275,531 @@ static void tombstone_attachment(ymir_particles* p, int32_t a, uint64_t step_cou 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) +// ---- derivation: components and tethers ---------------------------------------------------------------------- + +static int heap_less(const ymir_particles* p, int32_t i, int32_t j) { - if (p == NULL || !chain_live(p, chain, generation)) + if (p->heap_key[i] != p->heap_key[j]) { - return YMIR_PARTICLES_INVALID_ARGUMENT; + return p->heap_key[i] < p->heap_key[j]; } - 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->heap_node[i] != p->heap_node[j]) { - if (p->att_kind[a] == YMIR_ATTACH_REMOVED) + return p->heap_node[i] < p->heap_node[j]; + } + return p->heap_edge[i] < p->heap_edge[j]; +} + +static void heap_swap(ymir_particles* p, int32_t i, int32_t j) +{ + float k = p->heap_key[i]; p->heap_key[i] = p->heap_key[j]; p->heap_key[j] = k; + int32_t n = p->heap_node[i]; p->heap_node[i] = p->heap_node[j]; p->heap_node[j] = n; + int32_t e = p->heap_edge[i]; p->heap_edge[i] = p->heap_edge[j]; p->heap_edge[j] = e; +} + +static void heap_push(ymir_particles* p, int32_t* size, float key, int32_t node, int32_t edge) +{ + int32_t i = (*size)++; + p->heap_key[i] = key; + p->heap_node[i] = node; + p->heap_edge[i] = edge; + while (i > 0 && heap_less(p, i, (i - 1) / 2)) + { + heap_swap(p, i, (i - 1) / 2); + i = (i - 1) / 2; + } +} + +// Moves the smallest entry to slot `size` (just past the shrunk heap), where the caller reads it. +static void heap_pop(ymir_particles* p, int32_t* size) +{ + int32_t n = --(*size); + heap_swap(p, 0, n); + int32_t i = 0; + for (;;) + { + int32_t l = 2 * i + 1, r = l + 1, m = i; + if (l < n && heap_less(p, l, m)) + { + m = l; + } + if (r < n && heap_less(p, r, m)) + { + m = r; + } + if (m == i) + { + break; + } + heap_swap(p, i, m); + i = m; + } +} + +// One tether per particle the attachment's particle reaches through live distances, bounded by the geodesic rest +// path (Dijkstra, ties broken by lane), with the tether of the previous particle on the path and the edge used. +// Parents come before children, so a reverse sweep visits leaves first. +static void derive_from(ymir_particles* p, int32_t a, int32_t* nt) +{ + int32_t s = p->att_particle[a], size = 0; + for (int32_t i = 0; i < p->particle_count; ++i) + { + p->path[i] = 1.0e30f; + p->done[i] = 0; + p->tether_of[i] = -1; + } + p->path[s] = 0.0f; + heap_push(p, &size, 0.0f, s, -1); + while (size > 0) + { + heap_pop(p, &size); + float key = p->heap_key[size]; + int32_t u = p->heap_node[size], e = p->heap_edge[size]; + if (p->done[u]) { 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)) + p->done[u] = 1; + if (u != s) { - tombstone_attachment(p, a, step_count); + int32_t t = (*nt)++, other = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e]; + p->tether_att[t] = a; + p->tether_particle[t] = u; + p->tether_bound[t] = key; + p->tether_edge[t] = e; + p->tether_other[t] = -1; + p->tether_parent[t] = p->tether_of[other]; + p->tether_of[u] = t; + } + for (int32_t k = p->adj_start[u]; k < p->adj_start[u + 1]; ++k) + { + int32_t e2 = p->adj_edge[k], v = p->dist_a[e2] == u ? p->dist_b[e2] : p->dist_a[e2]; + float nd = key + p->dist_rest[e2]; + if (!p->done[v] && nd < p->path[v]) + { + p->path[v] = nd; + heap_push(p, &size, nd, v, e2); + } } } - for (int32_t i = lo; i < hi; ++i) +} + +static int is_tether(const ymir_particles* p, int32_t a) +{ + return p->att_kind[a] != YMIR_ATTACH_REMOVED && (p->att_flags[a] & YMIR_ATTACH_FLAG_TETHER); +} + +// 1 when attachments a < b are both tethers on different particles of one component (`label` names components), +// so the rest path between their particles bounds the distance between their points. +static int pairs_with(const ymir_particles* p, int32_t a, int32_t b, const int32_t* label) +{ + int32_t pa = p->att_particle[a], pb = p->att_particle[b]; + return is_tether(p, b) && pa != pb && label[pa] == label[pb]; +} + +// The only writer of the tether lanes and the component lane. Called at the end of every topology command. The +// tether count is known from the component sizes before anything is written: a derivation that would not fit is +// refused with every lane as it was. +static int32_t rederive_topology(ymir_particles* p) +{ + int32_t np = p->particle_count; + memset(p->adj_start, 0, sizeof(int32_t) * ((size_t)np + 1)); + for (int32_t e = 0; e < p->distance_count; ++e) { - 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; + if (p->dist_live[e]) + { + p->adj_start[p->dist_a[e] + 1]++; + p->adj_start[p->dist_b[e] + 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--; + for (int32_t i = 0; i < np; ++i) + { + p->adj_start[i + 1] += p->adj_start[i]; + p->comp_size[i] = p->adj_start[i]; // fill cursors + } + for (int32_t e = 0; e < p->distance_count; ++e) + { + if (p->dist_live[e]) + { + p->adj_edge[p->comp_size[p->dist_a[e]]++] = e; + p->adj_edge[p->comp_size[p->dist_b[e]]++] = e; + } + } + // components by breadth-first labelling from the lowest lane, labels held in tether_of until the count is settled + for (int32_t i = 0; i < np; ++i) + { + p->tether_of[i] = -1; + } + for (int32_t i = 0; i < np; ++i) + { + if (!p->particle_live[i] || p->tether_of[i] >= 0) + { + continue; + } + int32_t head = 0, tail = 0; + p->tether_of[i] = i; + p->queue[tail++] = i; + while (head < tail) + { + int32_t u = p->queue[head++]; + for (int32_t k = p->adj_start[u]; k < p->adj_start[u + 1]; ++k) + { + int32_t e = p->adj_edge[k], v = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e]; + if (p->tether_of[v] < 0) + { + p->tether_of[v] = i; + p->queue[tail++] = v; + } + } + } + p->comp_size[i] = tail; + } + int64_t need = 0; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (!is_tether(p, a)) + { + continue; + } + need += p->comp_size[p->tether_of[p->att_particle[a]]] - 1; + for (int32_t b = a + 1; b < p->attachment_count; ++b) + { + need += pairs_with(p, a, b, p->tether_of); + } + } + if (need > p->tether_capacity) + { + return YMIR_PARTICLES_FULL; + } + for (int32_t i = 0; i < np; ++i) + { + p->component[i] = p->tether_of[i] >= 0 ? p->tether_of[i] : 0; + } + int32_t nt = 0; + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (!is_tether(p, a)) + { + continue; + } + derive_from(p, a, &nt); + for (int32_t b = a + 1; b < p->attachment_count; ++b) + { + if (pairs_with(p, a, b, p->component)) + { + int32_t t = nt++, q = p->att_particle[b]; + p->tether_att[t] = a; + p->tether_particle[t] = q; + p->tether_bound[t] = p->path[q]; + p->tether_edge[t] = -1; + p->tether_other[t] = b; + p->tether_parent[t] = p->tether_of[q]; + } + } + } + p->tether_count = nt; 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) +// ---- commands ------------------------------------------------------------------------------------------------ + +int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out) { - 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) + if (p == NULL || n < 0 || (n > 0 && d == NULL)) { return YMIR_PARTICLES_INVALID_ARGUMENT; } - if (d->kind == YMIR_ATTACH_PARTICLE_BODY && (d->body < 0 || d->body >= body_count)) + for (int32_t k = 0; k < n; ++k) + { + if (!finite3(d[k].position) || !finite3(d[k].rest) || !finite3(d[k].velocity) || !isfinite(d[k].mass) || d[k].mass < 0.0f || + (d[k].mass > 0.0f && !isfinite(1.0f / d[k].mass)) || !isfinite(d[k].radius) || d[k].radius <= 0.0f || + (d[k].phase & ~(uint32_t)YMIR_PHASE_VALID) != 0 || d[k].material >= (uint32_t)p->material_capacity) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + } + if (free_count(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, step_count) < n) + { + return YMIR_PARTICLES_FULL; + } + int32_t cursor = 0; + for (int32_t k = 0; k < n; ++k) + { + int32_t i = next_lane(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, cursor, step_count); + cursor = i + 1; + p->particle_count = i + 1 > p->particle_count ? i + 1 : p->particle_count; + p->pos_x[i] = d[k].position[0]; p->pos_y[i] = d[k].position[1]; p->pos_z[i] = d[k].position[2]; + p->vel_x[i] = d[k].velocity[0]; p->vel_y[i] = d[k].velocity[1]; p->vel_z[i] = d[k].velocity[2]; + p->rest_x[i] = d[k].rest[0]; p->rest_y[i] = d[k].rest[1]; p->rest_z[i] = d[k].rest[2]; + p->radius[i] = d[k].radius; + p->inv_mass[i] = d[k].mass > 0.0f ? 1.0f / d[k].mass : 0.0f; + p->phase[i] = d[k].phase; + p->material[i] = d[k].material; + p->particle_live[i] = 1; + p->live_particles++; + if (out != NULL) + { + out[k] = (ymir_handle){i, p->particle_generation[i]}; + } + } + return rederive_topology(p); +} + +int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count) +{ + if (p == NULL || n < 0 || (n > 0 && h == NULL)) { 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)) + for (int32_t k = 0; k < n; ++k) + { + if (!particle_ok(p, h[k].lane, h[k].generation)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + } + for (int32_t k = 0; k < n; ++k) + { + int32_t i = h[k].lane; + if (!p->particle_live[i]) + { + continue; // named twice + } + for (int32_t e = 0; e < p->distance_count; ++e) + { + if (p->dist_live[e] && (p->dist_a[e] == i || p->dist_b[e] == i)) + { + kill_distance(p, e, step_count); + } + } + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (p->att_kind[a] != YMIR_ATTACH_REMOVED && p->att_particle[a] == i) + { + kill_attachment(p, a, step_count); + } + } + 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->rest_x[i] = p->rest_y[i] = p->rest_z[i] = 0.0f; + p->radius[i] = p->inv_mass[i] = 0.0f; + p->phase[i] = p->material[i] = 0; + p->particle_live[i] = 0; + p->particle_generation[i] += 1; + p->particle_removed_at[i] = step_count; + p->live_particles--; + } + return rederive_topology(p); +} + +int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out) +{ + if (p == NULL || n < 0 || (n > 0 && d == NULL)) { return YMIR_PARTICLES_INVALID_ARGUMENT; } - int32_t a = attachment_slot(p, step_count); + for (int32_t k = 0; k < n; ++k) + { + if (!particle_ok(p, d[k].a.lane, d[k].a.generation) || !particle_ok(p, d[k].b.lane, d[k].b.generation) || + d[k].a.lane == d[k].b.lane || !isfinite(d[k].rest) || !isfinite(d[k].compliance) || d[k].compliance < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + } + if (free_count(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, step_count) < n) + { + return YMIR_PARTICLES_FULL; + } + int32_t old_count = p->distance_count, cursor = 0; + for (int32_t k = 0; k < n; ++k) + { + int32_t e = next_lane(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, cursor, step_count); + cursor = e + 1; + int32_t a = d[k].a.lane, b = d[k].b.lane; + p->lane_list[k] = e; + p->distance_count = e + 1 > p->distance_count ? e + 1 : p->distance_count; + p->dist_a[e] = a; + p->dist_b[e] = b; + p->dist_rest[e] = d[k].rest >= 0.0f + ? d[k].rest + : vlen(vsub((v3){p->rest_x[a], p->rest_y[a], p->rest_z[a]}, (v3){p->rest_x[b], p->rest_y[b], p->rest_z[b]})); + p->dist_compliance[e] = d[k].compliance; + p->dist_tension[e] = 0.0f; + p->dist_live[e] = 1; + } + int32_t status = rederive_topology(p); + if (status != YMIR_PARTICLES_OK) + { + for (int32_t k = 0; k < n; ++k) // back out: the lanes read as they did before the command + { + int32_t e = p->lane_list[k]; + p->dist_a[e] = p->dist_b[e] = 0; + p->dist_rest[e] = p->dist_compliance[e] = 0.0f; + p->dist_live[e] = 0; + } + p->distance_count = old_count; + return status; + } + if (out != NULL) + { + for (int32_t k = 0; k < n; ++k) + { + out[k] = (ymir_handle){p->lane_list[k], p->dist_generation[p->lane_list[k]]}; + } + } + return YMIR_PARTICLES_OK; +} + +int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out) +{ + if (p == NULL || n < 0 || (n > 0 && d == NULL)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + for (int32_t k = 0; k < n; ++k) + { + int32_t e1 = d[k].e1.lane, e2 = d[k].e2.lane; + if (!distance_ok(p, e1, d[k].e1.generation) || !distance_ok(p, e2, d[k].e2.generation) || e1 == e2 || + !isfinite(d[k].compliance) || !isfinite(d[k].max_angle) || d[k].max_angle > 3.14159265f || + (d[k].compliance < 0.0f && d[k].max_angle < 0.0f) || !(p->dist_rest[e1] > 0.0f) || !(p->dist_rest[e2] > 0.0f)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; // a bend that does nothing, or over links of no length, or not over two links + } + int32_t a1 = p->dist_a[e1], b1 = p->dist_b[e1], a2 = p->dist_a[e2], b2 = p->dist_b[e2]; + int shared = (a1 == a2) + (a1 == b2) + (b1 == a2) + (b1 == b2); + if (shared != 1) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; // the two distances must share exactly one particle + } + } + if (free_count(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, step_count) < n) + { + return YMIR_PARTICLES_FULL; + } + int32_t cursor = 0; + for (int32_t k = 0; k < n; ++k) + { + int32_t i = next_lane(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, cursor, step_count); + cursor = i + 1; + int32_t e1 = d[k].e1.lane, e2 = d[k].e2.lane; + int32_t a1 = p->dist_a[e1], b1 = p->dist_b[e1], a2 = p->dist_a[e2], b2 = p->dist_b[e2]; + int32_t a, b, c; + if (b1 == a2) { a = a1; b = b1; c = b2; } + else if (a1 == a2) { a = b1; b = a1; c = b2; } + else if (b1 == b2) { a = a1; b = b1; c = a2; } + else { a = b1; b = a1; c = a2; } + p->bend_count = i + 1 > p->bend_count ? i + 1 : p->bend_count; + p->bend_e1[i] = e1; p->bend_e2[i] = e2; + p->bend_a[i] = a; p->bend_b[i] = b; p->bend_c[i] = c; + v3 ra = {p->rest_x[a], p->rest_y[a], p->rest_z[a]}, rb = {p->rest_x[b], p->rest_y[b], p->rest_z[b]}, + rc = {p->rest_x[c], p->rest_y[c], p->rest_z[c]}; + v3 centroid = vmul(vadd(vadd(ra, rb), rc), 1.0f / 3.0f); + p->bend_rest[i] = vlen(vsub(rb, centroid)); + float l1 = p->dist_rest[e1], l2 = p->dist_rest[e2]; + // |b - centroid| = |(a - b) + (c - b)| / 3, and at deflection phi from straight the links' sum has + // squared length l1^2 + l2^2 - 2 l1 l2 cos(phi): the offset at the limit. + p->bend_limit[i] = d[k].max_angle < 0.0f ? -1.0f : sqrtf(vmax(0.0f, l1 * l1 + l2 * l2 - 2.0f * l1 * l2 * cosf(d[k].max_angle))) / 3.0f; + p->bend_compliance[i] = d[k].compliance; + p->bend_live[i] = 1; + if (out != NULL) + { + out[k] = (ymir_handle){i, p->bend_generation[i]}; + } + } + return rederive_topology(p); +} + +int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out) +{ + if (p == NULL || d == NULL || (d->kind != YMIR_ATTACH_BODY && d->kind != YMIR_ATTACH_STATIC) || + (d->flags & ~(uint32_t)YMIR_ATTACH_FLAG_TETHER) != 0 || !particle_ok(p, d->particle.lane, d->particle.generation) || + !finite3(d->point) || !isfinite(d->compliance) || d->compliance < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + if (d->kind == YMIR_ATTACH_BODY && (d->body < 0 || d->body >= body_count)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + int32_t a = next_lane(p->att_kind, YMIR_ATTACH_REMOVED, p->att_removed_at, p->attachment_count, p->attachment_capacity, 0, step_count); if (a < 0) { return YMIR_PARTICLES_FULL; } - if (a == p->attachment_count) - { - p->attachment_count++; - } + int32_t old_count = p->attachment_count; + p->attachment_count = a + 1 > p->attachment_count ? a + 1 : 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_flags[a] = d->flags; + p->att_particle[a] = d->particle.lane; + p->att_body[a] = d->kind == YMIR_ATTACH_BODY ? d->body : -1; 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) + int32_t status = rederive_topology(p); + if (status != YMIR_PARTICLES_OK) { - *attachment = a; + p->att_kind[a] = a < old_count ? YMIR_ATTACH_REMOVED : 0; + p->att_flags[a] = 0; + p->att_particle[a] = a < old_count ? -1 : 0; + p->att_body[a] = a < old_count ? -1 : 0; + p->att_point_x[a] = p->att_point_y[a] = p->att_point_z[a] = 0.0f; + p->att_compliance[a] = 0.0f; + p->attachment_count = old_count; + return status; } - if (generation != NULL) + if (out != NULL) { - *generation = p->att_generation[a]; + *out = (ymir_handle){a, 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) +int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, 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) + if (p == NULL || n < 0 || (n > 0 && h == NULL) || + (type != YMIR_LANES_DISTANCE && type != YMIR_LANES_BEND && type != YMIR_LANES_ATTACHMENT)) { return YMIR_PARTICLES_INVALID_ARGUMENT; } - tombstone_attachment(p, attachment, step_count); + for (int32_t k = 0; k < n; ++k) + { + int ok = type == YMIR_LANES_DISTANCE ? distance_ok(p, h[k].lane, h[k].generation) + : type == YMIR_LANES_BEND ? bend_ok(p, h[k].lane, h[k].generation) + : attachment_ok(p, h[k].lane, h[k].generation); + if (!ok) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + } + for (int32_t k = 0; k < n; ++k) + { + int32_t lane = h[k].lane; + if (type == YMIR_LANES_DISTANCE && p->dist_live[lane]) + { + kill_distance(p, lane, step_count); + } + else if (type == YMIR_LANES_BEND && p->bend_live[lane]) + { + kill_bend(p, lane, step_count); + } + else if (type == YMIR_LANES_ATTACHMENT && p->att_kind[lane] != YMIR_ATTACH_REMOVED) + { + kill_attachment(p, lane, step_count); + } + } + return rederive_topology(p); +} + +int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d) +{ + if (p == NULL || d == NULL || index < 0 || index >= p->material_capacity || !isfinite(d->friction) || d->friction < 0.0f) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + p->mat_friction[index] = d->friction; + p->mat_id[index] = d->material_id; return YMIR_PARTICLES_OK; } @@ -575,47 +866,30 @@ static void proxy_push(const phase* f, ymir_particle_proxy* b, v3 at, v3 imp) // 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) + if (p->att_kind[a] == YMIR_ATTACH_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; + return p->att_kind[a] == YMIR_ATTACH_BODY ? proxy_w(p->proxies + p->att_body[a], at, n) : 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) + if (p->att_kind[a] == YMIR_ATTACH_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]))); - } } -// Adds a force (N) the attachment `a` exerts on the chain to its sensor lane. +// Adds a force (N) the attachment `a` exerts on its particles to its sensor lane. static void add_force(ymir_particles* p, int32_t a, v3 force) { p->att_force_x[a] += force.x; @@ -623,16 +897,6 @@ static void add_force(ymir_particles* p, int32_t a, v3 force) p->att_force_z[a] += force.z; } -// Books a structural position impulse (kg m) the chain delivers to its particle `i`: links, bends and tethers. -// Every booking has an equal and opposite one, so the sum over the particles past a link is the load the link -// carries (momentum balance), however the solver routed it. -static void add_struct(ymir_particles* p, int32_t i, v3 imp) -{ - p->struct_x[i] += imp.x; - p->struct_y[i] += imp.y; - p->struct_z[i] += imp.z; -} - // ---- grid and particle-particle contact ---------------------------------------------------------------------- static uint32_t cell_hash(int32_t a, int32_t b, int32_t c, uint32_t mask) @@ -652,7 +916,7 @@ 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) + if (p->particle_live[i]) { rmax = vmax(rmax, p->radius[i]); } @@ -662,7 +926,7 @@ static float build_grid(ymir_particles* p) 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) + if (!p->particle_live[i]) { continue; } @@ -678,7 +942,7 @@ static float build_grid(ymir_particles* p) } for (int32_t i = 0; i < p->particle_count; ++i) { - if (p->chain[i] >= 0) + if (p->particle_live[i]) { 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; @@ -687,62 +951,107 @@ static float build_grid(ymir_particles* p) 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. + +// Do particles i and j collide by contact? Symmetric in i and j, which momentum conservation needs. Particles of +// different groups always do; of one group only when both set SELF_COLLIDE, and not, when either sets +// SELF_FILTER, if they touched in the rest pose. +static int collides(const ymir_particles* p, int32_t i, int32_t j) +{ + uint32_t a = p->phase[i], b = p->phase[j]; + if ((a & YMIR_PHASE_GROUP_MASK) != (b & YMIR_PHASE_GROUP_MASK)) + { + return 1; + } + if (!(a & b & YMIR_PHASE_SELF_COLLIDE)) + { + return 0; + } + if ((a | b) & YMIR_PHASE_SELF_FILTER) + { + v3 d = vsub((v3){p->rest_x[i], p->rest_y[i], p->rest_z[i]}, (v3){p->rest_x[j], p->rest_y[j], p->rest_z[j]}); + float reach = 1.5f * (p->radius[i] + p->radius[j]); + if (vdot(d, d) < reach * reach) + { + return 0; + } + } + return 1; +} + +// Overlapping pairs push each other apart, split by inverse mass. Gather form in two passes: the first counts each +// particle's overlaps, the second has particle i read its neighbours' predicted positions and write only its own +// correction, each pair weighted 1 / max(n_i, n_j) from both ends. The pair's two corrections then hold equal and +// opposite momentum, so contact conserves it; a per-particle average would not. static void particle_contacts(ymir_particles* p) { - for (int32_t i = 0; i < p->particle_count; ++i) + for (int pass = 0; pass < 2; ++pass) { - 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) + for (int32_t i = 0; i < p->particle_count; ++i) { - 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) + if (pass == 1) { - for (int32_t dc = -1; dc <= 1; ++dc) + p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f; + } + else + { + p->contacts[i] = 0; + } + if (!p->particle_live[i] || (pass == 1 && 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 overlaps = 0; + for (int32_t da = -1; da <= 1; ++da) + { + for (int32_t db = -1; db <= 1; ++db) { - 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) + for (int32_t dc = -1; dc <= 1; ++dc) { - int32_t j = p->sorted[q]; - if (j == i || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc) + 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) { - continue; // another cell sharing the bucket + int32_t j = p->sorted[q]; + if (j == i || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc || !collides(p, i, j)) + { + continue; // itself, another cell sharing the bucket, or a pair that never collides + } + 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; + } + if (pass == 0) + { + overlaps++; + continue; + } + float rr = sqrtf(r2); + int32_t most = p->contacts[i] > p->contacts[j] ? p->contacts[i] : p->contacts[j]; + float weight = 1.0f / (float)most; + sum = vadd(sum, vmul(d, weight * (p->inv_mass[i] / wsum) * (md - rr) / rr)); } - 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 + if (pass == 0) + { + p->contacts[i] = overlaps; + } + else + { + put(p->dp_x, p->dp_y, p->dp_z, i, sum); + } } } for (int32_t i = 0; i < p->particle_count; ++i) { - if (p->chain[i] >= 0) + if (p->particle_live[i]) { p->pp_x[i] += p->dp_x[i]; p->pp_y[i] += p->dp_y[i]; @@ -820,12 +1129,11 @@ 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) + if (!p->particle_live[i] || p->inv_mass[i] == 0.0f) { continue; } - float mu = p->chain_friction[chain]; + float mu = p->mat_friction[p->material[i]]; float r = p->radius[i]; float wi = p->inv_mass[i]; for (int32_t k = 0; k < p->body_count; ++k) @@ -877,7 +1185,22 @@ static void body_contacts(phase* f) } } -// ---- attachments, chain constraints, tethers ----------------------------------------------------------------- +// ---- attachments, distances, bends, tethers ------------------------------------------------------------------ + +// Books on edge `e` the load an impulse `imp` (kg m) delivered to the particle `far`, the side of the edge away +// from `near`, puts on it: along the edge, positive when the edge is being stretched. Every impulse the +// structure delivers has an equal and opposite one, so the sum past an edge is the load it carries however the +// solver routed it. +static void book(const phase* f, int32_t e, int32_t near_i, int32_t far_i, v3 imp) +{ + ymir_particles* p = f->p; + v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, far_i), P(p, p->pp_x, p->pp_y, p->pp_z, near_i)); + float len = vlen(d); + if (len > 1e-9f) + { + p->dist_acc[e] += -vdot(imp, d) / len * f->k; + } +} // Pulls an attached particle onto the point it is attached to (rest length 0), by inverse mass. static void solve_attachments(phase* f) @@ -910,110 +1233,103 @@ static void solve_attachments(phase* f) } } -// 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))); - add_struct(p, i, vmul(n, -dl)); - add_struct(p, j, vmul(n, 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) +// Each live distance in lane order (Gauss-Seidel), one iteration per substep: the small step does the converging. +// Its lambda is its tension (positive when stretched). +static void solve_distances(phase* f) { ymir_particles* p = f->p; - float hh = f->h * f->h; - for (int32_t c = 0; c < p->chain_count; ++c) + for (int32_t e = 0; e < p->distance_count; ++e) { - if (p->chain_kind[c] != YMIR_CHAIN_LIVE) + if (!p->dist_live[e]) { continue; } - int32_t first = p->chain_first[c], last = first + p->chain_size[c]; - for (int32_t i = first; i + 1 < last; ++i) - { - distance_constraint(p, i, i + 1, p->rest_link[i], p->chain_stretch[c] / hh); - } - 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 bear load past the links, -// so their structural impulses are booked on the particles they pull and 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)) + int32_t i = p->dist_a[e], j = p->dist_b[e]; + float wi = p->inv_mass[i], wj = p->inv_mass[j], alpha = p->dist_compliance[e] / (f->h * f->h); + 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) { 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) + v3 n = vmul(d, 1.0f / len); + float dl = -(len - p->dist_rest[e]) / (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))); + p->dist_acc[e] += -dl * f->k; + } +} + +// Each live bend in lane order, on the offset of the shared particle b from the centroid of a, b, c (Kelager +// 2010): a soft pass (XPBD, compliance / h^2) toward the rest offset, then a hard unilateral pass at the offset the +// maximum angle allows, free inside it and rigid at it. The three position impulses sum to zero; what crossed +// each of the two distances is booked on it. +static void solve_bends(phase* f) +{ + ymir_particles* p = f->p; + for (int32_t k = 0; k < p->bend_count; ++k) + { + if (!p->bend_live[k]) { - if (j == i) + continue; + } + int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k]; + float wa = p->inv_mass[a], wb = p->inv_mass[b], wc = p->inv_mass[c]; + v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f}; + for (int pass = 0; pass < 2; ++pass) + { + if ((pass == 0 && p->bend_compliance[k] < 0.0f) || (pass == 1 && p->bend_limit[k] < 0.0f)) { 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 target = pass == 0 ? p->bend_rest[k] : p->bend_limit[k]; + v3 centroid = vmul(vadd(vadd(P(p, p->pp_x, p->pp_y, p->pp_z, a), P(p, p->pp_x, p->pp_y, p->pp_z, b)), + P(p, p->pp_x, p->pp_y, p->pp_z, c)), 1.0f / 3.0f); + v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, b), centroid); float len = vlen(d); - if (len <= bound) + if (len < 1e-9f) { continue; } - v3 n = vmul(d, 1.0f / len); - float den = p->inv_mass[j] + end_w(p, a, at, n); + float violation = len - target; + if (pass == 1 && violation <= 0.0f) + { + continue; + } + float alpha = pass == 0 ? p->bend_compliance[k] / (f->h * f->h) : 0.0f; + float den = (wa + 4.0f * wb + wc) / 9.0f + alpha; 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)); - add_force(p, a, vmul(n, dl * f->k)); // the force on the chain, toward the attachment - add_struct(p, j, vmul(n, dl)); // the chain between i and j pulls j toward i - add_struct(p, i, vmul(n, -dl)); // and i toward j + v3 n = vmul(d, 1.0f / len); + float dl = -violation / den; + v3 ia = vmul(n, -dl / 3.0f), ib = vmul(n, 2.0f * dl / 3.0f), ic = vmul(n, -dl / 3.0f); + put(p->pp_x, p->pp_y, p->pp_z, a, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, a), vmul(ia, wa))); + put(p->pp_x, p->pp_y, p->pp_z, b, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, b), vmul(ib, wb))); + put(p->pp_x, p->pp_y, p->pp_z, c, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, c), vmul(ic, wc))); + ja = vadd(ja, ia); + jc = vadd(jc, ic); } + book(f, p->bend_e1[k], a, b, vmul(ja, -1.0f)); // what crossed e1 toward b and c + book(f, p->bend_e2[k], b, c, jc); } - for (int32_t a = 0; a < p->attachment_count; ++a) +} + +// Long-range bounds derived from the graph, unilateral: a tether holds a particle within the rest path of an +// attachment point, a pair tether holds two attachment points within the rest path between their particles. They +// bear load past the distances, so each tether's impulse is routed leaves first up its path tree and booked on the +// edges it crossed: the tension sensors read the load, not the path. +static void solve_tethers(phase* f) +{ + ymir_particles* p = f->p; + for (int32_t t = 0; t < p->tether_count; ++t) { - if (!tetherable(p, a)) + p->tacc_x[t] = p->tacc_y[t] = p->tacc_z[t] = 0.0f; + int32_t a = p->tether_att[t], b = p->tether_other[t]; + float bound = p->tether_bound[t]; + if (b >= 0) { - 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); @@ -1030,10 +1346,44 @@ static void solve_tethers(phase* f) float dl = -(len - bound) / den; end_push(f, a, pa, vmul(n, dl)); end_push(f, b, pb, vmul(n, -dl)); - add_force(p, a, vmul(n, -dl * f->k)); // each point pulls the chain away from the other + add_force(p, a, vmul(n, -dl * f->k)); // each point pulls the particles away from the other add_force(p, b, vmul(n, dl * f->k)); - add_struct(p, p->att_particle[a], vmul(n, dl)); // the chain between pulls each end toward the other - add_struct(p, p->att_particle[b], vmul(n, -dl)); + put(p->tacc_x, p->tacc_y, p->tacc_z, t, vmul(n, -dl)); // delivered to b's particle, toward a + continue; + } + int32_t j = p->tether_particle[t]; + 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)); + add_force(p, a, vmul(n, dl * f->k)); // the force on the particles, toward the attachment + put(p->tacc_x, p->tacc_y, p->tacc_z, t, vmul(n, dl)); + } + for (int32_t t = p->tether_count - 1; t >= 0; --t) + { + v3 load = P(p, p->tacc_x, p->tacc_y, p->tacc_z, t); + int32_t e = p->tether_edge[t]; + if (e >= 0) + { + int32_t j = p->tether_particle[t], other = p->dist_a[e] == j ? p->dist_b[e] : p->dist_a[e]; + book(f, e, other, j, load); + } + if (p->tether_parent[t] >= 0) + { + int32_t q = p->tether_parent[t]; + put(p->tacc_x, p->tacc_y, p->tacc_z, q, vadd(P(p, p->tacc_x, p->tacc_y, p->tacc_z, q), load)); } } } @@ -1042,7 +1392,7 @@ static void solve_tethers(phase* f) int32_t ymir_particles_begin(ymir_particles* p) { - if (p == NULL || p->live_chains == 0) + if (p == NULL || p->live_particles == 0) { return 0; } @@ -1055,12 +1405,15 @@ int32_t ymir_particles_begin(ymir_particles* p) for (int32_t i = 0; i < p->particle_count; ++i) { p->skip_body[i] = -1; - p->tension_acc[i] = 0.0f; + } + for (int32_t e = 0; e < p->distance_count; ++e) + { + p->dist_acc[e] = 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) + if (p->att_kind[a] == YMIR_ATTACH_BODY) { p->skip_body[p->att_particle[a]] = p->att_body[a]; } @@ -1074,7 +1427,7 @@ int32_t ymir_particles_begin(ymir_particles* p) // velocity and momentum stay one state: XPBD's velocity update, done by the rigid integrator. void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz) { - if (p == NULL || p->live_chains == 0) + if (p == NULL || p->live_particles == 0) { return; } @@ -1110,7 +1463,7 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa } for (int32_t i = 0; i < p->particle_count; ++i) { - if (p->chain[i] < 0) + if (!p->particle_live[i]) { continue; } @@ -1122,37 +1475,17 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa x = vadd(x, vmul(v, h)); } put(p->pp_x, p->pp_y, p->pp_z, i, x); - p->struct_x[i] = p->struct_y[i] = p->struct_z[i] = 0.0f; } build_grid(p); particle_contacts(p); solve_attachments(&f); - solve_chains(&f); + solve_distances(&f); + solve_bends(&f); solve_tethers(&f); body_contacts(&f); - // Link tension by momentum balance: what the structure delivered to the particles past the link, along it. - 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]; - v3 past = {0.0f, 0.0f, 0.0f}; - for (int32_t i = last - 2; i >= first; --i) - { - past = vadd(past, P(p, p->struct_x, p->struct_y, p->struct_z, i + 1)); - v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i + 1), P(p, p->pp_x, p->pp_y, p->pp_z, i)); - float len = vlen(d); - if (len > 1e-9f) - { - p->tension_acc[i] += -vdot(past, d) / len * f.k; - } - } - } for (int32_t i = 0; i < p->particle_count; ++i) { - if (p->chain[i] < 0) + if (!p->particle_live[i]) { continue; } @@ -1176,21 +1509,14 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa void ymir_particles_end(ymir_particles* p, int32_t substeps) { - if (p == NULL || p->live_chains == 0) + if (p == NULL || p->live_particles == 0) { return; } float mean = 1.0f / (float)substeps; - for (int32_t i = 0; i < p->particle_count; ++i) + for (int32_t e = 0; e < p->distance_count; ++e) { - 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; - } + p->dist_tension[e] = p->dist_live[e] ? p->dist_acc[e] * mean : 0.0f; } for (int32_t a = 0; a < p->attachment_count; ++a) { diff --git a/native/Ymir.Box3D/ymir_particles.h b/native/Ymir.Box3D/ymir_particles.h index a5694cb..1ffba62 100644 --- a/native/Ymir.Box3D/ymir_particles.h +++ b/native/Ymir.Box3D/ymir_particles.h @@ -1,13 +1,22 @@ -// 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. +// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps +// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body +// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver 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. +// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type +// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a +// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every +// topology command ends in and which is their only writer. +// +// Determinism: single thread; constraints are Gauss-Seidel in lane 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, a pair weighted the same from both ends); proxy impulses are summed per body +// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise +// on MSVC) so no fused multiply-add changes a byte. +// +// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019). +// No code of PhysX 5.6.0 or any other solver is adapted here. #ifndef YMIR_PARTICLES_H #define YMIR_PARTICLES_H @@ -23,18 +32,34 @@ enum YMIR_PARTICLES_OUT_OF_MEMORY = 4 }; +// Phase word: bits 0-19 are the group; the two flags below are the only other bits. enum { - YMIR_CHAIN_LIVE = 0, - YMIR_CHAIN_REMOVED = 1 // a destroyed chain's lane: reusable only once a step has passed + YMIR_PHASE_GROUP_MASK = 0xFFFFFu, + YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it) + YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it) + YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER +}; + +// Lane sets a command names (a type for remove, a set for free_slots). +enum +{ + YMIR_LANES_PARTICLE = 0, + YMIR_LANES_DISTANCE = 1, + YMIR_LANES_BEND = 2, + YMIR_LANES_ATTACHMENT = 3 }; 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 + YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane) + YMIR_ATTACH_STATIC = 1, // particle to a world point + YMIR_ATTACH_REMOVED = 2 +}; + +enum +{ + YMIR_ATTACH_FLAG_TETHER = 1u // the attachment bounds every particle its component reaches by the rest path }; enum @@ -45,34 +70,68 @@ enum 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 +// A lane and the generation it had when the handle was made. +typedef struct ymir_handle { - 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; + int32_t lane; + uint32_t generation; +} ymir_handle; -// 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_particle_capacities +{ + int32_t particles, distances, bends, attachments, tethers, materials; +} ymir_particle_capacities; + +// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and +// the self-collision filter read it); `material` indexes the material table. +typedef struct ymir_particle_desc +{ + float position[3]; + float rest[3]; + float velocity[3]; + float mass; + float radius; + uint32_t phase; + uint32_t material; +} ymir_particle_desc; + +// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0. +typedef struct ymir_distance_desc +{ + ymir_handle a, b; + float rest; + float compliance; +} ymir_distance_desc; + +// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off; +// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off. +typedef struct ymir_bend_desc +{ + ymir_handle e1, e2; + float compliance; + float max_angle; +} ymir_bend_desc; + +// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body) +// or the world (static). typedef struct ymir_attachment_desc { uint32_t kind; - int32_t particle; + uint32_t flags; + ymir_handle particle; int32_t body; float point[3]; float compliance; // m/N, >= 0 uint32_t reserved; } ymir_attachment_desc; +typedef struct ymir_material_desc +{ + float friction; // >= 0 + uint32_t reserved; + uint64_t material_id; +} ymir_material_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 @@ -93,59 +152,75 @@ typedef struct 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; + int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity; + int32_t body_capacity; + int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks + int32_t tether_count; // derived: the live tethers + int32_t body_count; // bodies filled in `proxies` this step + int32_t live_particles; ymir_particle_proxy* proxies; - // particle lanes + // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at 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 + float *rest_x, *rest_y, *rest_z; + uint32_t *phase, *material, *particle_live, *particle_generation; + uint64_t* particle_removed_at; + int32_t* component; // derived: the lowest lane of the particle's distance-connected component - // 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; + // distance lanes + int32_t *dist_a, *dist_b; + float *dist_rest, *dist_compliance; + float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor + uint32_t *dist_live, *dist_generation; + uint64_t* dist_removed_at; + + // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared) + int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c; + float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off + uint32_t *bend_live, *bend_generation; + uint64_t* bend_removed_at; // attachment lanes - uint32_t* att_kind; - uint32_t* att_generation; - int32_t* att_particle; - int32_t* att_body; + uint32_t *att_kind, *att_flags, *att_generation; + int32_t *att_particle, *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 + float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor uint64_t* att_removed_at; + // tether lanes: derived, per attachment its settled particles in order and then its pairs, parents before children; + // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point + int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other; + float* tether_bound; + + // material table + float* mat_friction; + uint64_t* mat_id; + // 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, *struct_x, *struct_y, *struct_z; - int32_t *skip_body, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted; + float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z; + int32_t *lane_list, *skip_body, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts; + int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *prev_edge, *tether_of, *queue, *comp_size; + float *heap_key, *path; + uint8_t* done; 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); +// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure. +ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, 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); +// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest +// lane first. Every refusal happens before anything changes; a command that would need more tethers than the +// capacity is refused whole. Every topology command ends in the one rederive_topology. +int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out); +int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count); +int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out); +int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out); +int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out); +int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count); +int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d); +int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count); // The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the // proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 1f16576..f1f918f 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -67,17 +67,97 @@ internal struct Box3DSoaRayHitNative public uint Reserved; } -/// Native layout of ymir_chain_desc. +/// +/// A particle's identity: its lane and the slot's generation when it was made. Native layout of ymir_handle. +/// Converts to the lane for reading lanes; commands refuse a handle from an earlier occupant of the slot. +/// [StructLayout(LayoutKind.Sequential)] -internal unsafe struct Box3DSoaChainDesc +public readonly record struct Box3DSoaParticleHandle(int Lane, uint Generation) { - public ulong StableId; - public int Count; - public uint Reserved; - public float* Positions; - public float* Masses; - public float Radius, StretchCompliance, BendCompliance, Friction; - public ulong MaterialId; + public static implicit operator int(Box3DSoaParticleHandle handle) => handle.Lane; +} + +/// The constraint lane sets. Native numbering: a particle is set 0. +public enum Box3DSoaConstraintType : uint +{ + Distance = 1, + Bend = 2, + Attachment = 3 +} + +/// A constraint's identity: its type, lane and the slot's generation when it was made. +public readonly record struct Box3DSoaConstraintHandle(Box3DSoaConstraintType Type, int Lane, uint Generation) +{ + public static implicit operator int(Box3DSoaConstraintHandle handle) => handle.Lane; +} + +/// The phase word: bits 0-19 are the group; the flags are the only other bits. +public static class Box3DSoaPhase +{ + public const uint GroupMask = 0xFFFFFu; + /// Particles of one group collide (both must set it). + public const uint SelfCollide = 1u << 20; + /// ...except pairs closer than 1.5 (ri + rj) in the rest pose (either may carry it). + public const uint SelfFilter = 1u << 21; + + public static uint Of(uint group, bool selfCollide = false, bool selfFilter = false) => + (group & GroupMask) | (selfCollide ? SelfCollide : 0u) | (selfFilter ? SelfFilter : 0u); +} + +/// Capacities of the particle state; null or all zero is a world without particles (ABI 8 behaviour). +[StructLayout(LayoutKind.Sequential)] +public readonly record struct Box3DSoaParticleCapacities(int Particles, int Distances, int Bends, int Attachments, int Tethers, int Materials); + +/// Native layout of ymir_particle_desc: a particle to create. Mass kg (0 = immovable); rest is its place in the rest pose. +[StructLayout(LayoutKind.Sequential)] +public struct Box3DSoaParticleDesc +{ + public float X, Y, Z; + public float RestX, RestY, RestZ; + public float VelocityX, VelocityY, VelocityZ; + public float Mass, Radius; + public uint Phase, Material; + + /// A particle at , its rest pose the same place unless says otherwise. + public Box3DSoaParticleDesc((float X, float Y, float Z) position, float mass, float radius, uint phase = 0, uint material = 0, (float X, float Y, float Z)? rest = null, (float X, float Y, float Z) velocity = default) + { + (X, Y, Z) = position; + (RestX, RestY, RestZ) = rest ?? position; + (VelocityX, VelocityY, VelocityZ) = velocity; + Mass = mass; Radius = radius; Phase = phase; Material = material; + } +} + +/// Native layout of ymir_distance_desc. Rest < 0 takes the rest-pose length; compliance is m/N. +[StructLayout(LayoutKind.Sequential)] +public struct Box3DSoaDistanceDesc +{ + public Box3DSoaParticleHandle A, B; + public float Rest, Compliance; + + public Box3DSoaDistanceDesc(Box3DSoaParticleHandle a, Box3DSoaParticleHandle b, float compliance = 0f, float rest = -1f) + { + A = a; B = b; Rest = rest; Compliance = compliance; + } +} + +/// +/// Native layout of ymir_bend_desc: a bend over two distances that share one particle. A compliance < 0 switches +/// the soft pass off, a max angle (radians from straight) < 0 the hard limit. +/// +[StructLayout(LayoutKind.Sequential)] +public struct Box3DSoaBendDesc +{ + public int E1; + public uint G1; + public int E2; + public uint G2; + public float Compliance, MaxAngle; + + public Box3DSoaBendDesc(Box3DSoaConstraintHandle e1, Box3DSoaConstraintHandle e2, float compliance = 1e-4f, float maxAngle = -1f) + { + E1 = e1.Lane; G1 = e1.Generation; E2 = e2.Lane; G2 = e2.Generation; Compliance = compliance; MaxAngle = maxAngle; + } } /// Native layout of ymir_attachment_desc. @@ -85,42 +165,31 @@ internal unsafe struct Box3DSoaChainDesc internal struct Box3DSoaAttachmentDesc { public uint Kind; - public int Particle; + public uint Flags; + public Box3DSoaParticleHandle Particle; public int Body; public float PointX, PointY, PointZ; public float Compliance; public uint Reserved; } +/// Native layout of ymir_material_desc. +[StructLayout(LayoutKind.Sequential)] +internal struct Box3DSoaMaterialDesc +{ + public float Friction; + public uint Reserved; + public ulong MaterialId; +} + 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; + /// The kind lane of a removed attachment (a tombstone). + Removed = 2 } /// @@ -149,12 +218,16 @@ internal unsafe struct Box3DSoaViewNative public ulong StepCount; public int ParticleCount; public int ParticleCapacity; - public int ChainCount; - public int ChainCapacity; + public int DistanceCount; + public int DistanceCapacity; + public int BendCount; + public int BendCapacity; public int AttachmentCount; public int AttachmentCapacity; - public uint ReservedParticles0; - public uint ReservedParticles1; + public int TetherCount; + public int TetherCapacity; + public int MaterialCapacity; + public int ReservedParticles; public ulong* StableId; public uint* Kind; public int* Parent; @@ -214,19 +287,36 @@ internal unsafe struct Box3DSoaViewNative 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 float* ParticleRestX; + public float* ParticleRestY; + public float* ParticleRestZ; + public uint* ParticlePhase; + public uint* ParticleMaterial; + public uint* ParticleLive; + public uint* ParticleGeneration; + public ulong* ParticleRemovedAt; + public int* ParticleComponent; + public int* DistanceA; + public int* DistanceB; + public float* DistanceRest; + public float* DistanceCompliance; + public float* DistanceTension; + public uint* DistanceLive; + public uint* DistanceGeneration; + public ulong* DistanceRemovedAt; + public int* BendE1; + public int* BendE2; + public int* BendA; + public int* BendB; + public int* BendC; + public float* BendRest; + public float* BendLimit; + public float* BendCompliance; + public uint* BendLive; + public uint* BendGeneration; + public ulong* BendRemovedAt; public uint* AttachmentKind; + public uint* AttachmentFlags; public uint* AttachmentGeneration; public int* AttachmentParticle; public int* AttachmentBody; @@ -237,6 +327,15 @@ internal unsafe struct Box3DSoaViewNative public float* AttachmentForceX; public float* AttachmentForceY; public float* AttachmentForceZ; + public ulong* AttachmentRemovedAt; + public int* TetherAtt; + public int* TetherParticle; + public int* TetherParent; + public int* TetherEdge; + public int* TetherOther; + public float* TetherBound; + public float* MaterialFriction; + public ulong* MaterialTableId; } /// Native layout of ymir_box3d_soa_facts: counts, dropped counters, then three pointers. @@ -354,7 +453,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, int particleCapacity, int chainCapacity, int attachmentCapacity, 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, Box3DSoaParticleCapacities* particles, out nint world); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] @@ -402,43 +501,39 @@ internal static unsafe partial class Box3DSoaNative [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial uint ymir_box3d_soa_get_chain_desc_size(); + internal static partial uint ymir_box3d_soa_get_particle_desc_size(uint which); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial uint ymir_box3d_soa_get_attachment_desc_size(); + internal static partial int ymir_box3d_soa_create_particles(nint world, int n, Box3DSoaParticleDesc* desc, Box3DSoaParticleHandle* output); [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); + internal static partial int ymir_box3d_soa_destroy_particles(nint world, int n, Box3DSoaParticleHandle* handles); [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); + internal static partial int ymir_box3d_soa_create_distances(nint world, int n, Box3DSoaDistanceDesc* desc, Box3DSoaParticleHandle* output); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial int ymir_box3d_soa_destroy_chain(nint world, int chain, uint generation); + internal static partial int ymir_box3d_soa_create_bends(nint world, int n, Box3DSoaBendDesc* desc, Box3DSoaParticleHandle* output); [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); + internal static partial int ymir_box3d_soa_attach(nint world, in Box3DSoaAttachmentDesc desc, out Box3DSoaParticleHandle handle); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial int ymir_box3d_soa_detach(nint world, int attachment, uint generation); + internal static partial int ymir_box3d_soa_remove(nint world, uint type, int n, Box3DSoaParticleHandle* handles); [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] - internal static partial int ymir_box3d_soa_free_particle_slots(nint world); + internal static partial int ymir_box3d_soa_set_material(nint world, int index, in Box3DSoaMaterialDesc desc); [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); + internal static partial int ymir_box3d_soa_free_slots(nint world, uint laneSet); } /// @@ -550,12 +645,11 @@ 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. + // Particle lanes: read-only, changed only by Step and by the particle and constraint commands. Lanes are indexed up to + // the set's count (a high-water mark). A dead lane reads live 0 and every other lane 0 except generation and removed_at; + // it is reused once a step has passed since its removal. 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); @@ -564,35 +658,73 @@ public readonly unsafe struct Box3DSoaView 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 ParticleRestX => Lane(_v.ParticleRestX, ParticleCount); + public ReadOnlySpan ParticleRestY => Lane(_v.ParticleRestY, ParticleCount); + public ReadOnlySpan ParticleRestZ => Lane(_v.ParticleRestZ, ParticleCount); + public ReadOnlySpan ParticlePhase => Lane(_v.ParticlePhase, ParticleCount); + public ReadOnlySpan ParticleMaterial => Lane(_v.ParticleMaterial, ParticleCount); + public ReadOnlySpan ParticleLive => Lane(_v.ParticleLive, ParticleCount); + public ReadOnlySpan ParticleGeneration => Lane(_v.ParticleGeneration, ParticleCount); + public ReadOnlySpan ParticleRemovedAt => Lane(_v.ParticleRemovedAt, ParticleCount); + /// Derived: the lowest lane of the particle's component of distance-connected particles. + public ReadOnlySpan ParticleComponent => Lane(_v.ParticleComponent, 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 int DistanceCount => _v.DistanceCount; + public ReadOnlySpan DistanceA => Lane(_v.DistanceA, DistanceCount); + public ReadOnlySpan DistanceB => Lane(_v.DistanceB, DistanceCount); + public ReadOnlySpan DistanceRest => Lane(_v.DistanceRest, DistanceCount); + public ReadOnlySpan DistanceCompliance => Lane(_v.DistanceCompliance, DistanceCount); + /// N: the load the constraint carries (its own correction, the bends over it and the tether impulses routed through it), mean over the substeps. A sensor: Ymir never removes a constraint on it. + public ReadOnlySpan DistanceTension => Lane(_v.DistanceTension, DistanceCount); + public ReadOnlySpan DistanceLive => Lane(_v.DistanceLive, DistanceCount); + public ReadOnlySpan DistanceGeneration => Lane(_v.DistanceGeneration, DistanceCount); + public ReadOnlySpan DistanceRemovedAt => Lane(_v.DistanceRemovedAt, DistanceCount); + public int BendCount => _v.BendCount; + public ReadOnlySpan BendE1 => Lane(_v.BendE1, BendCount); + public ReadOnlySpan BendE2 => Lane(_v.BendE2, BendCount); + public ReadOnlySpan BendA => Lane(_v.BendA, BendCount); + public ReadOnlySpan BendB => Lane(_v.BendB, BendCount); + public ReadOnlySpan BendC => Lane(_v.BendC, BendCount); + /// Offsets of the shared particle from the centroid of the three, in metres: at rest and at the hard limit (negative: no limit). + public ReadOnlySpan BendRest => Lane(_v.BendRest, BendCount); + public ReadOnlySpan BendLimit => Lane(_v.BendLimit, BendCount); + public ReadOnlySpan BendCompliance => Lane(_v.BendCompliance, BendCount); + public ReadOnlySpan BendLive => Lane(_v.BendLive, BendCount); + public ReadOnlySpan BendGeneration => Lane(_v.BendGeneration, BendCount); + public ReadOnlySpan BendRemovedAt => Lane(_v.BendRemovedAt, BendCount); + + public int AttachmentCount => _v.AttachmentCount; public ReadOnlySpan AttachmentKind => Lane(_v.AttachmentKind, AttachmentCount); + public ReadOnlySpan AttachmentFlags => Lane(_v.AttachmentFlags, 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. + /// The body 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. + /// N: what the attachment exerts on its particles, 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); + public ReadOnlySpan AttachmentRemovedAt => Lane(_v.AttachmentRemovedAt, AttachmentCount); + + /// Derived tethers, up to : written only by the topology commands, parents before children per attachment. + public int TetherCount => _v.TetherCount; + public int TetherCapacity => _v.TetherCapacity; + public ReadOnlySpan TetherAttachment => Lane(_v.TetherAtt, TetherCount); + public ReadOnlySpan TetherParticle => Lane(_v.TetherParticle, TetherCount); + public ReadOnlySpan TetherParent => Lane(_v.TetherParent, TetherCount); + public ReadOnlySpan TetherEdge => Lane(_v.TetherEdge, TetherCount); + /// The second attachment of a pair tether (a bound between two attachment points, edge -1), or -1. + public ReadOnlySpan TetherOther => Lane(_v.TetherOther, TetherCount); + public ReadOnlySpan TetherBound => Lane(_v.TetherBound, TetherCount); + + public int MaterialCapacity => _v.MaterialCapacity; + public ReadOnlySpan MaterialFriction => Lane(_v.MaterialFriction, MaterialCapacity); + public ReadOnlySpan MaterialTableId => Lane(_v.MaterialTableId, MaterialCapacity); /// 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); @@ -611,19 +743,19 @@ public readonly unsafe struct Box3DSoaView /// public sealed class Box3DSoaWorld : IDisposable { - private const uint ExpectedAbi = 9; + private const uint ExpectedAbi = 10; private nint _handle; /// /// bounds each kind of per-step contact fact (default 4 x capacity; 0 or less is refused); /// is the approach speed in m/s above which a touch is a hit (Box3D's default, 1). /// - public Box3DSoaWorld( + public unsafe Box3DSoaWorld( int capacity, float gravityX = 0f, float gravityY = -10f, float gravityZ = 0f, int jointCapacity = 0, - int? factCapacity = null, float hitThreshold = 1f, - int particleCapacity = 0, int chainCapacity = 0, int attachmentCapacity = 0) + int? factCapacity = null, float hitThreshold = 1f, Box3DSoaParticleCapacities? particles = null) { RequireNativeAbi(Box3DSoaNative.ymir_box3d_soa_get_abi_version()); + static uint Size(uint which) => Box3DSoaNative.ymir_box3d_soa_get_particle_desc_size(which); if (Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || Box3DSoaNative.ymir_box3d_soa_get_body_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || Box3DSoaNative.ymir_box3d_soa_get_joint_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || @@ -631,13 +763,19 @@ public sealed class Box3DSoaWorld : IDisposable 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_chain_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || - Box3DSoaNative.ymir_box3d_soa_get_attachment_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf()) + Size(0) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(1) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(2) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(3) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(4) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(5) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() || + Size(6) != (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, particleCapacity, chainCapacity, attachmentCapacity, out _handle)); + var caps = particles.GetValueOrDefault(); + Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, particles.HasValue ? &caps : null, out _handle)); } /// Fails closed when the native library is not the ABI this build expects, in either direction. @@ -849,95 +987,111 @@ public sealed class Box3DSoaWorld : IDisposable } /// - /// 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. + /// Creates particles in the lowest free lanes and writes their handles to (empty to discard them). + /// Throws for a full world, a bad phase or material index 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) + public unsafe void CreateParticles(ReadOnlySpan particles, Span handles = default) { 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); + if (!handles.IsEmpty && handles.Length < particles.Length) throw new ArgumentException("One handle per particle.", nameof(handles)); + fixed (Box3DSoaParticleDesc* d = particles) + fixed (Box3DSoaParticleHandle* h = handles) + Check(Box3DSoaNative.ymir_box3d_soa_create_particles(_handle, particles.Length, d, handles.IsEmpty ? null : h)); } /// - /// 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. + /// Destroys particles and, with them, every constraint that touches them. Their lanes are tombstones (live 0) reusable once a + /// has completed. A stale handle is refused. /// - public Box3DSoaChainHandle SplitChain(Box3DSoaChainHandle chain, int link, ulong tailStableId) + public unsafe void DestroyParticles(ReadOnlySpan particles) { 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); + fixed (Box3DSoaParticleHandle* h = particles) + Check(Box3DSoaNative.ymir_box3d_soa_destroy_particles(_handle, particles.Length, h)); } - /// - /// 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) + /// Creates distance constraints; may be empty. Throws when the derived tethers would not fit the tether capacity. + public unsafe void CreateDistances(ReadOnlySpan distances, Span handles = default) { ObjectDisposedException.ThrowIf(_handle == 0, this); - Check(Box3DSoaNative.ymir_box3d_soa_destroy_chain(_handle, chain.Lane, chain.Generation)); + if (!handles.IsEmpty && handles.Length < distances.Length) throw new ArgumentException("One handle per distance.", nameof(handles)); + Span native = distances.Length <= 256 ? stackalloc Box3DSoaParticleHandle[distances.Length] : new Box3DSoaParticleHandle[distances.Length]; + fixed (Box3DSoaDistanceDesc* d = distances) + fixed (Box3DSoaParticleHandle* h = native) + Check(Box3DSoaNative.ymir_box3d_soa_create_distances(_handle, distances.Length, d, h)); + for (var i = 0; i < handles.Length && i < native.Length; i++) + handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, native[i].Lane, native[i].Generation); + } + + /// Creates bends over pairs of distances that share one particle; a bend dies with either of its distances. + public unsafe void CreateBends(ReadOnlySpan bends, Span handles = default) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + if (!handles.IsEmpty && handles.Length < bends.Length) throw new ArgumentException("One handle per bend.", nameof(handles)); + Span native = bends.Length <= 256 ? stackalloc Box3DSoaParticleHandle[bends.Length] : new Box3DSoaParticleHandle[bends.Length]; + fixed (Box3DSoaBendDesc* d = bends) + fixed (Box3DSoaParticleHandle* h = native) + Check(Box3DSoaNative.ymir_box3d_soa_create_bends(_handle, bends.Length, d, h)); + for (var i = 0; i < handles.Length && i < native.Length; i++) + handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Bend, native[i].Lane, native[i].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. + /// its frame) or a world point (Static). With the point also bounds every particle of the component by + /// the rest path. 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) + public Box3DSoaConstraintHandle Attach( + Box3DSoaAttachKind kind, Box3DSoaParticleHandle particle, int target = -1, (float X, float Y, float Z) point = default, + float compliance = 0f, bool tether = false) { 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, + Kind = (uint)kind, Flags = tether ? 1u : 0u, 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); + Check(Box3DSoaNative.ymir_box3d_soa_attach(_handle, desc, out var handle)); + return new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Attachment, handle.Lane, handle.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) + /// Removes constraints of one type (a distance takes the bends over it with it). A stale handle is refused. + public unsafe void Remove(ReadOnlySpan constraints) { ObjectDisposedException.ThrowIf(_handle == 0, this); - Check(Box3DSoaNative.ymir_box3d_soa_detach(_handle, attachment.Lane, attachment.Generation)); + if (constraints.IsEmpty) return; + var type = constraints[0].Type; + Span native = constraints.Length <= 256 ? stackalloc Box3DSoaParticleHandle[constraints.Length] : new Box3DSoaParticleHandle[constraints.Length]; + for (var i = 0; i < constraints.Length; i++) + { + if (constraints[i].Type != type) throw new ArgumentException("One type per call.", nameof(constraints)); + native[i] = new Box3DSoaParticleHandle(constraints[i].Lane, constraints[i].Generation); + } + fixed (Box3DSoaParticleHandle* h = native) + Check(Box3DSoaNative.ymir_box3d_soa_remove(_handle, (uint)type, constraints.Length, h)); } - /// 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); } } + /// Removes one constraint. + public void Remove(Box3DSoaConstraintHandle constraint) => Remove([constraint]); + + /// Sets a material table entry: the friction particles of that material have against bodies and the caller's id for it. + public void SetMaterial(int index, float friction, ulong materialId = 0) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + Check(Box3DSoaNative.ymir_box3d_soa_set_material(_handle, index, new Box3DSoaMaterialDesc { Friction = friction, MaterialId = materialId })); + } + + /// Lanes a new particle could take right now (never used, or dead for a step). + public int FreeParticleSlots { get { ObjectDisposedException.ThrowIf(_handle == 0, this); return Box3DSoaNative.ymir_box3d_soa_free_slots(_handle, 0); } } + public int FreeDistanceSlots => FreeSlots(Box3DSoaConstraintType.Distance); + public int FreeBendSlots => FreeSlots(Box3DSoaConstraintType.Bend); + public int FreeAttachmentSlots => FreeSlots(Box3DSoaConstraintType.Attachment); + + private int FreeSlots(Box3DSoaConstraintType type) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + return Box3DSoaNative.ymir_box3d_soa_free_slots(_handle, (uint)type); + } private static Box3DSoaBodyDesc Describe( Box3DSoaKind kind, ulong stableId, (float X, float Y, float Z) position, diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs index e430cfc..c78b82f 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs @@ -3,19 +3,21 @@ using Ymir.Box3D; namespace Ymir.Box3D.Soa.Tests; +using Pos = (float X, float Y, float Z); + /// -/// Chains and bodies coupled inside Box3D's substep (docs/soa-world.md, particle section): a held weight stays held, momentum and -/// energy are kept through a throw and a snap, the sensors read what the structure carries, and a release takes effect in its step. -/// Every reading the tests judge is also appended to the file named by YMIR_READINGS when that variable is set. +/// Particles and bodies coupled inside Box3D's substep (docs/soa-world.md, particle section): a held weight stays held, +/// momentum and energy are kept through a throw and a snap, and a release takes effect in its step. The ropes are built +/// by a test-local builder. Every reading the tests judge is also appended to the file named by YMIR_READINGS when set. /// public sealed class Box3DSoaCouplingTests { - private const float Dt = 1f / 120f; - private const int Sub = 4; + private const float Dt = Box3DSoaParticleTests.Dt; + private const int Sub = Box3DSoaParticleTests.Sub; private const float G = 10f; - private const float ParticleMass = 0.02f; - private const float ParticleRadius = 0.0125f; - private const float Spacing = 0.03f; + private const float ParticleMass = Box3DSoaParticleTests.ParticleMass; + private const float ParticleRadius = Box3DSoaParticleTests.ParticleRadius; + private const float Spacing = Box3DSoaParticleTests.Spacing; private static void Reading(string line) { @@ -24,42 +26,32 @@ public sealed class Box3DSoaCouplingTests } private static string F(double x) => x.ToString("G6", CultureInfo.InvariantCulture); - - private static (float X, float Y, float Z)[] Line((float X, float Y, float Z) from, (float X, float Y, float Z) step, int count) => - Box3DSoaParticleTests.Line(from, step, count); - - private static float Dens(float mass, float radius) => mass / (4f / 3f * MathF.PI * radius * radius * radius); - + private static Pos[] Line(Pos from, Pos step, int count) => Graph.Line(from, step, count); + private static float Dens(float mass, float radius) => Graph.Dens(mass, radius); private static float Sq(float x) => x * x; + private static Box3DSoaWorld World(float gravityX = 0f) => Box3DSoaParticleTests.World(gravityX: gravityX, gravityY: -G); + private static void Run(Box3DSoaWorld world, int steps) => Box3DSoaParticleTests.Run(world, steps); - private static Box3DSoaWorld World(float gravityX = 0f) => - new(8, gravityX: gravityX, gravityY: -G, jointCapacity: 2, particleCapacity: 256, chainCapacity: 8, attachmentCapacity: 8); - - private static void Run(Box3DSoaWorld world, int steps) - { - for (var i = 0; i < steps; i++) world.Step(Dt, Sub); - } - - /// A chain of 48 particles hanging from a static point with a sphere of tied under its end. - private static (int Sphere, Box3DSoaAttachmentHandle Top, Box3DSoaAttachmentHandle Bottom, Box3DSoaChainHandle Chain) Hung( - Box3DSoaWorld world, float mass, float radius = 0.1f, (float X, float Y, float Z) velocity = default) + /// A rope of 48 particles hanging from a static point with a sphere of tied under its end. + internal static (int Sphere, Box3DSoaConstraintHandle Top, Box3DSoaConstraintHandle Bottom, Made Rope) Hung( + Box3DSoaWorld world, float mass, float radius = 0.1f, Pos velocity = default) { var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); - var chain = world.CreateChain(1, positions, ParticleMass, ParticleRadius); - var top = world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + var top = world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); var end = positions[47]; var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius), velocity: velocity); - var bottom = world.Attach(Box3DSoaAttachKind.Body, 47, sphere, (0f, radius, 0f)); - return (sphere, top, bottom, chain); + var bottom = world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); + return (sphere, top, bottom, rope); } - /// Kinetic and potential energy of the chain's particles and of the listed spheres (translation and spin), gravity along -y. + /// Kinetic and potential energy of the particles and of the listed spheres (translation and spin), gravity along -y. private static double Energy(Box3DSoaView v, params (int Lane, float Mass, float Radius)[] spheres) { double e = 0; for (var i = 0; i < v.ParticleCount; i++) { - if (v.ParticleChain[i] < 0 || v.ParticleInvMass[i] <= 0f) continue; + if (v.ParticleLive[i] == 0 || v.ParticleInvMass[i] <= 0f) continue; double m = 1.0 / v.ParticleInvMass[i]; e += 0.5 * m * (Sq(v.ParticleVx[i]) + Sq(v.ParticleVy[i]) + Sq(v.ParticleVz[i])) + m * G * v.ParticleY[i]; } @@ -73,51 +65,18 @@ public sealed class Box3DSoaCouplingTests return e; } - private static double ChainMomentumX(Box3DSoaView v) + private static double ParticleMomentumX(Box3DSoaView v) { double p = 0; for (var i = 0; i < v.ParticleCount; i++) - if (v.ParticleChain[i] >= 0 && v.ParticleInvMass[i] > 0f) p += v.ParticleVx[i] / v.ParticleInvMass[i]; + if (v.ParticleLive[i] != 0 && v.ParticleInvMass[i] > 0f) p += v.ParticleVx[i] / v.ParticleInvMass[i]; return p; } - // ---- holding --------------------------------------------------------------------------------------------- - - [Theory] - [InlineData(1f)] - [InlineData(5f)] - [InlineData(20f)] - [InlineData(70f)] - public void Top_link_tension_reads_the_load(float mass) - { - using var world = World(); - var (sphere, top, bottom, _) = Hung(world, mass); - var view = world.View; - Run(world, 240); - double t0 = 0, t10 = 0, t46 = 0, topForce = 0, bodyForce = 0; - for (var i = 0; i < 60; i++) - { - world.Step(Dt, Sub); - t0 += view.ParticleLinkTension[0]; t10 += view.ParticleLinkTension[10]; t46 += view.ParticleLinkTension[46]; - topForce += view.AttachmentForceY[top.Lane]; bodyForce += view.AttachmentForceY[bottom.Lane]; - } - t0 /= 60; t10 /= 60; t46 /= 60; topForce /= 60; bodyForce /= 60; - double Below(int link) => (mass + (47 - link) * ParticleMass) * G; // the body and every particle past the link - Reading($"TENSION M={mass} link0 {F(t0)}/{F(Below(0))} link10 {F(t10)}/{F(Below(10))} link46 {F(t46)}/{F(Below(46))} body {F(bodyForce)}/{F(-mass * G)} static {F(topForce)}/{F((mass + 48 * ParticleMass) * G)}"); - Assert.True(Math.Abs(t0 - Below(0)) < 0.01 * Below(0), $"link 0 reads {t0} N, load {Below(0)} N"); - Assert.True(Math.Abs(t10 - Below(10)) < 0.01 * Below(10), $"link 10 reads {t10} N, load {Below(10)} N"); - Assert.True(Math.Abs(t46 - Below(46)) < 0.01 * Below(46), $"link 46 reads {t46} N, load {Below(46)} N"); - Assert.True(Math.Abs(bodyForce + mass * G) < 0.005 * mass * G, $"the body's pull on the chain reads {bodyForce} N, weight {mass * G} N"); - var all = (mass + 48 * ParticleMass) * G; - Assert.True(Math.Abs(topForce - all) < 0.01 * all, $"the static point's support reads {topForce} N, load {all} N"); - _ = sphere; - } - [Fact] public void Attached_end_stays_on_its_point() { - // A 1 kg sphere hung under the chain: the end particle is tied to the sphere's top and the sphere is skipped by that - // particle's contacts. A contact that pushed the end particle off its own body would read as a gap. + // The end particle is tied to the sphere's top and skips that sphere in contact. A contact that pushed it off its own body would read as a gap. using var world = World(); var (sphere, _, _, _) = Hung(world, 1f); var view = world.View; @@ -128,13 +87,11 @@ public sealed class Box3DSoaCouplingTests world.Step(Dt, Sub); if (i < 10) continue; float qx = view.RotationX[sphere], qy = view.RotationY[sphere], qz = view.RotationZ[sphere], qw = view.RotationW[sphere]; - // the body point (0, r, 0) rotated by q var tx = 2f * (qy * 0f - qz * radius); var ty = 2f * (qz * 0f - qx * 0f); var tz = 2f * (qx * radius - qy * 0f); var px = view.PositionX[sphere] + qw * tx + (qy * tz - qz * ty); var py = view.PositionY[sphere] + radius + qw * ty + (qz * tx - qx * tz); var pz = view.PositionZ[sphere] + qw * tz + (qx * ty - qy * tx); - var gap = MathF.Sqrt(Sq(view.ParticleX[47] - px) + Sq(view.ParticleY[47] - py) + Sq(view.ParticleZ[47] - pz)); - worst = MathF.Max(worst, gap); + worst = MathF.Max(worst, MathF.Sqrt(Sq(view.ParticleX[47] - px) + Sq(view.ParticleY[47] - py) + Sq(view.ParticleZ[47] - pz))); } Reading($"ATTACHED_END worst gap {F(worst)} m"); Assert.True(worst < 1e-4f, $"the end particle sat {worst} m from its body point"); @@ -143,25 +100,22 @@ public sealed class Box3DSoaCouplingTests [Fact] public void Tethers_hold_the_rest_path() { - // A 70 kg particle at the end of a 48-particle chain from a static point: no particle may be farther from the + // A 70 kg particle at the end of a 48-particle rope from a static point: no particle may be farther from the // attachment than the rest path to it, however the load is routed. using var world = World(); var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); var masses = new float[48]; Array.Fill(masses, ParticleMass); masses[47] = 70f; - world.CreateChain(1, positions, masses, ParticleRadius); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius, masses: masses); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); var view = world.View; var worst = 0f; for (var i = 0; i < 240; i++) { world.Step(Dt, Sub); for (var k = 1; k < 48; k++) - { - var d = MathF.Sqrt(Sq(view.ParticleX[k] - positions[0].X) + Sq(view.ParticleY[k] - positions[0].Y) + Sq(view.ParticleZ[k] - positions[0].Z)); - worst = MathF.Max(worst, d - k * Spacing); - } + worst = MathF.Max(worst, MathF.Sqrt(Sq(view.ParticleX[k] - positions[0].X) + Sq(view.ParticleY[k] - positions[0].Y) + Sq(view.ParticleZ[k] - positions[0].Z)) - k * Spacing); } Reading($"TETHER_BOUND worst overshoot {F(worst)} m"); Assert.True(worst < 1e-5f, $"a particle sits {worst} m past its rest path"); @@ -172,23 +126,21 @@ public sealed class Box3DSoaCouplingTests [Theory] [InlineData(5f)] [InlineData(70f)] - public void Free_chain_throw_keeps_momentum(float mass) + public void Free_throw_keeps_momentum(float mass) { - // A sphere thrown at 5 m/s with a 48 x 20 g chain tied behind it, the chain at rest: gravity acts on y only, so x momentum is - // M x 5 for good, and the chain may only slow the body by picking up speed itself. + // A sphere thrown at 5 m/s with a 48 x 20 g rope tied behind it, the rope at rest: x momentum is M x 5 for good. const float radius = 0.1f; using var world = World(); - var positions = Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48); - world.CreateChain(1, positions, ParticleMass, ParticleRadius); + var rope = Graph.Rope(world, Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius); var sphere = world.AddSphere(10, (radius, 10f, 0f), radius, Dens(mass, radius), velocity: (5f, 0f, 0f)); - world.Attach(Box3DSoaAttachKind.Body, 0, sphere, (-radius, 0f, 0f)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (-radius, 0f, 0f), tether: true); var view = world.View; var floor = 0.95 * mass * 5.0 / (mass + 48 * ParticleMass); double e0 = 0, worstMomentum = 0, worstEnergy = double.MinValue, firstVx = 0; for (var i = 0; i < 240; i++) { world.Step(Dt, Sub); - var momentum = mass * view.VelocityX[sphere] + ChainMomentumX(view); + var momentum = mass * view.VelocityX[sphere] + ParticleMomentumX(view); var energy = Energy(view, (sphere, mass, radius)); if (i == 0) { e0 = energy; firstVx = view.VelocityX[sphere]; } worstMomentum = Math.Max(worstMomentum, Math.Abs(momentum - mass * 5.0) / (mass * 5.0)); @@ -207,10 +159,9 @@ public sealed class Box3DSoaCouplingTests { const float radius = 0.1f; using var world = World(); - var positions = Line((0f, 10f - radius, 0f), (0f, -Spacing, 0f), 48); // hangs below the body - world.CreateChain(1, positions, ParticleMass, ParticleRadius); + var rope = Graph.Rope(world, Line((0f, 10f - radius, 0f), (0f, -Spacing, 0f), 48), ParticleMass, ParticleRadius); // hangs below the body var sphere = world.AddSphere(10, (0f, 10f, 0f), radius, Dens(mass, radius), velocity: (0f, 5f, 0f)); - world.Attach(Box3DSoaAttachKind.Body, 0, sphere, (0f, -radius, 0f)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (0f, -radius, 0f), tether: true); var view = world.View; var apex = 10f; for (var i = 0; i < 240; i++) @@ -218,7 +169,7 @@ public sealed class Box3DSoaCouplingTests world.Step(Dt, Sub); apex = MathF.Max(apex, view.PositionY[sphere]); } - // The body alone would rise 1.25 m; the chain it picks up from rest takes the momentum it needs. + // The body alone would rise 1.25 m; the rope it picks up from rest takes the momentum it needs. var ratio = mass / (mass + 48 * ParticleMass); var expected = 10f + 1.25f * ratio * ratio; Reading($"THROW_UP M={mass} apex {F(apex)} expected {F(expected)}"); @@ -253,7 +204,7 @@ public sealed class Box3DSoaCouplingTests [Fact] public void Pendulum_gains_no_energy() { - // A 45 degree swing for 12 s, the weight as a tied body and as a heavy particle at the chain's end (the control the + // A 45 degree swing for 12 s, the weight as a tied body and as a heavy particle at the rope's end (the control the // solver is known to damp): the body must lose no less than nothing and no more than 1.25 times the control. const float radius = 0.05f; foreach (var mass in new[] { 5f, 70f }) @@ -267,14 +218,14 @@ public sealed class Box3DSoaCouplingTests var masses = new float[48]; Array.Fill(masses, ParticleMass); if (!asBody) masses[47] = mass; - world.CreateChain(1, positions, masses, ParticleRadius); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius, masses: masses); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); (int, float, float)[] bodies = []; if (asBody) { var end = positions[47]; var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius)); - world.Attach(Box3DSoaAttachKind.Body, 47, sphere, (0f, radius, 0f)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); bodies = [(sphere, mass, radius)]; } var view = world.View; @@ -303,13 +254,13 @@ public sealed class Box3DSoaCouplingTests const float radius = 0.05f, mass = 5f; using var world = World(); var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); - world.CreateChain(1, positions, ParticleMass, ParticleRadius); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); var end = positions[47]; var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius)); - world.Attach(Box3DSoaAttachKind.Body, 47, sphere, (0f, radius, 0f)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); var inertia = 0.4f * mass * radius * radius; - (float X, float Y, float Z) centre = (end.X, end.Y - radius, end.Z); + Pos centre = (end.X, end.Y - radius, end.Z); world.ApplyImpulse(sphere, (0f, 0f, 30f * inertia / radius), (centre.X + radius, centre.Y, centre.Z)); // a couple about -y: omega_y = -30 world.ApplyImpulse(sphere, (0f, 0f, -30f * inertia / radius), centre); var view = world.View; @@ -325,13 +276,13 @@ public sealed class Box3DSoaCouplingTests [Theory] [InlineData(false)] [InlineData(true)] - public void Detach_releases_in_step(bool destroyChain) + public void Release_takes_effect_in_step(bool destroyParticles) { using var world = World(); - var (sphere, _, bottom, chain) = Hung(world, 70f); + var (sphere, _, bottom, rope) = Hung(world, 70f); var view = world.View; Run(world, 3 * 120); - if (destroyChain) world.DestroyChain(chain); else world.Detach(bottom); + if (destroyParticles) world.DestroyParticles(rope.Particles); else world.Remove(bottom); var worst = 0f; var impulse = float.MinValue; for (var k = 1; k <= 4; k++) @@ -340,15 +291,15 @@ public sealed class Box3DSoaCouplingTests worst = MathF.Max(worst, MathF.Abs(view.VelocityY[sphere] - (-G * Dt * k))); impulse = MathF.Max(impulse, view.ParticleImpulseY[sphere]); } - Reading($"RELEASE destroyChain={destroyChain} worst vy error {F(worst)} m/s, greatest impulse Y {F(impulse)}"); + Reading($"RELEASE destroyParticles={destroyParticles} worst vy error {F(worst)} m/s, greatest impulse Y {F(impulse)}"); Assert.True(worst < 0.005f, $"the body is {worst} m/s off free fall in the step after the command"); - Assert.True(impulse <= 0f, $"the released chain still pushed the body up by {impulse} N s"); + Assert.True(impulse <= 0f, $"the released rope still pushed the body up by {impulse} N s"); } [Fact] public void Particle_impulse_is_what_Box3D_applied() { - // M (v_after - v_before) - M g dt is, per axis, the impulse the chain gave the body this tick: the lane reads exactly that. + // M (v_after - v_before) - M g dt is, per axis, the impulse the particles gave the body this tick: the lane reads exactly that. const float radius = 0.1f; foreach (var thrown in new[] { false, true }) { @@ -358,10 +309,9 @@ public sealed class Box3DSoaCouplingTests if (!thrown) sphere = Hung(world, mass).Sphere; else { - var positions = Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48); - world.CreateChain(1, positions, ParticleMass, ParticleRadius); + var rope = Graph.Rope(world, Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius); sphere = world.AddSphere(10, (radius, 10f, 0f), radius, Dens(mass, radius), velocity: (5f, 0f, 0f)); - world.Attach(Box3DSoaAttachKind.Body, 0, sphere, (-radius, 0f, 0f)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (-radius, 0f, 0f), tether: true); } var view = world.View; var (vx, vy, vz) = (view.VelocityX[sphere], view.VelocityY[sphere], view.VelocityZ[sphere]); @@ -380,23 +330,24 @@ public sealed class Box3DSoaCouplingTests } } - // ---- bodies and chains without the pull ---------------------------------------------------------------------- + // ---- bodies and particles without the pull ------------------------------------------------------------------- [Theory] [InlineData(0.6f, true)] [InlineData(0f, false)] - public void Chain_friction_holds_on_a_slope(float friction, bool holds) + public void Material_friction_holds_on_a_slope(float friction, bool holds) { - // Gravity tilted 20 degrees on a chain lying on a static box: friction 0.6 (above tan 20) holds it, friction 0 lets it go. + // Gravity tilted 20 degrees on a rope lying on a static box: friction 0.6 (above tan 20) holds it, friction 0 lets it go. var tilt = 20f * MathF.PI / 180f; using var world = World(gravityX: G * MathF.Sin(tilt)); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f); - world.CreateChain(1, Line((0f, ParticleRadius, 0f), (0f, 0f, Spacing), 12), ParticleMass, ParticleRadius, friction: friction); + world.SetMaterial(0, friction); + var rope = Graph.Rope(world, Line((0f, ParticleRadius, 0f), (0f, 0f, Spacing), 12), ParticleMass, ParticleRadius); var view = world.View; Run(world, 2 * 120); - var slid = MathF.Abs(view.ParticleX[6]); + var slid = MathF.Abs(view.ParticleX[rope.Particles[6]]); Reading($"SLOPE mu={friction} slid {F(slid)} m in 2 s"); - if (holds) Assert.True(slid < 0.01f, $"friction {friction} let the chain slide {slid} m"); + if (holds) Assert.True(slid < 0.01f, $"friction {friction} let the rope slide {slid} m"); else Assert.True(slid > 1f, $"friction 0 slid only {slid} m"); } @@ -406,15 +357,15 @@ public sealed class Box3DSoaCouplingTests // Box3D returns early from a world with nothing awake; the particle substeps run all the same. using var world = World(); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f)); - world.CreateChain(1, Line((0f, 1f, 0f), (0f, 0f, Spacing), 8), ParticleMass, ParticleRadius); + var rope = Graph.Rope(world, Line((0f, 1f, 0f), (0f, 0f, Spacing), 8), ParticleMass, ParticleRadius); var view = world.View; Run(world, 24); // 0.2 s - var fell = 1f - view.ParticleY[3]; + var fell = 1f - view.ParticleY[rope.Particles[3]]; Reading($"NO_AWAKE fell {F(fell)} m in 0.2 s (g t^2 / 2 = 0.2)"); - Assert.True(MathF.Abs(fell - 0.2f) < 0.02f * 0.2f, $"the chain fell {fell} m, expected 0.2 m"); + Assert.True(MathF.Abs(fell - 0.2f) < 0.02f * 0.2f, $"the rope fell {fell} m, expected 0.2 m"); Run(world, 4 * 120); - Assert.Equal(ParticleRadius, view.ParticleY[3], 1e-3f); - Assert.True(MathF.Abs(view.ParticleVy[3]) < 1e-3f, "the chain rests on the box"); + Assert.Equal(ParticleRadius, view.ParticleY[rope.Particles[3]], 1e-3f); + Assert.True(MathF.Abs(view.ParticleVy[rope.Particles[3]]) < 1e-3f, "the rope rests on the box"); } // ---- cost --------------------------------------------------------------------------------------------------- @@ -424,16 +375,17 @@ public sealed class Box3DSoaCouplingTests [InlineData(40)] public void Particle_cost_line(int bodies) { - using var world = new Box3DSoaWorld(64, gravityY: -G, particleCapacity: 16 * 48, chainCapacity: 16, attachmentCapacity: 16); + using var world = new Box3DSoaWorld(64, gravityY: -G, particles: new Box3DSoaParticleCapacities(16 * 48 + 256, 16 * 47 + 480, 16 * 46 + 448, 16, 600, 1)); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f)); for (var b = 1; b < bodies; b++) world.AddSphere((ulong)(100 + b), (0.2f * (b % 8), 0.3f + 0.25f * (b / 8), 0.5f), 0.08f, 800f); - for (var c = 0; c < 16; c++) // a pile: chains zig-zag so particles meet their neighbours' links - world.CreateChain((ulong)(10 + c), Line((0f, 0.5f + 0.03f * c, 0.02f * (c % 4)), (Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius); + for (var c = 0; c < 16; c++) // a pile: ropes zig-zag so particles meet their neighbours' links + Graph.Rope(world, Line((0f, 0.5f + 0.03f * c, 0.02f * (c % 4)), (Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius, Box3DSoaPhase.Of((uint)(c + 1), true, true)); + Graph.Sheet(world, (0.2f, 1.2f, 0f), (0.03f, 0f, 0f), (0f, 0f, 0.03f), 16, 16, ParticleMass, ParticleRadius, Box3DSoaPhase.Of(99, true, true)); Run(world, 60); var watch = System.Diagnostics.Stopwatch.StartNew(); Run(world, 240); - var line = $"PARTICLE_COST 16 chains x 48 particles, 4 substeps, {bodies} bod{(bodies == 1 ? "y" : "ies")}: {watch.Elapsed.TotalMilliseconds / 240:F3} ms per tick"; + var line = $"PARTICLE_COST 16 ropes x 48 and one 16 x 16 sheet, 4 substeps, {bodies} bod{(bodies == 1 ? "y" : "ies")}: {watch.Elapsed.TotalMilliseconds / 240:F3} ms per tick"; Console.Error.WriteLine(line); Reading(line); Assert.True(watch.Elapsed.TotalMilliseconds > 0); diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs index 0537008..1fcdfc4 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(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 + Assert.Equal(10u, Box3DSoaNative.ymir_box3d_soa_get_abi_version()); + Box3DSoaWorld.RequireNativeAbi(10); + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(9)); // an older native under this managed build + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(11)); // a newer one } [Fact] diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs new file mode 100644 index 0000000..9b5509a --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs @@ -0,0 +1,93 @@ +using Ymir.Box3D; + +namespace Ymir.Box3D.Soa.Tests; + +using Pos = (float X, float Y, float Z); + +/// What a builder made: the particles, the distances between them and the bends over pairs of distances. +internal sealed record Made(Box3DSoaParticleHandle[] Particles, Box3DSoaConstraintHandle[] Edges, Box3DSoaConstraintHandle[] Bends); + +/// +/// Test-local builders. Ymir has no rope or sheet: both are only the constraints these functions emit through the +/// public commands, so the tests exercise exactly the surface a game would. +/// +internal static class Graph +{ + public static Pos[] Line(Pos from, Pos step, int count) + { + var p = new Pos[count]; + for (var i = 0; i < count; i++) p[i] = (from.X + step.X * i, from.Y + step.Y * i, from.Z + step.Z * i); + return p; + } + + /// Particles at (rest pose or the same), a distance between neighbours and a bend over each pair of distances. + public static Made Rope( + Box3DSoaWorld world, Pos[] positions, float mass, float radius, uint phase = 0, float stretch = 0f, float bend = 1e-4f, + float maxAngle = -1f, Pos[]? rest = null, float[]? masses = null, Pos velocity = default, uint material = 0) + { + var n = positions.Length; + var desc = new Box3DSoaParticleDesc[n]; + for (var i = 0; i < n; i++) + desc[i] = new Box3DSoaParticleDesc(positions[i], masses?[i] ?? mass, radius, phase, material, rest?[i], velocity); + var particles = new Box3DSoaParticleHandle[n]; + world.CreateParticles(desc, particles); + var edges = new Box3DSoaConstraintHandle[n - 1]; + var d = new Box3DSoaDistanceDesc[n - 1]; + for (var i = 0; i + 1 < n; i++) d[i] = new Box3DSoaDistanceDesc(particles[i], particles[i + 1], stretch); + world.CreateDistances(d, edges); + var bends = Array.Empty(); + if (bend >= 0f || maxAngle >= 0f) + { + bends = new Box3DSoaConstraintHandle[Math.Max(0, n - 2)]; + var b = new Box3DSoaBendDesc[bends.Length]; + for (var i = 0; i + 2 < n; i++) b[i] = new Box3DSoaBendDesc(edges[i], edges[i + 1], bend, maxAngle); + world.CreateBends(b, bends); + } + return new Made(particles, edges, bends); + } + + /// An x grid: distances along both axes, bends along both. + public static Made Sheet( + Box3DSoaWorld world, Pos origin, Pos du, Pos dv, int nu, int nv, float mass, float radius, uint phase = 0, + float stretch = 0f, float bend = 1e-4f) + { + var desc = new Box3DSoaParticleDesc[nu * nv]; + for (var j = 0; j < nv; j++) + for (var i = 0; i < nu; i++) + desc[j * nu + i] = new Box3DSoaParticleDesc( + (origin.X + du.X * i + dv.X * j, origin.Y + du.Y * i + dv.Y * j, origin.Z + du.Z * i + dv.Z * j), mass, radius, phase); + var p = new Box3DSoaParticleHandle[nu * nv]; + world.CreateParticles(desc, p); + var d = new List(); + for (var j = 0; j < nv; j++) for (var i = 0; i + 1 < nu; i++) d.Add(new(p[j * nu + i], p[j * nu + i + 1], stretch)); + var uCount = d.Count; + for (var j = 0; j + 1 < nv; j++) for (var i = 0; i < nu; i++) d.Add(new(p[j * nu + i], p[(j + 1) * nu + i], stretch)); + var e = new Box3DSoaConstraintHandle[d.Count]; + world.CreateDistances(d.ToArray(), e); + var b = new List(); + for (var j = 0; j < nv; j++) for (var i = 0; i + 2 < nu; i++) b.Add(new(e[j * (nu - 1) + i], e[j * (nu - 1) + i + 1], bend)); + for (var j = 0; j + 2 < nv; j++) for (var i = 0; i < nu; i++) b.Add(new(e[uCount + j * nu + i], e[uCount + (j + 1) * nu + i], bend)); + var bends = new Box3DSoaConstraintHandle[b.Count]; + world.CreateBends(b.ToArray(), bends); + return new Made(p, e, bends); + } + + public static float Dist(Box3DSoaView v, int a, int b) => + MathF.Sqrt(Sq(v.ParticleX[a] - v.ParticleX[b]) + Sq(v.ParticleY[a] - v.ParticleY[b]) + Sq(v.ParticleZ[a] - v.ParticleZ[b])); + + public static float Sq(float x) => x * x; + + /// The summed length of the given distances over their summed rest lengths, minus 1. + public static float Stretch(Box3DSoaView v, Made m) + { + float length = 0f, rest = 0f; + foreach (var e in m.Edges) + { + length += Dist(v, v.DistanceA[e.Lane], v.DistanceB[e.Lane]); + rest += v.DistanceRest[e.Lane]; + } + return length / rest - 1f; + } + + public static float Dens(float mass, float radius) => mass / (4f / 3f * MathF.PI * radius * radius * radius); +} diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs index 8e42625..b048f9c 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs @@ -1,13 +1,19 @@ using System.Runtime.InteropServices; +using System.Text.RegularExpressions; using Ymir.Box3D; namespace Ymir.Box3D.Soa.Tests; -/// Particle chains and attachments: the contract of docs/soa-world.md, particle section. +using Pos = (float X, float Y, float Z); + +/// The particle graph: the contract of docs/soa-world.md, particle section. public sealed class Box3DSoaParticleTests { - private const float Dt = 1f / 120f; - private const int Sub = 4; + internal const float Dt = 1f / 120f; + internal const int Sub = 4; + internal const float Spacing = 0.03f; + internal const float ParticleMass = 0.02f; + internal const float ParticleRadius = 0.0125f; private static ulong Fnv(ulong h, ReadOnlySpan bytes) { @@ -59,106 +65,83 @@ public sealed class Box3DSoaParticleTests // ---- scenes --------------------------------------------------------------------------------------------- - private const float Spacing = 0.03f; - private const float ParticleMass = 0.02f; - private const float ParticleRadius = 0.0125f; + internal static Box3DSoaWorld World( + int bodies = 8, int particles = 256, int distances = 600, int bends = 600, int attachments = 8, int tethers = 600, int joints = 2, + float gravityX = 0f, float gravityY = -10f) => + new(bodies, gravityX: gravityX, gravityY: gravityY, jointCapacity: joints, + particles: new Box3DSoaParticleCapacities(particles, distances, bends, attachments, tethers, 2)); - private static Box3DSoaWorld World(int bodies = 8, int particles = 256, int chains = 8, int attachments = 8, int joints = 2) => - new(bodies, gravityY: -10f, jointCapacity: joints, particleCapacity: particles, chainCapacity: chains, attachmentCapacity: attachments); - - internal static (float X, float Y, float Z)[] Line((float X, float Y, float Z) from, (float X, float Y, float Z) step, int count) - { - var p = new (float, float, float)[count]; - for (var i = 0; i < count; i++) p[i] = (from.X + step.X * i, from.Y + step.Y * i, from.Z + step.Z * i); - return p; - } - - private static float Dist(Box3DSoaView v, int a, int b) => - MathF.Sqrt(Sq(v.ParticleX[a] - v.ParticleX[b]) + Sq(v.ParticleY[a] - v.ParticleY[b]) + Sq(v.ParticleZ[a] - v.ParticleZ[b])); - - private static float Sq(float x) => x * x; - - /// Total link length of a chain over its rest length, minus 1. - private static float Stretch(Box3DSoaView v, Box3DSoaChainHandle chain, float restLength) - { - var first = v.ChainFirst[chain.Lane]; - var last = first + v.ChainSize[chain.Lane]; - var length = 0f; - for (var i = first; i + 1 < last; i++) length += Dist(v, i, i + 1); - return length / restLength - 1f; - } - - private static void Run(Box3DSoaWorld world, int steps) + internal static void Run(Box3DSoaWorld world, int steps) { for (var i = 0; i < steps; i++) world.Step(Dt, Sub); } - private static float SphereDensity(float mass, float radius) => mass / (4f / 3f * MathF.PI * radius * radius * radius); + private static Pos[] Line(Pos from, Pos step, int count) => Graph.Line(from, step, count); + private static float Sq(float x) => x * x; // ---- behaviour ------------------------------------------------------------------------------------------ [Fact] - public void Chain_hangs_near_rest_length() + public void Rope_hangs_near_rest_length() { using var world = World(); var positions = Line((0f, 3f, 0f), (0f, -Spacing, 0f), 48); - var chain = world.CreateChain(1, positions, ParticleMass, ParticleRadius); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); var view = world.View; - var rest = 47 * Spacing; var worst = 0f; for (var i = 0; i < 4 * 120; i++) { world.Step(Dt, Sub); - worst = MathF.Max(worst, MathF.Abs(Stretch(view, chain, rest))); + worst = MathF.Max(worst, MathF.Abs(Graph.Stretch(view, rope))); } Assert.True(worst < 0.01f, $"stretch peaked at {worst}"); - Assert.Equal(3f - rest, view.ParticleY[47], 0.05f); // it hangs, not sags to the side or floats + Assert.Equal(3f - 47 * Spacing, view.ParticleY[47], 0.05f); // it hangs, not sags to the side or floats Assert.Equal(0f, view.ParticleX[47], 0.05f); } [Fact] - public void Chain_holds_a_70kg_body() + public void Rope_holds_a_70kg_body() { using var world = World(); var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); - var chain = world.CreateChain(1, positions, ParticleMass, ParticleRadius); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); const float radius = 0.15f, mass = 70f; var end = positions[47]; - var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, SphereDensity(mass, radius)); - world.Attach(Box3DSoaAttachKind.Body, 47, sphere, (0f, radius, 0f)); + var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Graph.Dens(mass, radius)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); var view = world.View; - var rest = 47 * Spacing; float worstStretch = 0f, worstSpeed = 0f, worstImpulse = 0f; for (var i = 0; i < 5 * 120; i++) { world.Step(Dt, Sub); if (i < 120) continue; // from 1 s to 5 s the body is still - worstStretch = MathF.Max(worstStretch, MathF.Abs(Stretch(view, chain, rest))); + worstStretch = MathF.Max(worstStretch, MathF.Abs(Graph.Stretch(view, rope))); worstSpeed = MathF.Max(worstSpeed, MathF.Sqrt(Sq(view.VelocityX[sphere]) + Sq(view.VelocityY[sphere]) + Sq(view.VelocityZ[sphere]))); worstImpulse = MathF.Max(worstImpulse, MathF.Abs(view.ParticleImpulseY[sphere] - mass * 10f * Dt)); } Assert.True(worstStretch < 0.001f, $"stretch peaked at {worstStretch}"); Assert.True(worstSpeed < 0.001f, $"the body moves at {worstSpeed} m/s"); - Assert.True(worstImpulse < 0.005f * mass * 10f * Dt, $"the impulse per tick strays {worstImpulse} N s from M g dt = {mass * 10f * Dt}"); // the body is held, so the chain gives exactly its weight + Assert.True(worstImpulse < 0.005f * mass * 10f * Dt, $"the impulse per tick strays {worstImpulse} N s from M g dt = {mass * 10f * Dt}"); Assert.Equal(end.Y - radius, view.PositionY[sphere], 0.1f); } [Fact] - public void Chain_drags_a_resting_box() + public void Rope_drags_a_resting_box() { using var world = World(); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f); + world.SetMaterial(0, 0.3f); const float half = 0.15f; var count = 29; var positions = Line((0f, ParticleRadius, 0f), (Spacing, 0f, 0f), count); var tip = positions[count - 1]; var box = world.AddBox(2, (tip.X + half, half, 0f), (half, half, half), 5f / (8f * half * half * half), friction: 0.6f); var anchor = world.AddAnchor(3, positions[0]); - world.CreateChain(1, positions, ParticleMass, ParticleRadius, friction: 0.3f); - world.Attach(Box3DSoaAttachKind.Body, 0, anchor); - world.Attach(Box3DSoaAttachKind.Body, count - 1, box, (-half, ParticleRadius - half, 0f)); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], anchor, tether: true); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[count - 1], box, (-half, ParticleRadius - half, 0f), tether: true); var view = world.View; var startX = view.PositionX[box]; var peak = 0f; @@ -177,7 +160,7 @@ public sealed class Box3DSoaParticleTests { var px = v.ParticleX[i] - v.PositionX[b]; var py = v.ParticleY[i] - v.PositionY[b]; var pz = v.ParticleZ[i] - v.PositionZ[b]; float qx = v.RotationX[b], qy = v.RotationY[b], qz = v.RotationZ[b], qw = v.RotationW[b]; - (float X, float Y, float Z) Rot(float x, float y, float z, float s) // rotate by q (s = 1) or its inverse (s = -1) + Pos Rot(float x, float y, float z, float s) // rotate by q (s = 1) or its inverse (s = -1) { var ux = qx * s; var uy = qy * s; var uz = qz * s; var tx = 2f * (uy * z - uz * y); var ty = 2f * (uz * x - ux * z); var tz = 2f * (ux * y - uy * x); @@ -211,9 +194,9 @@ public sealed class Box3DSoaParticleTests { using var world = World(); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f); - var positions = Line((0f, ParticleRadius, 0f), (Spacing, 0f, 0f), 12); - world.CreateChain(1, positions, ParticleMass, ParticleRadius, friction: 0.3f); - // The body starts half a particle radius into the chain's end and, if it moves, is pushed on into it. + world.SetMaterial(0, 0.3f); + Graph.Rope(world, Line((0f, ParticleRadius, 0f), (Spacing, 0f, 0f), 12), ParticleMass, ParticleRadius); + // The body starts half a particle radius into the rope's end and, if it moves, is pushed on into it. var x0 = -0.05f - 0.5f * ParticleRadius; var body = kind switch { @@ -226,122 +209,383 @@ public sealed class Box3DSoaParticleTests var worst = 0f; for (var step = 0; step < 120; step++) { - if (kind != Box3DSoaKind.StaticBox) view.ForceX[body] = 6f; // pushes into the chain + if (kind != Box3DSoaKind.StaticBox) view.ForceX[body] = 6f; // pushes into the rope world.Step(Dt, Sub); if (step >= 60) for (var i = 0; i < 12; i++) worst = MathF.Max(worst, Penetration(view, body, i)); } Assert.True(worst < 0.1f * ParticleRadius, $"{kind}: a particle sits {worst / ParticleRadius:P0} of its radius inside the body"); - Assert.True(view.ParticleX[0] > positions[0].X + 0.001f, $"{kind}: the chain end was pushed on"); // the contact acted, it was not merely clear + Assert.True(view.ParticleX[0] > 0.001f, $"{kind}: the rope end was pushed on"); } [Fact] - public void Overload_never_splits() + public void Sheet_and_rope_are_one_code_path() + { + // A 16 x 16 sheet hung by two corners, made by a test-local builder out of the same distances and bends a rope uses. + using var world = World(particles: 256, distances: 512, bends: 512, tethers: 1024); + const float sp = 0.04f; + var sheet = Graph.Sheet(world, (0f, 2f, 0f), (sp, 0f, 0f), (0f, -sp, 0f), 16, 16, ParticleMass, 0.02f, bend: 1e-4f); + world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[0], point: (0f, 2f, 0f), tether: true); + world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[15], point: (15 * sp, 2f, 0f), tether: true); + var view = world.View; + Run(world, 5 * 120); + double fy = 0; + for (var a = 0; a < 2; a++) fy += view.AttachmentForceY[a]; + var weight = 256 * ParticleMass * 10.0; + Assert.True(Math.Abs(fy - weight) < 0.01 * weight, $"the corners carry {fy} N of {weight} N"); + var maxStretch = 0f; + foreach (var e in sheet.Edges) maxStretch = MathF.Max(maxStretch, MathF.Abs(Graph.Dist(view, view.DistanceA[e.Lane], view.DistanceB[e.Lane]) / view.DistanceRest[e.Lane] - 1f)); + Assert.True(maxStretch < 0.05f, $"an edge stretched by {maxStretch}"); + } + + [Theory] + [InlineData(1f)] + [InlineData(5f)] + [InlineData(20f)] + [InlineData(70f)] + public void Edge_tension_reads_the_load(float mass) + { + using var world = World(); + var (_, top, bottom, rope) = Box3DSoaCouplingTests.Hung(world, mass); + var view = world.View; + Run(world, 240); + double t0 = 0, t10 = 0, t46 = 0, topForce = 0, bodyForce = 0; + for (var i = 0; i < 60; i++) + { + world.Step(Dt, Sub); + t0 += view.DistanceTension[rope.Edges[0].Lane]; t10 += view.DistanceTension[rope.Edges[10].Lane]; t46 += view.DistanceTension[rope.Edges[46].Lane]; + topForce += view.AttachmentForceY[top.Lane]; bodyForce += view.AttachmentForceY[bottom.Lane]; + } + t0 /= 60; t10 /= 60; t46 /= 60; topForce /= 60; bodyForce /= 60; + double Below(int edge) => (mass + (47 - edge) * ParticleMass) * 10.0; + Assert.True(Math.Abs(t0 - Below(0)) < 0.01 * Below(0), $"edge 0 reads {t0} N, load {Below(0)} N"); + Assert.True(Math.Abs(t10 - Below(10)) < 0.01 * Below(10), $"edge 10 reads {t10} N, load {Below(10)} N"); + Assert.True(Math.Abs(t46 - Below(46)) < 0.01 * Below(46), $"edge 46 reads {t46} N, load {Below(46)} N"); + Assert.True(Math.Abs(bodyForce + mass * 10.0) < 0.005 * mass * 10.0, $"the body's pull reads {bodyForce} N, weight {mass * 10.0} N"); + var all = (mass + 48 * ParticleMass) * 10.0; + Assert.True(Math.Abs(topForce - all) < 0.01 * all, $"the static point's support reads {topForce} N, load {all} N"); + } + + [Fact] + public void Cut_removes_bends_and_rederives_tethers() + { + using var world = World(); + var positions = Line((0f, 4f, 0f), (0f, -Spacing, 0f), 40); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); + var view = world.View; + Assert.Equal(39, view.TetherCount); + Assert.True(view.ParticleComponent[..40].ToArray().All(c => c == 0)); + Run(world, 60); + world.Remove(rope.Edges[19]); + Assert.Equal(19, world.View.TetherCount); + Assert.Equal(0u, view.DistanceLive[19]); + Assert.Equal(0u, view.BendLive[18]); // the two bends over edge 19 died with it + Assert.Equal(0u, view.BendLive[19]); + Assert.Equal(1u, view.BendLive[17]); + Assert.Equal(0, view.ParticleComponent[19]); + Assert.Equal(20, view.ParticleComponent[20]); // the tail is its own component, named by its lowest lane + Assert.Equal(20, view.ParticleComponent[39]); + Run(world, 120); + Assert.True(view.ParticleY[19] > 4f - 19 * Spacing - 0.1f, "the head holds"); + Assert.True(view.ParticleY[39] < 4f - 39 * Spacing - 2f, "the tail falls"); + double top = 0; + for (var i = 0; i < 30; i++) { world.Step(Dt, Sub); top += view.DistanceTension[rope.Edges[0].Lane]; } + top /= 30; + var load = 19 * ParticleMass * 10.0; + Assert.True(Math.Abs(top - load) < 0.01 * load, $"the top edge reads {top} N, the load below it is {load} N"); + } + + [Fact] + public void Overload_never_removes_a_constraint() { using var world = World(); var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); - var chain = world.CreateChain(1, positions, ParticleMass, ParticleRadius, materialId: 7); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); const float radius = 0.2f; var end = positions[47]; - var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, SphereDensity(300f, radius)); - world.Attach(Box3DSoaAttachKind.Body, 47, sphere, (0f, radius, 0f)); + var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Graph.Dens(300f, radius)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); var view = world.View; Run(world, 3 * 120); var tension = 0f; - for (var i = 0; i < 47; i++) tension = MathF.Max(tension, view.ParticleLinkTension[i]); + foreach (var e in rope.Edges) tension = MathF.Max(tension, view.DistanceTension[e.Lane]); Assert.True(tension > 1000f, $"the load is read: {tension} N"); // 300 kg: far past any strength a material would give it - Assert.Equal(1, view.ChainCount); - Assert.Equal((uint)Box3DSoaChainKind.Live, view.ChainKind[chain.Lane]); - Assert.Equal(48, view.ChainSize[chain.Lane]); - for (var i = 0; i < 48; i++) Assert.Equal(chain.Lane, view.ParticleChain[i]); - Assert.Equal(1, world.SplitChain(chain, 20, 2).Lane); // only the command splits it + for (var i = 0; i < 47; i++) Assert.Equal(1u, view.DistanceLive[i]); + for (var i = 0; i < 46; i++) Assert.Equal(1u, view.BendLive[i]); + for (var i = 0; i < 48; i++) Assert.Equal(1u, view.ParticleLive[i]); + Assert.Equal(2, view.AttachmentCount); + world.Remove(rope.Edges[20]); // only the command cuts + Assert.Equal(0u, view.DistanceLive[20]); } [Fact] - public void Split_keeps_lanes() + public void Destroy_particles_removes_their_constraints() { using var world = World(); - var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 10); - var chain = world.CreateChain(11, positions, ParticleMass, ParticleRadius, materialId: 5); - world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); + var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48); + var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); + const float radius = 0.15f, mass = 70f; + var end = positions[47]; + var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Graph.Dens(mass, radius)); + world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true); var view = world.View; - Run(world, 60); - var before = (view.ParticleY.ToArray(), view.ParticleX.ToArray()); - var addressBefore = ParticleLaneAddress(view); - var tail = world.SplitChain(chain, 4, 99); - view = world.View; - Assert.Equal(addressBefore, ParticleLaneAddress(view)); // no particle changes address - Assert.True(before.Item1.AsSpan().SequenceEqual(view.ParticleY) && before.Item2.AsSpan().SequenceEqual(view.ParticleX), "no particle moved"); - Assert.Equal(11ul, view.ChainStableId[chain.Lane]); - Assert.Equal(99ul, view.ChainStableId[tail.Lane]); - Assert.Equal(5, view.ChainSize[chain.Lane]); - Assert.Equal(5, view.ChainSize[tail.Lane]); - Assert.Equal(5, view.ChainFirst[tail.Lane]); - Assert.Equal(5ul, view.ChainMaterialId[tail.Lane]); - for (var i = 0; i < 10; i++) Assert.Equal(i < 5 ? chain.Lane : tail.Lane, view.ParticleChain[i]); - var tailY = view.ParticleY[9]; - Run(world, 120); - Assert.True(tailY - view.ParticleY[9] > 1.5f, "the tail falls free"); // 0.5 g t^2 = 5 m, less the settling - Assert.True(view.ParticleY[4] > 4.5f, "the head still hangs"); + Run(world, 2 * 120); + Assert.True(MathF.Abs(view.VelocityY[sphere]) < 0.001f, "held"); + world.DestroyParticles([rope.Particles[24]]); + Assert.Equal(0u, view.ParticleLive[24]); + Assert.Equal(0u, view.DistanceLive[23]); // its two distances + Assert.Equal(0u, view.DistanceLive[24]); + foreach (var k in new[] { 22, 23, 24 }) Assert.Equal(0u, view.BendLive[k]); // the bends over them + Assert.Equal(1u, view.BendLive[21]); + Assert.Equal(23 + 22, world.View.TetherCount); // the head 1..23 bound by the static point, the tail 25..46 by the body at 47 + Run(world, 1); + Assert.True(view.VelocityY[sphere] < -0.05f, $"the held body fell the step after: vy {view.VelocityY[sphere]}"); } - private static unsafe nint ParticleLaneAddress(Box3DSoaView v) + [Theory] + [InlineData(32)] + public void Soft_bend_and_hard_limit_one_constraint(int substeps) { - fixed (float* p = v.ParticleX) return (nint)p; + // A 24-particle cantilever held at both of its first particles: the soft pass alone, the hard limit alone and both. + (float Drop, float Defl) Cantilever(float compliance, float limitDeg) + { + using var world = World(gravityY: -9.81f); + var positions = Line((0f, 1f, 0f), (0.04f, 0f, 0f), 24); + var rope = Graph.Rope(world, positions, ParticleMass, 0.02f, bend: compliance, maxAngle: limitDeg < 0 ? -1f : limitDeg * MathF.PI / 180f); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0]); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[1], point: positions[1]); + var view = world.View; + for (var i = 0; i < 300; i++) world.Step(1f / 60f, substeps); + float worst = 0f; + for (var k = 1; k + 1 < 24; k++) + { + (float X, float Y) a = (view.ParticleX[k] - view.ParticleX[k - 1], view.ParticleY[k] - view.ParticleY[k - 1]); + (float X, float Y) b = (view.ParticleX[k + 1] - view.ParticleX[k], view.ParticleY[k + 1] - view.ParticleY[k]); + var c = (a.X * b.X + a.Y * b.Y) / MathF.Sqrt((a.X * a.X + a.Y * a.Y) * (b.X * b.X + b.Y * b.Y)); + worst = MathF.Max(worst, MathF.Acos(MathF.Min(1f, c)) * 180f / MathF.PI); + } + return (1f - view.ParticleY[23], worst); + } + var stiff = Cantilever(1e-7f, -1f); + var floppy = Cantilever(1e-4f, -1f); + var thirty = Cantilever(-1f, 30f); + var ten = Cantilever(-1f, 10f); + Assert.True(stiff.Drop < floppy.Drop, $"stiff {stiff.Drop} m, floppy {floppy.Drop} m"); + Assert.True(thirty.Defl <= 31f, $"the 30 degree limit allowed {thirty.Defl} degrees"); + Assert.True(ten.Defl <= 11.5f, $"the 10 degree limit allowed {ten.Defl} degrees"); + Assert.True(ten.Drop < thirty.Drop, "the tighter limit droops less"); + // A limit alone applies nothing inside its cone: a gently swinging hung rope is bit-identical with and without it. + float[] Swing(bool limited) + { + using var world = World(gravityY: -10f); + var step = (MathF.Sin(0.05f) * Spacing, -MathF.Cos(0.05f) * Spacing, 0f); + var positions = Line((0f, 3f, 0f), step, 24); + var rope = limited ? Graph.Rope(world, positions, ParticleMass, ParticleRadius, bend: -1f, maxAngle: 30f * MathF.PI / 180f) + : Graph.Rope(world, positions, ParticleMass, ParticleRadius, bend: -1f); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true); + var view = world.View; + Run(world, 60); + return [.. view.ParticleX, .. view.ParticleY]; + } + Assert.True(Swing(true).AsSpan().SequenceEqual(Swing(false)), "a limit-only bend moved something inside its cone"); } [Fact] - public void Removed_lanes_reused_after_a_step() + public void Contact_conserves_momentum() { - using var world = World(particles: 12, chains: 2, attachments: 2); - var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 10); - var a = world.CreateChain(1, positions, ParticleMass, ParticleRadius); - var attachment = world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); - world.Step(Dt, Sub); - world.DestroyChain(a); + // Zero gravity: a self-colliding rope thrown at 3 m/s into a self-colliding sheet and a loose blob; the sum of momentum + // may not drift and the kinetic energy may not rise (a per-particle average of contacts fails both). + using var world = World(particles: 512, distances: 512, bends: 512, tethers: 8, gravityY: 0f); + world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f)); + var sheet = Graph.Sheet(world, (0f, 0f, 0f), (0.04f, 0f, 0f), (0f, 0.04f, 0f), 12, 12, ParticleMass, 0.02f, Box3DSoaPhase.Of(7, true, true)); + var rope = Graph.Rope(world, Line((-0.6f, 0.2f, -0.3f), (0f, 0f, 0.04f), 31), 0.03f, 0.02f, Box3DSoaPhase.Of(8, true, true), bend: 1e-5f, velocity: (3f, 0f, 0f)); + var blob = new List(); + for (var a = 0; a < 5; a++) for (var b = 0; b < 5; b++) for (var c = 0; c < 5; c++) + blob.Add(new Box3DSoaParticleDesc((0.15f + a * 0.04f, 0.15f + b * 0.04f, 0.4f + c * 0.04f), 0.008f, 0.02f, Box3DSoaPhase.Of(9), velocity: (0f, 0f, -4f))); + world.CreateParticles(blob.ToArray()); var view = world.View; - Assert.Equal((uint)Box3DSoaChainKind.Removed, view.ChainKind[a.Lane]); - Assert.Equal((uint)Box3DSoaAttachKind.Removed, view.AttachmentKind[attachment.Lane]); // it would dangle - Assert.Equal(-1, view.ParticleChain[0]); + (double X, double Y, double Z, double E) Total() + { + double x = 0, y = 0, z = 0, e = 0; + for (var i = 0; i < view.ParticleCount; i++) + { + if (view.ParticleLive[i] == 0 || view.ParticleInvMass[i] == 0f) continue; + double m = 1.0 / view.ParticleInvMass[i]; + x += m * view.ParticleVx[i]; y += m * view.ParticleVy[i]; z += m * view.ParticleVz[i]; + e += 0.5 * m * (Sq(view.ParticleVx[i]) + Sq(view.ParticleVy[i]) + Sq(view.ParticleVz[i])); + } + return (x, y, z, e); + } + var p0 = Total(); + var emax = p0.E; + for (var i = 0; i < 180; i++) + { + world.Step(1f / 60f, 8); + emax = Math.Max(emax, Total().E); + } + var p1 = Total(); + var mag = Math.Sqrt(p0.X * p0.X + p0.Y * p0.Y + p0.Z * p0.Z); + var drift = Math.Sqrt(Sq((float)(p1.X - p0.X)) + Sq((float)(p1.Y - p0.Y)) + Sq((float)(p1.Z - p0.Z))); + Assert.True(drift / mag < 2e-4, $"momentum drifted by {drift / mag:P4}"); + Assert.True(emax <= p0.E * (1 + 1e-5), $"kinetic energy rose from {p0.E} to {emax}"); + _ = sheet; _ = rope; + } + + [Fact] + public void Phase_rules() + { + using var world = World(gravityY: 0f); + world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f)); + // Two pairs of particles flying at each other: different groups collide, one group without SELF_COLLIDE passes through. + var apart = new Box3DSoaParticleDesc[] + { + new((0f, 0f, 0f), 0.02f, 0.02f, Box3DSoaPhase.Of(1), velocity: (1f, 0f, 0f)), + new((0.2f, 0f, 0f), 0.02f, 0.02f, Box3DSoaPhase.Of(2), velocity: (-1f, 0f, 0f)), + new((0f, 1f, 0f), 0.02f, 0.02f, Box3DSoaPhase.Of(3), velocity: (1f, 0f, 0f)), + new((0.2f, 1f, 0f), 0.02f, 0.02f, Box3DSoaPhase.Of(3), velocity: (-1f, 0f, 0f)), + }; + world.CreateParticles(apart); + var view = world.View; + Run(world, 60); + Assert.True(view.ParticleX[1] - view.ParticleX[0] > 0.039f && view.ParticleX[0] < view.ParticleX[1], "different groups collided"); + Assert.True(view.ParticleX[2] > view.ParticleX[3] + 0.1f, "one group without SELF_COLLIDE passed through"); + // SELF_FILTER: two particles that touch in the rest pose and are held by a stitch keep their distance; a folded rope's far parts do not overlap. + var phase = Box3DSoaPhase.Of(4, true, true); + var pair = new Box3DSoaParticleHandle[2]; + world.CreateParticles([new((0f, 3f, 0f), 0.02f, 0.0125f, phase), new((0.01f, 3f, 0f), 0.02f, 0.0125f, phase)], pair); + world.CreateDistances([new Box3DSoaDistanceDesc(pair[0], pair[1])]); + var straight = Line((0f, 6f, 0f), (Spacing, 0f, 0f), 24); + var folded = new Pos[24]; + for (var i = 0; i < 12; i++) folded[i] = (i * Spacing, 6f, 0f); + for (var i = 12; i < 24; i++) folded[i] = ((23 - i) * Spacing, 6f, 0.02f); // the second arm lies 2 cm over the first + var rope = Graph.Rope(world, folded, ParticleMass, ParticleRadius, phase, rest: straight, bend: -1f, maxAngle: -1f); + view = world.View; + Run(world, 120); + var held = Graph.Dist(view, pair[0], pair[1]); + Assert.True(MathF.Abs(held - 0.01f) < 0.0005f, $"a rest-touching pair was pushed apart to {held}"); + var closest = float.MaxValue; + for (var i = 0; i < 24; i++) + for (var j = i + 3; j < 24; j++) + closest = MathF.Min(closest, Graph.Dist(view, rope.Particles[i], rope.Particles[j])); + Assert.True(closest > 0.9f * 2f * ParticleRadius, $"far parts of the folded rope overlap: {closest}"); + } + + [Fact] + public void Off_centre_attachment_spins_a_free_box() + { + // A particle tied to a point off a free box's centre and pulled by a world point: the box's angular velocity changes by + // I^-1 (r x J), J being the impulse lane. Dropping sub_angular or the proxy's rotation prediction breaks the 2%. + using var world = World(gravityY: 0f); + const float half = 0.2f, mass = 1f; + var box = world.AddBox(2, (0f, 0f, 0f), (half, half, half), mass / (8f * half * half * half)); + var p = new Box3DSoaParticleHandle[1]; + world.CreateParticles([new((half, 0f, 0f), 0.05f, 0.02f)], p); + world.Attach(Box3DSoaAttachKind.Body, p[0], box, (half, 0f, 0f)); + world.Attach(Box3DSoaAttachKind.Static, p[0], point: (half, 0.05f, 0f), compliance: 1e-3f); + var view = world.View; + world.Step(Dt, Sub); + var j = (X: view.ParticleImpulseX[box], Y: view.ParticleImpulseY[box], Z: view.ParticleImpulseZ[box]); + var inertia = mass * (2f * half) * (2f * half) / 6f; // a cube: m s^2 / 6 + var wz = (half * j.Y - 0f * j.X) / inertia; // r = (half, 0, 0): (r x J).z = half * Jy + Assert.True(MathF.Abs(j.Y) > 0.001f, $"the pull is read: {j.Y}"); + Assert.True(MathF.Abs(view.AngularVelocityZ[box] - wz) < 0.02f * MathF.Abs(wz), $"omega_z {view.AngularVelocityZ[box]}, expected {wz}"); + Assert.True(MathF.Abs(view.VelocityY[box] - j.Y / mass) < 0.02f * MathF.Abs(j.Y / mass), $"vy {view.VelocityY[box]}, expected {j.Y / mass}"); + } + + // ---- lanes ---------------------------------------------------------------------------------------------- + + [Fact] + public void Lanes_reused_after_a_step_and_refusals_change_nothing() + { + using var world = World(particles: 12, distances: 12, bends: 12, attachments: 2, tethers: 20); + var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 10); + var a = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + var attachment = world.Attach(Box3DSoaAttachKind.Static, a.Particles[0], point: positions[0], tether: true); + world.Step(Dt, Sub); + world.DestroyParticles(a.Particles); + var view = world.View; + Assert.Equal(0u, view.ParticleLive[0]); Assert.Equal(0f, view.ParticleY[0]); - Assert.Equal(2, world.FreeParticleSlots); // only the two slots beyond the destroyed range - Assert.Throws(() => world.CreateChain(2, positions, ParticleMass, ParticleRadius)); // the range is held this step + Assert.Equal(1u, view.ParticleGeneration[0]); + Assert.Equal(world.StepCount, view.ParticleRemovedAt[0]); + Assert.Equal((uint)Box3DSoaAttachKind.Removed, view.AttachmentKind[attachment.Lane]); // it would dangle + Assert.Equal(0, world.View.TetherCount); + Assert.Equal(2, world.FreeParticleSlots); // only the two lanes beyond the destroyed ones + Assert.Throws(() => Graph.Rope(world, positions, ParticleMass, ParticleRadius)); // the lanes are held this step + Assert.Equal(10, view.ParticleCount); world.Step(Dt, Sub); Assert.Equal(12, world.FreeParticleSlots); - var b = world.CreateChain(2, positions, ParticleMass, ParticleRadius); - Assert.Equal(a.Lane, b.Lane); // the lowest reusable lane, and its range - Assert.Equal(0, world.View.ChainFirst[b.Lane]); - Assert.NotEqual(a.Generation, b.Generation); - Assert.Throws(() => world.DestroyChain(a)); // stale - Assert.Throws(() => world.SplitChain(a, 3, 5)); - Assert.Throws(() => world.Detach(attachment)); - var c = world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); - world.Detach(c); + var b = Graph.Rope(world, positions, ParticleMass, ParticleRadius); + Assert.Equal(a.Particles.Select(h => h.Lane), b.Particles.Select(h => h.Lane)); // lowest first + Assert.Equal(a.Edges.Select(h => h.Lane), b.Edges.Select(h => h.Lane)); + Assert.Equal(1u, b.Particles[0].Generation); + Assert.Throws(() => world.DestroyParticles([a.Particles[0]])); // stale + Assert.Throws(() => world.Remove(a.Edges[0])); + Assert.Throws(() => world.Remove(attachment)); + var c = world.Attach(Box3DSoaAttachKind.Static, b.Particles[0], point: positions[0]); + world.Remove(c); world.Step(Dt, Sub); - var d = world.Attach(Box3DSoaAttachKind.Static, 0, point: positions[0]); - Assert.Equal(c.Lane, d.Lane); - Assert.Throws(() => world.Detach(c)); + Assert.Equal(c.Lane, world.Attach(Box3DSoaAttachKind.Static, b.Particles[0], point: positions[0]).Lane); + + // a derivation that does not fit is refused whole + using var small = World(particles: 12, distances: 12, bends: 12, attachments: 2, tethers: 5); + var ps = new Box3DSoaParticleHandle[10]; + small.CreateParticles(Line((0f, 1f, 0f), (Spacing, 0f, 0f), 10).Select(q => new Box3DSoaParticleDesc(q, 0.02f, 0.0125f)).ToArray(), ps); + small.Attach(Box3DSoaAttachKind.Static, ps[0], point: (0f, 1f, 0f), tether: true); + var d = Enumerable.Range(0, 9).Select(i => new Box3DSoaDistanceDesc(ps[i], ps[i + 1])).ToArray(); + + Assert.Throws(() => small.CreateDistances(d)); // would need 9 tethers + Assert.Equal(0, small.View.DistanceCount); + Assert.Equal(0, small.View.TetherCount); + Assert.Equal(12, small.FreeDistanceSlots); + small.CreateDistances(d[..5]); // 5 tethers fit + Assert.Equal(5, small.View.TetherCount); + Assert.Throws(() => small.CreateDistances(d[5..6])); // the sixth would not + Assert.Equal(5, small.View.DistanceCount); + Assert.Equal(5, small.View.TetherCount); + + // refusals + Assert.Throws(() => small.CreateParticles([new((float.NaN, 0f, 0f), 1f, 0.01f)])); + Assert.Throws(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0f)])); // no radius + Assert.Throws(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f, 1u << 22)])); // an unknown phase bit + Assert.Throws(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f, 0, 2)])); // no such material + Assert.Throws(() => small.CreateDistances([new Box3DSoaDistanceDesc(ps[0], ps[0])])); + Assert.Throws(() => small.Attach(Box3DSoaAttachKind.Body, ps[0], 5)); // no such body + Assert.Throws(() => small.Attach(Box3DSoaAttachKind.Static, new Box3DSoaParticleHandle(99, 0))); + Assert.Throws(() => small.Attach(Box3DSoaAttachKind.Static, ps[0], point: (float.PositiveInfinity, 0f, 0f))); + Assert.Throws(() => small.CreateBends([new Box3DSoaBendDesc(new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, 0, 0), new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, 3, 0))])); // share no particle + Assert.Equal(10, small.View.ParticleCount); + Assert.Equal(0, small.View.BendCount); + Assert.Equal(1, small.View.AttachmentCount); + using var plain = new Box3DSoaWorld(2); // no particle capacity: every command is refused + Assert.Throws(() => plain.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f)])); + Assert.Throws(() => new Box3DSoaWorld(2, particles: new Box3DSoaParticleCapacities(-1, 0, 0, 0, 0, 0))); } // ---- determinism -------------------------------------------------------------------------------------- private static Box3DSoaWorld PileScene(bool nudge = false) { - var world = World(bodies: 8, particles: 128, chains: 8, attachments: 8); + var world = World(bodies: 8, particles: 192, distances: 256, bends: 256, attachments: 8, tethers: 256); world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f); + world.SetMaterial(0, 0.3f); var sphere = world.AddSphere(2, (0.2f, 0.35f, 0.1f), 0.15f, 800f); - var box = world.AddBox(3, (-0.3f, 0.2f, -0.1f), (0.2f, 0.1f, 0.2f), 300f); + world.AddBox(3, (-0.3f, 0.2f, -0.1f), (0.2f, 0.1f, 0.2f), 300f); + var ropes = new Made[4]; for (var c = 0; c < 4; c++) { var from = (-0.5f + 0.1f * c, 0.5f + 0.06f * c, -0.3f + 0.2f * c); var step = c % 2 == 0 ? (Spacing, 0f, 0.012f * c) : (0.01f * c, 0f, Spacing); var line = Line(from, step, 24); - if (nudge && c == 2) line[7].Item2 = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(line[7].Item2) + 1); - world.CreateChain((ulong)(10 + c), line, ParticleMass, ParticleRadius, friction: 0.3f, materialId: (ulong)c); + if (nudge && c == 2) line[7].Y = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(line[7].Y) + 1); + ropes[c] = Graph.Rope(world, line, ParticleMass, ParticleRadius, Box3DSoaPhase.Of((uint)(c + 1), true, true)); } - world.Attach(Box3DSoaAttachKind.Body, 24 * 3 + 23, sphere, (0f, 0.15f, 0f)); // a chain tied to a body on the pile - world.Attach(Box3DSoaAttachKind.Static, 0, point: (-0.5f, 0.5f, -0.3f)); + Graph.Sheet(world, (0.1f, 0.9f, -0.2f), (0.03f, 0f, 0f), (0f, 0f, 0.03f), 8, 8, ParticleMass, ParticleRadius, Box3DSoaPhase.Of(9, true, true)); + world.Attach(Box3DSoaAttachKind.Body, ropes[3].Particles[23], sphere, (0f, 0.15f, 0f), tether: true); // a rope tied to a body on the pile + world.Attach(Box3DSoaAttachKind.Static, ropes[0].Particles[0], point: (-0.5f, 0.5f, -0.3f), tether: true); return world; } @@ -349,11 +593,13 @@ public sealed class Box3DSoaParticleTests { var h = 1469598103934665603ul; void F(ReadOnlySpan lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane)); - F(v.ParticleX); F(v.ParticleY); F(v.ParticleZ); F(v.ParticleVx); F(v.ParticleVy); F(v.ParticleVz); F(v.ParticleLinkTension); + F(v.ParticleX); F(v.ParticleY); F(v.ParticleZ); F(v.ParticleVx); F(v.ParticleVy); F(v.ParticleVz); F(v.DistanceTension); F(v.AttachmentForceX); F(v.AttachmentForceY); F(v.AttachmentForceZ); F(v.PositionX); F(v.PositionY); F(v.PositionZ); F(v.RotationX); F(v.RotationY); F(v.RotationZ); F(v.RotationW); F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ); F(v.AngularVelocityX); F(v.AngularVelocityY); F(v.AngularVelocityZ); - F(v.ParticleImpulseX); F(v.ParticleImpulseY); F(v.ParticleImpulseZ); + F(v.ParticleImpulseX); F(v.ParticleImpulseY); F(v.ParticleImpulseZ); F(v.TetherBound); + h = Fnv(h, MemoryMarshal.AsBytes(v.TetherParent)); + h = Fnv(h, MemoryMarshal.AsBytes(v.ParticleComponent)); return h; } @@ -370,6 +616,9 @@ public sealed class Box3DSoaParticleTests return hashes; } + // Recorded on this commit's build (gcc 13.2, -ffp-contract=off): the pile of four ropes and a sheet on two bodies. + private static readonly ulong[] PileHashes = [12993313564863515222ul, 2307790533006845688ul, 13436656559607346955ul, 6468437088969606470ul, 10562521318003626344ul, 7711170181992570593ul]; + [Fact] public void Particle_world_is_byte_deterministic() { @@ -378,13 +627,14 @@ public sealed class Box3DSoaParticleTests Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b)); Assert.True(a.Distinct().Count() == 6, "the scene moves"); Assert.False(a.AsSpan().SequenceEqual(Checkpoints(nudge: true)), "a one-ulp input difference must diverge"); + Assert.True(PileHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul"))); } [Fact] public async Task Particle_world_is_the_same_bytes_on_any_thread_under_load() { - // The solver is single-threaded by construction (no threads in this cut); what is provable is that nothing in it - // depends on which thread runs it or what else is running: eight worlds at once give the serial bytes. + // The solver is single-threaded by construction; what is provable is that nothing in it depends on which thread + // runs it or what else is running: eight worlds at once give the serial bytes. var serial = Checkpoints(); var results = Enumerable.Range(0, 8).Select(_ => Task.Factory.StartNew(() => Checkpoints(), TaskCreationOptions.LongRunning)).ToArray(); await Task.WhenAll(results); @@ -392,57 +642,45 @@ public sealed class Box3DSoaParticleTests } [Fact] - public void Particle_step_does_not_allocate() + public void Particle_step_and_commands_do_not_allocate() { using var world = PileScene(); var view = world.View; Run(world, 20); + var spare = new Box3DSoaParticleHandle[2]; + var fresh = new[] { new Box3DSoaParticleDesc((3f, 3f, 3f), 0.02f, 0.0125f), new Box3DSoaParticleDesc((3f, 3.03f, 3f), 0.02f, 0.0125f) }; + var edge = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, 10, view.DistanceGeneration[10]); + var victim = new[] { new Box3DSoaParticleHandle(100, view.ParticleGeneration[100]) }; var sink = 0f; var before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < 100; i++) { world.Step(Dt, Sub); - sink += view.ParticleY[3] + view.ParticleLinkTension[1] + view.ParticleImpulseX[2] + view.AttachmentForceY[0]; + sink += view.ParticleY[3] + view.DistanceTension[1] + view.ParticleImpulseX[2] + view.AttachmentForceY[0]; } + world.Remove(edge); // a cut + world.DestroyParticles(victim); // a destroy + world.Step(Dt, Sub); + world.Step(Dt, Sub); + world.CreateParticles(fresh, spare); // a create var allocated = GC.GetAllocatedBytesForCurrentThread() - before; Assert.True(sink != 0f); Assert.Equal(0L, allocated); } - - [Fact] - public void Refusals_change_nothing() - { - using var world = World(); - var good = Line((0f, 1f, 0f), (Spacing, 0f, 0f), 4); - world.CreateChain(1, good, ParticleMass, ParticleRadius); - Assert.Throws(() => world.CreateChain(1, good, ParticleMass, ParticleRadius)); // duplicate id - var nan = Line((0f, 1f, 0f), (Spacing, 0f, 0f), 4); nan[2].Item2 = float.NaN; - Assert.Throws(() => world.CreateChain(2, nan, ParticleMass, ParticleRadius)); - Assert.Throws(() => world.CreateChain(3, good, ParticleMass, 0f)); // no radius - Assert.Throws(() => world.CreateChain(3, Line((0f, 1f, 0f), (0f, 0f, 0f), 3), ParticleMass, ParticleRadius)); // links of no length - Assert.Throws(() => world.Attach(Box3DSoaAttachKind.Body, 0, 5)); // no such body - Assert.Throws(() => world.Attach(Box3DSoaAttachKind.Static, 99)); - Assert.Throws(() => world.Attach(Box3DSoaAttachKind.Static, 0, point: (float.PositiveInfinity, 0f, 0f))); - var view = world.View; - Assert.Equal(1, view.ChainCount); - Assert.Equal(0, view.AttachmentCount); - Assert.Equal(4, view.ParticleCount); - using var plain = new Box3DSoaWorld(2); // no particle capacity: every command is refused - Assert.Throws(() => plain.CreateChain(1, good, ParticleMass, ParticleRadius)); - Assert.Throws(() => new Box3DSoaWorld(2, particleCapacity: -1)); - } } /// The structural promises of the particle module, read from its source. public sealed class Box3DSoaParticleSourceTests { - private static string Native() + private static string Root() { var dir = AppContext.BaseDirectory; while (dir != null && !File.Exists(Path.Combine(dir, "native", "Ymir.Box3D", "ymir_particles.c"))) dir = Path.GetDirectoryName(dir); - return Path.Combine(dir ?? throw new FileNotFoundException("native/Ymir.Box3D"), "native", "Ymir.Box3D"); + return dir ?? throw new FileNotFoundException("native/Ymir.Box3D"); } + private static string Native() => Path.Combine(Root(), "native", "Ymir.Box3D"); + /// The text of a function from its signature line to its closing brace at column 0. private static string Body(string source, string signature) { @@ -455,27 +693,46 @@ public sealed class Box3DSoaParticleSourceTests return source.Substring(start, end - start + 2); } - private static string Without(string source, string body) => source.Replace(body, ""); + private static string StripComments(string s) => Regex.Replace(s, @"//[^\n]*|/\*.*?\*/", "", RegexOptions.Singleline); - [Fact] - public void The_particle_module_calls_no_box3d_and_nothing_else_it_must_not() - { - var c = File.ReadAllText(Path.Combine(Native(), "ymir_particles.c")); - var h = File.ReadAllText(Path.Combine(Native(), "ymir_particles.h")); - Assert.Empty(System.Text.RegularExpressions.Regex.Matches(c + h, @"b3[A-Z_]|box3d\.h")); - var outside = Without(Without(c, Body(c, "ymir_particles* ymir_particles_create(")), Body(c, "void ymir_particles_free(")); - Assert.Empty(System.Text.RegularExpressions.Regex.Matches(outside, @"malloc|calloc|realloc|free\(")); - Assert.Empty(System.Text.RegularExpressions.Regex.Matches(c, @"\bomp\b|#pragma|pthread|_Atomic|atomic_")); - } + private static int Count(string text, string pattern) => Regex.Matches(text, pattern).Count; private static int Calls(string name) => Directory.GetFiles(Native(), "*.c").Where(f => !f.EndsWith("ymir_particles.c")).Concat(Directory.GetFiles(Native(), "*.h").Where(f => !f.EndsWith("ymir_particles.h"))) - .Sum(f => System.Text.RegularExpressions.Regex.Matches(File.ReadAllText(f), name + @"\(").Count); - - private static int Count(string text, string pattern) => System.Text.RegularExpressions.Regex.Matches(text, pattern).Count; + .Sum(f => Count(File.ReadAllText(f), name + @"\(")); [Fact] - public void The_particle_phase_runs_in_the_substep_callback_and_never_splits_or_destroys() + public void Particle_source_rules() + { + var c = File.ReadAllText(Path.Combine(Native(), "ymir_particles.c")); + var h = File.ReadAllText(Path.Combine(Native(), "ymir_particles.h")); + var code = StripComments(c + h); + Assert.Equal(0, Count(c + h, @"b3[A-Z_]|box3d\.h")); + var outside = c.Replace(Body(c, "ymir_particles* ymir_particles_create("), "").Replace(Body(c, "void ymir_particles_free("), ""); + Assert.Equal(0, Count(outside, @"malloc|calloc|realloc|free\(")); + Assert.Equal(0, Count(c, @"\bomp\b|#pragma|pthread|_Atomic|atomic_")); + // no object kind: a rope, a sheet, a cloth or a chain is what a caller builds, never a name in the solver or its binding + var bindings = string.Join("\n", Directory.GetFiles(Path.Combine(Root(), "src", "Ymir.Box3D"), "*.cs").Select(f => StripComments(File.ReadAllText(f)))); + Assert.Equal(0, Count(code + bindings, @"(?(component|tether_att|tether_particle|tether_parent|tether_edge|tether_bound)\[[^\]]*\]\s*=[^=]|->tether_count\s*=[^=]")); + Assert.Contains("rederive_topology(p)", Body(c, "int32_t ymir_particles_remove(")); + foreach (var command in new[] { "create_particles", "destroy_particles", "create_distances", "create_bends", "attach", "remove" }) + Assert.Contains("rederive_topology(p)", Body(c, $"int32_t ymir_particles_{command}(")); + // the retired owners stay gone + var retired = string.Join("|", "create_" + "chain", "split_" + "chain", "destroy_" + "chain", "chain_" + "first", "chain_" + "size", "chain_stable_" + "id", + "Chain" + "Handle", "Create" + "Chain", "Split" + "Chain", "Destroy" + "Chain", "FreeChain" + "Slots", "link_" + "tension", "Link" + "Tension"); + foreach (var dir in new[] { "native", "src", "tests", "docs" }) + foreach (var f in Directory.GetFiles(Path.Combine(Root(), dir), "*.*", SearchOption.AllDirectories).Where(f => !f.Contains("obj") && !f.Contains("bin") && (f.EndsWith(".c") || f.EndsWith(".h") || f.EndsWith(".cs") || f.EndsWith(".md")))) + Assert.True(Count(File.ReadAllText(f), retired) == 0, f); + Assert.Equal(0, Count(c + h, @"PARTICLE_" + @"PARTICLE|find_range|mark_slots|stable_id_taken|rest_pos|add_struct")); + Assert.Equal(0, Count(c, @"1\.0f / \(float\)contacts")); + } + + [Fact] + public void The_particle_phase_runs_in_the_substep_callback_and_never_removes() { var soa = File.ReadAllText(Path.Combine(Native(), "ymir_box3d_soa.c")); var c = File.ReadAllText(Path.Combine(Native(), "ymir_particles.c")); @@ -489,17 +746,18 @@ public sealed class Box3DSoaParticleSourceTests Assert.Contains("ymir_particles_end(", step); Assert.Contains("ymir_particles_substep(", callback); Assert.Equal(1, Count(soa, @"b3World_SetSubStepCallback\(")); + Assert.Contains("live_particles == 0", callback); // a body is touched only through the callback's two fork accessors: never pushed after the step, never teleported Assert.Equal(0, Count(step + callback, @"b3Body_ApplyLinearImpulse|b3Body_ApplyAngularImpulse|b3Body_SetTransform")); Assert.Equal(1, Count(soa, @"b3Body_GetSubStepState\(")); Assert.Equal(1, Count(soa, @"b3Body_ApplySubStepImpulse\(")); Assert.Contains("b3Body_GetSubStepState(", callback); Assert.Contains("b3Body_ApplySubStepImpulse(", callback); + // no topology change inside the step var phases = new[] { Body(c, "int32_t ymir_particles_begin("), Body(c, "void ymir_particles_substep("), Body(c, "void ymir_particles_end(") }; foreach (var text in phases.Append(step).Append(callback)) - Assert.Equal(0, Count(text, @"split_chain|destroy_chain|detach")); - // the retired owners stay gone - Assert.Equal(0, Count(c, @"carry|hard_impulse|cancel|k_body|end_force_scale|tension_diff|add_link_load|ymir_particles_step")); - Assert.Equal(0, Count(soa, @"carry|ymir_particles_step|ymir_soa_apply_particle_impulses")); + Assert.Equal(0, Count(text, @"rederive_topology|kill_|ymir_particles_(create|destroy|remove|attach)")); + Assert.Equal(0, Count(c, @"carry|hard_impulse|cancel|k_body|end_force_scale|tension_diff|add_link_load|ymir_particles_step")); + Assert.Equal(0, Count(soa, @"carry|ymir_particles_step|ymir_soa_apply_particle_impulses")); } }