Particles become a constraint graph: chain surface deleted, phased particle lanes and typed constraint lanes with derived tethers and hard-limit bends (ABI 10)
The chain lanes, chain commands and exports, PARTICLE_PARTICLE attachments, chain-order implicit constraints, the per-particle contact average and the chain-order tension sweep are gone in the same commit as the graph that replaces them: the module, its exports, its binding and its tests do not build apart. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9ffc3cc21b
commit
5de7e05814
8 changed files with 1960 additions and 1017 deletions
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -67,17 +67,97 @@ internal struct Box3DSoaRayHitNative
|
|||
public uint Reserved;
|
||||
}
|
||||
|
||||
/// <summary>Native layout of <c>ymir_chain_desc</c>.</summary>
|
||||
/// <summary>
|
||||
/// A particle's identity: its lane and the slot's generation when it was made. Native layout of <c>ymir_handle</c>.
|
||||
/// Converts to the lane for reading lanes; commands refuse a handle from an earlier occupant of the slot.
|
||||
/// </summary>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>The constraint lane sets. Native numbering: a particle is set 0.</summary>
|
||||
public enum Box3DSoaConstraintType : uint
|
||||
{
|
||||
Distance = 1,
|
||||
Bend = 2,
|
||||
Attachment = 3
|
||||
}
|
||||
|
||||
/// <summary>A constraint's identity: its type, lane and the slot's generation when it was made.</summary>
|
||||
public readonly record struct Box3DSoaConstraintHandle(Box3DSoaConstraintType Type, int Lane, uint Generation)
|
||||
{
|
||||
public static implicit operator int(Box3DSoaConstraintHandle handle) => handle.Lane;
|
||||
}
|
||||
|
||||
/// <summary>The phase word: bits 0-19 are the group; the flags are the only other bits.</summary>
|
||||
public static class Box3DSoaPhase
|
||||
{
|
||||
public const uint GroupMask = 0xFFFFFu;
|
||||
/// <summary>Particles of one group collide (both must set it).</summary>
|
||||
public const uint SelfCollide = 1u << 20;
|
||||
/// <summary>...except pairs closer than 1.5 (ri + rj) in the rest pose (either may carry it).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Capacities of the particle state; <c>null</c> or all zero is a world without particles (ABI 8 behaviour).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public readonly record struct Box3DSoaParticleCapacities(int Particles, int Distances, int Bends, int Attachments, int Tethers, int Materials);
|
||||
|
||||
/// <summary>Native layout of <c>ymir_particle_desc</c>: a particle to create. Mass kg (0 = immovable); rest is its place in the rest pose.</summary>
|
||||
[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;
|
||||
|
||||
/// <summary>A particle at <paramref name="position"/>, its rest pose the same place unless <paramref name="rest"/> says otherwise.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Native layout of <c>ymir_distance_desc</c>. <c>Rest</c> < 0 takes the rest-pose length; compliance is m/N.</summary>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Native layout of <c>ymir_bend_desc</c>: 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.
|
||||
/// </summary>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Native layout of <c>ymir_attachment_desc</c>.</summary>
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>Native layout of <c>ymir_material_desc</c>.</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct Box3DSoaMaterialDesc
|
||||
{
|
||||
public float Friction;
|
||||
public uint Reserved;
|
||||
public ulong MaterialId;
|
||||
}
|
||||
|
||||
public enum Box3DSoaAttachKind : uint
|
||||
{
|
||||
/// <summary>The particle to a point fixed in a body: <c>target</c> is the body lane, <c>point</c> is in the body's frame.</summary>
|
||||
Body = 0,
|
||||
/// <summary>The particle to a world point (<c>point</c>); <c>target</c> is ignored.</summary>
|
||||
Static = 1,
|
||||
/// <summary>The particle to another particle: <c>target</c> is the other particle's lane.</summary>
|
||||
Particle = 2,
|
||||
/// <summary>The kind lane of a detached attachment (a tombstone).</summary>
|
||||
Removed = 3
|
||||
}
|
||||
|
||||
public enum Box3DSoaChainKind : uint
|
||||
{
|
||||
Live = 0,
|
||||
/// <summary>A destroyed chain's lane: reusable once a step has passed; it keeps its last range until then.</summary>
|
||||
Removed = 1
|
||||
}
|
||||
|
||||
/// <summary>A chain's identity: its lane and the slot's generation when it was created or split off.</summary>
|
||||
public readonly record struct Box3DSoaChainHandle(int Lane, uint Generation)
|
||||
{
|
||||
public static implicit operator int(Box3DSoaChainHandle handle) => handle.Lane;
|
||||
}
|
||||
|
||||
/// <summary>An attachment's identity: its lane and the slot's generation when it was made.</summary>
|
||||
public readonly record struct Box3DSoaAttachmentHandle(int Lane, uint Generation)
|
||||
{
|
||||
public static implicit operator int(Box3DSoaAttachmentHandle handle) => handle.Lane;
|
||||
/// <summary>The kind lane of a removed attachment (a tombstone).</summary>
|
||||
Removed = 2
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>Native layout of <c>ymir_box3d_soa_facts</c>: counts, dropped counters, then three pointers.</summary>
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -550,12 +645,11 @@ public readonly unsafe struct Box3DSoaView
|
|||
public ReadOnlySpan<float> JointOriginY => Lane(_v.JointOriginY, JointCount);
|
||||
public ReadOnlySpan<float> 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<float> ParticleX => Lane(_v.ParticleX, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleY => Lane(_v.ParticleY, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleZ => Lane(_v.ParticleZ, ParticleCount);
|
||||
|
|
@ -564,35 +658,73 @@ public readonly unsafe struct Box3DSoaView
|
|||
public ReadOnlySpan<float> ParticleVz => Lane(_v.ParticleVz, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleRadius => Lane(_v.ParticleRadius, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleInvMass => Lane(_v.ParticleInvMass, ParticleCount);
|
||||
/// <summary>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.</summary>
|
||||
public ReadOnlySpan<float> ParticleLinkTension => Lane(_v.ParticleLinkTension, ParticleCount);
|
||||
/// <summary>The particle's chain lane, -1 for a free slot.</summary>
|
||||
public ReadOnlySpan<int> ParticleChain => Lane(_v.ParticleChain, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleRestX => Lane(_v.ParticleRestX, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleRestY => Lane(_v.ParticleRestY, ParticleCount);
|
||||
public ReadOnlySpan<float> ParticleRestZ => Lane(_v.ParticleRestZ, ParticleCount);
|
||||
public ReadOnlySpan<uint> ParticlePhase => Lane(_v.ParticlePhase, ParticleCount);
|
||||
public ReadOnlySpan<uint> ParticleMaterial => Lane(_v.ParticleMaterial, ParticleCount);
|
||||
public ReadOnlySpan<uint> ParticleLive => Lane(_v.ParticleLive, ParticleCount);
|
||||
public ReadOnlySpan<uint> ParticleGeneration => Lane(_v.ParticleGeneration, ParticleCount);
|
||||
public ReadOnlySpan<ulong> ParticleRemovedAt => Lane(_v.ParticleRemovedAt, ParticleCount);
|
||||
/// <summary>Derived: the lowest lane of the particle's component of distance-connected particles.</summary>
|
||||
public ReadOnlySpan<int> ParticleComponent => Lane(_v.ParticleComponent, ParticleCount);
|
||||
|
||||
public ReadOnlySpan<ulong> ChainStableId => Lane(_v.ChainStableId, ChainCount);
|
||||
public ReadOnlySpan<uint> ChainKind => Lane(_v.ChainKind, ChainCount);
|
||||
public ReadOnlySpan<uint> ChainGeneration => Lane(_v.ChainGeneration, ChainCount);
|
||||
public ReadOnlySpan<int> ChainFirst => Lane(_v.ChainFirst, ChainCount);
|
||||
public ReadOnlySpan<int> ChainSize => Lane(_v.ChainSize, ChainCount);
|
||||
public ReadOnlySpan<ulong> ChainRemovedAt => Lane(_v.ChainRemovedAt, ChainCount);
|
||||
public ReadOnlySpan<ulong> ChainMaterialId => Lane(_v.ChainMaterialId, ChainCount);
|
||||
public ReadOnlySpan<float> ChainStretchCompliance => Lane(_v.ChainStretchCompliance, ChainCount);
|
||||
public ReadOnlySpan<float> ChainBendCompliance => Lane(_v.ChainBendCompliance, ChainCount);
|
||||
public ReadOnlySpan<float> ChainFriction => Lane(_v.ChainFriction, ChainCount);
|
||||
public int DistanceCount => _v.DistanceCount;
|
||||
public ReadOnlySpan<int> DistanceA => Lane(_v.DistanceA, DistanceCount);
|
||||
public ReadOnlySpan<int> DistanceB => Lane(_v.DistanceB, DistanceCount);
|
||||
public ReadOnlySpan<float> DistanceRest => Lane(_v.DistanceRest, DistanceCount);
|
||||
public ReadOnlySpan<float> DistanceCompliance => Lane(_v.DistanceCompliance, DistanceCount);
|
||||
/// <summary>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.</summary>
|
||||
public ReadOnlySpan<float> DistanceTension => Lane(_v.DistanceTension, DistanceCount);
|
||||
public ReadOnlySpan<uint> DistanceLive => Lane(_v.DistanceLive, DistanceCount);
|
||||
public ReadOnlySpan<uint> DistanceGeneration => Lane(_v.DistanceGeneration, DistanceCount);
|
||||
public ReadOnlySpan<ulong> DistanceRemovedAt => Lane(_v.DistanceRemovedAt, DistanceCount);
|
||||
|
||||
public int BendCount => _v.BendCount;
|
||||
public ReadOnlySpan<int> BendE1 => Lane(_v.BendE1, BendCount);
|
||||
public ReadOnlySpan<int> BendE2 => Lane(_v.BendE2, BendCount);
|
||||
public ReadOnlySpan<int> BendA => Lane(_v.BendA, BendCount);
|
||||
public ReadOnlySpan<int> BendB => Lane(_v.BendB, BendCount);
|
||||
public ReadOnlySpan<int> BendC => Lane(_v.BendC, BendCount);
|
||||
/// <summary>Offsets of the shared particle from the centroid of the three, in metres: at rest and at the hard limit (negative: no limit).</summary>
|
||||
public ReadOnlySpan<float> BendRest => Lane(_v.BendRest, BendCount);
|
||||
public ReadOnlySpan<float> BendLimit => Lane(_v.BendLimit, BendCount);
|
||||
public ReadOnlySpan<float> BendCompliance => Lane(_v.BendCompliance, BendCount);
|
||||
public ReadOnlySpan<uint> BendLive => Lane(_v.BendLive, BendCount);
|
||||
public ReadOnlySpan<uint> BendGeneration => Lane(_v.BendGeneration, BendCount);
|
||||
public ReadOnlySpan<ulong> BendRemovedAt => Lane(_v.BendRemovedAt, BendCount);
|
||||
|
||||
public int AttachmentCount => _v.AttachmentCount;
|
||||
public ReadOnlySpan<uint> AttachmentKind => Lane(_v.AttachmentKind, AttachmentCount);
|
||||
public ReadOnlySpan<uint> AttachmentFlags => Lane(_v.AttachmentFlags, AttachmentCount);
|
||||
public ReadOnlySpan<uint> AttachmentGeneration => Lane(_v.AttachmentGeneration, AttachmentCount);
|
||||
public ReadOnlySpan<int> AttachmentParticle => Lane(_v.AttachmentParticle, AttachmentCount);
|
||||
/// <summary>The body lane (<see cref="Box3DSoaAttachKind.Body"/>), the other particle's lane (<see cref="Box3DSoaAttachKind.Particle"/>) or -1.</summary>
|
||||
/// <summary>The body lane (<see cref="Box3DSoaAttachKind.Body"/>) or -1.</summary>
|
||||
public ReadOnlySpan<int> AttachmentBody => Lane(_v.AttachmentBody, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentPointX => Lane(_v.AttachmentPointX, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentPointY => Lane(_v.AttachmentPointY, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentPointZ => Lane(_v.AttachmentPointZ, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentCompliance => Lane(_v.AttachmentCompliance, AttachmentCount);
|
||||
/// <summary>N: what the attachment exerts on the chain, mean over the substeps, tether load included. A sensor.</summary>
|
||||
/// <summary>N: what the attachment exerts on its particles, mean over the substeps, tether load included. A sensor.</summary>
|
||||
public ReadOnlySpan<float> AttachmentForceX => Lane(_v.AttachmentForceX, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentForceY => Lane(_v.AttachmentForceY, AttachmentCount);
|
||||
public ReadOnlySpan<float> AttachmentForceZ => Lane(_v.AttachmentForceZ, AttachmentCount);
|
||||
public ReadOnlySpan<ulong> AttachmentRemovedAt => Lane(_v.AttachmentRemovedAt, AttachmentCount);
|
||||
|
||||
/// <summary>Derived tethers, up to <see cref="TetherCount"/>: written only by the topology commands, parents before children per attachment.</summary>
|
||||
public int TetherCount => _v.TetherCount;
|
||||
public int TetherCapacity => _v.TetherCapacity;
|
||||
public ReadOnlySpan<int> TetherAttachment => Lane(_v.TetherAtt, TetherCount);
|
||||
public ReadOnlySpan<int> TetherParticle => Lane(_v.TetherParticle, TetherCount);
|
||||
public ReadOnlySpan<int> TetherParent => Lane(_v.TetherParent, TetherCount);
|
||||
public ReadOnlySpan<int> TetherEdge => Lane(_v.TetherEdge, TetherCount);
|
||||
/// <summary>The second attachment of a pair tether (a bound between two attachment points, edge -1), or -1.</summary>
|
||||
public ReadOnlySpan<int> TetherOther => Lane(_v.TetherOther, TetherCount);
|
||||
public ReadOnlySpan<float> TetherBound => Lane(_v.TetherBound, TetherCount);
|
||||
|
||||
public int MaterialCapacity => _v.MaterialCapacity;
|
||||
public ReadOnlySpan<float> MaterialFriction => Lane(_v.MaterialFriction, MaterialCapacity);
|
||||
public ReadOnlySpan<ulong> MaterialTableId => Lane(_v.MaterialTableId, MaterialCapacity);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public ReadOnlySpan<float> ParticleImpulseX => Lane(_v.ParticleImpulseX, Count);
|
||||
|
|
@ -611,19 +743,19 @@ public readonly unsafe struct Box3DSoaView
|
|||
/// </summary>
|
||||
public sealed class Box3DSoaWorld : IDisposable
|
||||
{
|
||||
private const uint ExpectedAbi = 9;
|
||||
private const uint ExpectedAbi = 10;
|
||||
private nint _handle;
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="factCapacity"/> bounds each kind of per-step contact fact (default 4 x capacity; 0 or less is refused);
|
||||
/// <paramref name="hitThreshold"/> is the approach speed in m/s above which a touch is a hit (Box3D's default, 1).
|
||||
/// </summary>
|
||||
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<Box3DSoaViewNative>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_body_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaBodyDesc>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_joint_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaJointDesc>() ||
|
||||
|
|
@ -631,13 +763,19 @@ public sealed class Box3DSoaWorld : IDisposable
|
|||
Box3DSoaNative.ymir_box3d_soa_get_touch_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaTouch>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_hit_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaHit>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_ray_hit_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaRayHitNative>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_chain_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaChainDesc>() ||
|
||||
Box3DSoaNative.ymir_box3d_soa_get_attachment_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaAttachmentDesc>())
|
||||
Size(0) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleDesc>() ||
|
||||
Size(1) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaDistanceDesc>() ||
|
||||
Size(2) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaBendDesc>() ||
|
||||
Size(3) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaAttachmentDesc>() ||
|
||||
Size(4) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaMaterialDesc>() ||
|
||||
Size(5) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleCapacities>() ||
|
||||
Size(6) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleHandle>())
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Fails closed when the native library is not the ABI this build expects, in either direction.</summary>
|
||||
|
|
@ -849,95 +987,111 @@ public sealed class Box3DSoaWorld : IDisposable
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a particle chain of <c>positions.Length</c> (at least 2) particles, in a free range of the particle lanes.
|
||||
/// <paramref name="masses"/> 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 <paramref name="handles"/> (empty to discard them).
|
||||
/// Throws for a full world, a bad phase or material index or non-finite input; nothing changes when it throws.
|
||||
/// </summary>
|
||||
public unsafe Box3DSoaChainHandle CreateChain(
|
||||
ulong stableId, ReadOnlySpan<(float X, float Y, float Z)> positions, ReadOnlySpan<float> masses, float radius,
|
||||
float stretchCompliance = 0f, float bendCompliance = 1e-4f, float friction = 0.3f, ulong materialId = 0)
|
||||
public unsafe void CreateParticles(ReadOnlySpan<Box3DSoaParticleDesc> particles, Span<Box3DSoaParticleHandle> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A chain whose particles all weigh <paramref name="massPerParticle"/> kg.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cuts the link after particle <paramref name="link"/> (0 to size - 2): the head keeps its lane and stable id, the tail
|
||||
/// takes a new chain lane and <paramref name="tailStableId"/>. 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
|
||||
/// <see cref="Step"/> has completed. A stale handle is refused.
|
||||
/// </summary>
|
||||
public Box3DSoaChainHandle SplitChain(Box3DSoaChainHandle chain, int link, ulong tailStableId)
|
||||
public unsafe void DestroyParticles(ReadOnlySpan<Box3DSoaParticleHandle> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Step"/> has completed. A stale handle is refused.
|
||||
/// </summary>
|
||||
public void DestroyChain(Box3DSoaChainHandle chain)
|
||||
/// <summary>Creates distance constraints; <paramref name="handles"/> may be empty. Throws when the derived tethers would not fit the tether capacity.</summary>
|
||||
public unsafe void CreateDistances(ReadOnlySpan<Box3DSoaDistanceDesc> distances, Span<Box3DSoaConstraintHandle> 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<Box3DSoaParticleHandle> 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);
|
||||
}
|
||||
|
||||
/// <summary>Creates bends over pairs of distances that share one particle; a bend dies with either of its distances.</summary>
|
||||
public unsafe void CreateBends(ReadOnlySpan<Box3DSoaBendDesc> bends, Span<Box3DSoaConstraintHandle> handles = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_handle == 0, this);
|
||||
if (!handles.IsEmpty && handles.Length < bends.Length) throw new ArgumentException("One handle per bend.", nameof(handles));
|
||||
Span<Box3DSoaParticleHandle> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ties <paramref name="particle"/> to a body point (kind Body: <paramref name="target"/> is the body lane, <paramref name="point"/> in
|
||||
/// its frame), a world point (Static) or another particle (Particle: <paramref name="target"/> is its lane). Also gives the chain
|
||||
/// long-range tethers from this point. <paramref name="compliance"/> is m/N, 0 for rigid. Attach where the particle already is.
|
||||
/// its frame) or a world point (Static). With <paramref name="tether"/> the point also bounds every particle of the component by
|
||||
/// the rest path. <paramref name="compliance"/> is m/N, 0 for rigid. Attach where the particle already is.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Releases an attachment; its lane is a tombstone (kind Removed) until a step has completed. A stale handle is refused.</summary>
|
||||
public void Detach(Box3DSoaAttachmentHandle attachment)
|
||||
/// <summary>Removes constraints of one type (a distance takes the bends over it with it). A stale handle is refused.</summary>
|
||||
public unsafe void Remove(ReadOnlySpan<Box3DSoaConstraintHandle> 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<Box3DSoaParticleHandle> 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));
|
||||
}
|
||||
|
||||
/// <summary>The largest run of particle slots a new chain could take right now.</summary>
|
||||
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); } }
|
||||
/// <summary>Removes one constraint.</summary>
|
||||
public void Remove(Box3DSoaConstraintHandle constraint) => Remove([constraint]);
|
||||
|
||||
/// <summary>Sets a material table entry: the friction particles of that material have against bodies and the caller's id for it.</summary>
|
||||
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 }));
|
||||
}
|
||||
|
||||
/// <summary>Lanes a new particle could take right now (never used, or dead for a step).</summary>
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -3,19 +3,21 @@ using Ymir.Box3D;
|
|||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>A chain of 48 particles hanging from a static point with a sphere of <paramref name="mass"/> tied under its end.</summary>
|
||||
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)
|
||||
/// <summary>A rope of 48 particles hanging from a static point with a sphere of <paramref name="mass"/> tied under its end.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Kinetic and potential energy of the chain's particles and of the listed spheres (translation and spin), gravity along -y.</summary>
|
||||
/// <summary>Kinetic and potential energy of the particles and of the listed spheres (translation and spin), gravity along -y.</summary>
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -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<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(8)); // an older native under this managed build
|
||||
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(10)); // a newer one
|
||||
Assert.Equal(10u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
|
||||
Box3DSoaWorld.RequireNativeAbi(10);
|
||||
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(9)); // an older native under this managed build
|
||||
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(11)); // a newer one
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
93
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs
Normal file
93
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>What a builder made: the particles, the distances between them and the bends over pairs of distances.</summary>
|
||||
internal sealed record Made(Box3DSoaParticleHandle[] Particles, Box3DSoaConstraintHandle[] Edges, Box3DSoaConstraintHandle[] Bends);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Particles at <paramref name="positions"/> (rest pose <paramref name="rest"/> or the same), a distance between neighbours and a bend over each pair of distances.</summary>
|
||||
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<Box3DSoaConstraintHandle>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>An <paramref name="nu"/> x <paramref name="nv"/> grid: distances along both axes, bends along both.</summary>
|
||||
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<Box3DSoaDistanceDesc>();
|
||||
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<Box3DSoaBendDesc>();
|
||||
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;
|
||||
|
||||
/// <summary>The summed length of the given distances over their summed rest lengths, minus 1.</summary>
|
||||
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);
|
||||
}
|
||||
|
|
@ -1,13 +1,19 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>Particle chains and attachments: the contract of docs/soa-world.md, particle section.</summary>
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>The particle graph: the contract of docs/soa-world.md, particle section.</summary>
|
||||
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<byte> 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;
|
||||
|
||||
/// <summary>Total link length of a chain over its rest length, minus 1.</summary>
|
||||
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<Box3DSoaParticleDesc>();
|
||||
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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => world.DestroyChain(a)); // stale
|
||||
Assert.Throws<InvalidOperationException>(() => world.SplitChain(a, 3, 5));
|
||||
Assert.Throws<InvalidOperationException>(() => 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<InvalidOperationException>(() => world.DestroyParticles([a.Particles[0]])); // stale
|
||||
Assert.Throws<InvalidOperationException>(() => world.Remove(a.Edges[0]));
|
||||
Assert.Throws<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => small.CreateDistances(d[5..6])); // the sixth would not
|
||||
Assert.Equal(5, small.View.DistanceCount);
|
||||
Assert.Equal(5, small.View.TetherCount);
|
||||
|
||||
// refusals
|
||||
Assert.Throws<InvalidOperationException>(() => small.CreateParticles([new((float.NaN, 0f, 0f), 1f, 0.01f)]));
|
||||
Assert.Throws<InvalidOperationException>(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0f)])); // no radius
|
||||
Assert.Throws<InvalidOperationException>(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f, 1u << 22)])); // an unknown phase bit
|
||||
Assert.Throws<InvalidOperationException>(() => small.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f, 0, 2)])); // no such material
|
||||
Assert.Throws<InvalidOperationException>(() => small.CreateDistances([new Box3DSoaDistanceDesc(ps[0], ps[0])]));
|
||||
Assert.Throws<InvalidOperationException>(() => small.Attach(Box3DSoaAttachKind.Body, ps[0], 5)); // no such body
|
||||
Assert.Throws<InvalidOperationException>(() => small.Attach(Box3DSoaAttachKind.Static, new Box3DSoaParticleHandle(99, 0)));
|
||||
Assert.Throws<InvalidOperationException>(() => small.Attach(Box3DSoaAttachKind.Static, ps[0], point: (float.PositiveInfinity, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => 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<InvalidOperationException>(() => plain.CreateParticles([new((0f, 0f, 0f), 1f, 0.01f)]));
|
||||
Assert.Throws<InvalidOperationException>(() => 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<float> 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => world.CreateChain(2, nan, ParticleMass, ParticleRadius));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateChain(3, good, ParticleMass, 0f)); // no radius
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateChain(3, Line((0f, 1f, 0f), (0f, 0f, 0f), 3), ParticleMass, ParticleRadius)); // links of no length
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Body, 0, 5)); // no such body
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Static, 99));
|
||||
Assert.Throws<InvalidOperationException>(() => 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<InvalidOperationException>(() => plain.CreateChain(1, good, ParticleMass, ParticleRadius));
|
||||
Assert.Throws<InvalidOperationException>(() => new Box3DSoaWorld(2, particleCapacity: -1));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The structural promises of the particle module, read from its source.</summary>
|
||||
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");
|
||||
|
||||
/// <summary>The text of a function from its signature line to its closing brace at column 0.</summary>
|
||||
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, @"(?<![A-Za-z])(rope|sheet|cloth|chain|Rope|Sheet|Cloth|Chain)(?![a-z])"));
|
||||
// tether lanes and the component lane have one writer: the derivation
|
||||
var outsideWriters = c.Replace(Body(c, "static void derive_from("), "").Replace(Body(c, "static int32_t rederive_topology("), "");
|
||||
var rest = StripComments(outsideWriters);
|
||||
Assert.Equal(0, Count(rest, @"->(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"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue