diff --git a/docs/soa-world.md b/docs/soa-world.md index 0b870d1..1c47445 100644 --- a/docs/soa-world.md +++ b/docs/soa-world.md @@ -135,7 +135,7 @@ separate native object (`ymir_box3d_soa.c`, ABI 18) so the Aetheria session's co removed), flags (`TETHER`; `ONE_WAY`, Body only: the body side weighs nothing, so the attachment holds its particle to the body's point and never moves or loads the body, for flesh whose mass the bone already carries; `LIMB`, Body only: the particle is flesh of the body's limb tree, so contact skips every body whose limb-tree root, the `parent` lane followed to its end, is the attached body's), particle, body, point, compliance, `force` (sensor). Held lanes (derived, command time): per particle the list of bodies its live Body attachments name, which contact skips, and `limb_body`, the body of its lowest live `LIMB` attachment or -1. Limit: when a particle's `LIMB` attachments name bodies of two limb trees only the lowest one's tree is skipped; the other tree's bones collide, except the bodies the particle is attached to. Tether lanes (derived): attachment, particle, bound, parent tether, edge, other attachment. Material table: friction, XSPH viscosity, wet friction and the caller's material id. Handles are (lane, generation). - - Pinned, dormant, kinematic, anchor. `pinned` is a command-owned lane (`set_pinned`; `destroy_particles` frees it to 0). A pinned particle is dormant: no step walk visits it, its `x y z vx vy vz` are stale from the tick it was pinned until it wakes, and a reader draws it from its anchor, the point of its lowest live non-`TETHER` attachment (body or static) when it was pinned, held while it sleeps so no attachment another command adds can move it, where the view's `particle_pinned` lane says which and its `particle_anchor` lane names the attachment (readers read it, never re-derive it). A pinned particle that shares a live distance or bend with an unpinned one is kinematic: each substep its position is its anchor's point at the substep's start pose and its predicted position that point at the predicted pose, so the live neighbour is held against a moving border (its velocity is the anchor point's over the substep). Every step walk visits a list `rederive_active` derived at command time, the last step of every topology command and of `set_pinned`: `act` (live unpinned particles), `kin`, `act_dist` and `act_bend` (live constraints with an unpinned particle), `act_att` (attachments of unpinned particles), all in lane order, plus `anchor` and `w` (the inverse mass the step reads: 0 for pinned). With nothing pinned the lists are every live lane in lane order and `w` is `inv_mass`, bit for bit. A dormant particle is in no contact grid (flesh at rest meets no fluid and no body: it rides its bone, which is the body fluid and other bodies meet, so blood poured on dormant skin stops at the bone's capsule, within a skin radius of the skin's surface only while the capsule is that surface), writes no impulse, and a pinned fluid particle is refused. `set_pinned` refuses whole (INVALID_ARGUMENT) a stale or dead handle, a value other than 0 or 1, a fluid particle, and pinning a particle with no anchor or whose distance component holds a live `TETHER` attachment; a wake sets position to the anchor's point at the bodies' poses now and velocity to that point's velocity. `remove(attachment)` refuses a pinned particle's anchor. A tether attached to a particle whose distance component holds a pinned particle is refused whole by `attach`, the mirror of `set_pinned` refusing a tethered component (a tether loads every lane of its component, and no walk moves a pinned one): wake first. Any other attachment of a pinned particle is accepted in whatever lane it takes and leaves its anchor and pose as they were. A patch of settled liquid on a pinned particle is read at its anchor's point, so it rides the bone. + - Pinned, dormant, kinematic, anchor. `pinned` is a command-owned lane (`set_pinned`; `destroy_particles` frees it to 0). A pinned particle is dormant: no step walk visits it, its `x y z vx vy vz` are stale from the tick it was pinned until it wakes, and a reader draws it from its anchor, the point of its lowest live non-`TETHER` attachment (body or static) when it was pinned, held while it sleeps so no attachment another command adds can move it, where the view's `particle_pinned` lane says which and its `particle_anchor` lane names the attachment (readers read it, never re-derive it). A pinned particle that shares a live distance or bend with an unpinned one is kinematic: each substep its position is its anchor's point at the substep's start pose and its predicted position that point at the predicted pose, so the live neighbour is held against a moving border (its velocity is the anchor point's over the substep). Every step walk visits a list `rederive_active` derived at command time, the last step of every topology command and of `set_pinned`: `act` (live unpinned particles), `kin`, `act_dist` and `act_bend` (live constraints with an unpinned particle), `act_att` (attachments of unpinned particles), all in lane order, plus `anchor` and `w` (the inverse mass the step reads: 0 for pinned). With nothing pinned the lists are every live lane in lane order and `w` is `inv_mass`, bit for bit. A dormant particle is in no contact grid (flesh at rest meets no fluid and no body: it rides its bone, which is the body fluid and other bodies meet, so blood poured on dormant skin stops at the bone's capsule, within a skin radius of the skin's surface only while the capsule is that surface), writes no impulse, and a pinned fluid particle is refused. `set_pinned` refuses whole (INVALID_ARGUMENT) a stale or dead handle, a value other than 0 or 1, a fluid particle, and pinning a particle with no anchor; a wake sets position to the anchor's point at the bodies' poses now and velocity to that point's velocity. `remove(attachment)` refuses a pinned particle's anchor. No distance component holds both a pinned particle and a live `TETHER` attachment (a tether loads every lane of its component, and no walk moves a pinned one): `rederive_topology`, which every topology command and `set_pinned` end in, checks it once on the components it derives before writing any lane, and refuses whole whatever would break it (a tether attached into a component with pinned flesh, a distance joining such a component to a tethered one, a pin in a tethered component); the command backs its lanes out. Wake first. Any other attachment of a pinned particle is accepted in whatever lane it takes and leaves its anchor and pose as they were. A patch of settled liquid on a pinned particle is read at its anchor's point, so it rides the bone. - Commands, each refused whole before anything changes: `create_particles(n, desc{position, velocity, rest, mass, radius, phase, material})` takes the lowest free lanes; `destroy_particles(n, handles)` removes every constraint that touches them; `create_distances(n, desc{a, b, rest (< 0 = rest-pose length), compliance})`; `create_bends(n, desc{e1, e2, compliance diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c index 8f5ba18..7cfc63e 100644 --- a/native/Ymir.Box3D/ymir_particles.c +++ b/native/Ymir.Box3D/ymir_particles.c @@ -614,8 +614,8 @@ static int has_pair(const ymir_particles* p, int32_t a, const int32_t* label) return 0; } -// The only writer of the active lists, the counts, anchor and w. Called at the end of rederive_topology (every topology command) and by -// set_pinned: the step walks only these, so what a step visits is decided at command time and never tested per lane. A distance or bend +// The only writer of the active lists, the counts, anchor and w. Called at the end of rederive_topology (every topology command and +// set_pinned): the step walks only these, so what a step visits is decided at command time and never tested per lane. A distance or bend // is active when one of its particles is unpinned; a pinned particle it reaches is kinematic (the step holds it on its anchor), and the // bend's three particles all count, since a bend reads b against the centroid of a and c. static void rederive_active(ymir_particles* p) @@ -687,21 +687,65 @@ static void rederive_active(ymir_particles* p) p->kin_n = n; } -// The only writer of the tether lanes and the component lane. Called at the end of every topology command. The -// tether count is known from the component sizes before anything is written: a derivation that would not fit is -// refused with every lane as it was. +// 1 when a distance component (`label` names them by a lane) holds both a live pinned particle and a live TETHER attachment. +// A tether loads every lane of its component and no walk moves a pinned one, so no derivation admits it. done is scratch. +static int pinned_meets_tether(ymir_particles* p, const int32_t* label) +{ + int32_t np = p->particle_count; + memset(p->done, 0, (size_t)np); + for (int32_t i = 0; i < np; ++i) + { + if (p->particle_live[i] && p->pinned[i]) + { + p->done[label[i]] |= 1; + } + } + for (int32_t a = 0; a < p->attachment_count; ++a) + { + if (is_tether(p, a)) + { + p->done[label[p->att_particle[a]]] |= 2; + } + } + for (int32_t i = 0; i < np; ++i) + { + if (p->done[i] == 3) + { + return 1; + } + } + return 0; +} + +// The only writer of the tether lanes and the component lane, and the one check that no component holds both pinned flesh +// and a TETHER (pinned_meets_tether). Called at the end of every topology command and of set_pinned. The tether count and +// the check are settled from the components before anything is written: a derivation that would not fit, or would admit a +// pinned particle and a tether in one component, is refused (FULL, INVALID_ARGUMENT) with every lane as it was, and the +// command backs its own lanes out. // ISOLATED is for a command that changed no distance and no attachment, only which lanes are live: the graph, so every // tether and every other lane's component, is as it was. It writes the component of the `n` lanes in `lanes` (each // just created, which is its own component, or just destroyed, which reads 0), their held list (empty) and limb body (-1), -// and returns. +// and returns. A new particle is unpinned with no attachment and a destroyed one holds nothing, so it needs no check. +// PINNED is for a command that changed only which lanes are pinned: the graph and every component are as they were, so it +// checks on the component lane and derives the active lists. enum { TOPO_FULL = 0, - TOPO_ISOLATED = 1 + TOPO_ISOLATED = 1, + TOPO_PINNED = 2 }; static int32_t rederive_topology(ymir_particles* p, int mode, const int32_t* lanes, int32_t n) { + if (mode == TOPO_PINNED) + { + if (pinned_meets_tether(p, p->component)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; + } + rederive_active(p); + return YMIR_PARTICLES_OK; + } if (mode == TOPO_ISOLATED) { for (int32_t k = 0; k < n; ++k) @@ -765,6 +809,10 @@ static int32_t rederive_topology(ymir_particles* p, int mode, const int32_t* lan } p->comp_size[i] = tail; } + if (pinned_meets_tether(p, p->tether_of)) + { + return YMIR_PARTICLES_INVALID_ARGUMENT; // a tether and pinned flesh in one component: wake it first + } // Islands (Kim 2012 sec. 3.4): a particle holding a live TETHER attachment is a tether particle; an island is a maximal // set of them joined by live distances, named by its lowest TETHER attachment. isle labels tether particles, -1 elsewhere // (-2 while a tether particle awaits its island). @@ -1237,19 +1285,6 @@ int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_ben return rederive_topology(p, TOPO_FULL, NULL, 0); } -// 1 when a live pinned particle sits in the same distance component as lane i. -static int component_pinned(const ymir_particles* p, int32_t i) -{ - for (int32_t j = 0; j < p->particle_count; ++j) - { - if (p->particle_live[j] && p->pinned[j] && p->component[j] == p->component[i]) - { - return 1; - } - } - return 0; -} - int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out) { if (p == NULL || n < 0 || (n > 0 && d == NULL)) @@ -1289,20 +1324,7 @@ int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachmen p->att_compliance[a] = d[k].compliance; p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f; } - // A tether loads every lane of its distance component, and no walk moves a pinned one: a TETHER on a particle whose component holds pinned flesh is - // refused whole, the mirror of set_pinned refusing a tethered component. Wake it first. The component lane is the one before this command: an attach joins no component. - int32_t status = YMIR_PARTICLES_OK; - for (int32_t k = 0; k < n && status == YMIR_PARTICLES_OK; ++k) - { - if ((d[k].flags & YMIR_ATTACH_FLAG_TETHER) != 0 && component_pinned(p, d[k].particle.lane)) - { - status = YMIR_PARTICLES_INVALID_ARGUMENT; - } - } - if (status == YMIR_PARTICLES_OK) - { - status = rederive_topology(p, TOPO_FULL, NULL, 0); - } + int32_t status = rederive_topology(p, TOPO_FULL, NULL, 0); if (status != YMIR_PARTICLES_OK) { for (int32_t k = 0; k < n; ++k) // back out: the lanes read as they did before the command @@ -2703,19 +2725,6 @@ void ymir_particles_end(ymir_particles* p, int32_t substeps) // ---- pinned: the command-owned dormancy of a particle ------------------------------------------------------------ -// 1 when a live TETHER attachment sits on a particle of the same distance component as lane i. -static int component_tethered(const ymir_particles* p, int32_t i) -{ - for (int32_t a = 0; a < p->attachment_count; ++a) - { - if (is_tether(p, a) && p->component[p->att_particle[a]] == p->component[i]) - { - return 1; - } - } - return 0; -} - int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handle* h, uint32_t pinned) { if (p == NULL || n < 0 || (n > 0 && h == NULL) || pinned > 1) @@ -2725,18 +2734,26 @@ int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handl for (int32_t k = 0; k < n; ++k) { int32_t i = h[k].lane; - if (!particle_ok(p, i, h[k].generation) || (p->phase[i] & YMIR_PHASE_FLUID) || - (pinned && (p->anchor[i] < 0 || component_tethered(p, i)))) + if (!particle_ok(p, i, h[k].generation) || (p->phase[i] & YMIR_PHASE_FLUID) || (pinned && p->anchor[i] < 0)) { - return YMIR_PARTICLES_INVALID_ARGUMENT; // a pinned particle is drawn from its anchor, and a tether would load a lane that no walk moves + return YMIR_PARTICLES_INVALID_ARGUMENT; // a pinned particle is drawn from its anchor } } + int32_t newly = 0; // the lanes this pin took 0 -> 1, in queue, to back out if the derivation refuses for (int32_t k = 0; k < n; ++k) { int32_t i = h[k].lane; - if (pinned || !p->pinned[i]) + if (pinned) + { + if (!p->pinned[i]) + { + p->pinned[i] = 1; // 0 -> 1 writes only the lane + p->queue[newly++] = i; + } + continue; + } + if (!p->pinned[i]) { - p->pinned[i] = pinned; // 0 -> 1 writes only the lane continue; } // wake: on the anchor's point, moving as that point moves, at the proxies' pose now @@ -2753,8 +2770,13 @@ int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handl put(p->vel_x, p->vel_y, p->vel_z, i, v); p->pinned[i] = 0; } - rederive_active(p); - return YMIR_PARTICLES_OK; + // a wake only clears pinned lanes, so the derivation refuses only a pin, which wrote nothing but the lanes in queue + int32_t status = rederive_topology(p, TOPO_PINNED, NULL, 0); + for (int32_t k = 0; status != YMIR_PARTICLES_OK && k < newly; ++k) + { + p->pinned[p->queue[k]] = 0; + } + return status; } // ---- settle: liquid becomes data ---------------------------------------------------------------------------- diff --git a/native/Ymir.Box3D/ymir_particles.h b/native/Ymir.Box3D/ymir_particles.h index 31266bd..37982d8 100644 --- a/native/Ymir.Box3D/ymir_particles.h +++ b/native/Ymir.Box3D/ymir_particles.h @@ -283,7 +283,9 @@ float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, floa // 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 (tether capacity: up to two per particle reached, plus the pair routes). Every topology command ends in the one rederive_topology. +// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command and set_pinned ends in +// the one rederive_topology, which refuses whole (INVALID_ARGUMENT) a command that would leave one distance component holding both a pinned +// particle and a live TETHER attachment (a tether loads every lane of its component, and no walk moves a pinned one): wake it first. 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); @@ -293,9 +295,9 @@ int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachmen int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count); // Pins (1) or wakes (0) the named particles. A pinned particle is dormant: on no step walk (a particle of a live distance or bend with an // unpinned particle is held on its anchor each substep instead), its pos and vel stale, drawn from its anchor. Refuses whole (INVALID_ARGUMENT, -// nothing changed) a stale or dead handle, `pinned` not 0 or 1, a fluid particle, and pinned 1 on a particle with no anchor or whose -// distance component holds a live TETHER attachment. The wake sets pos to the anchor's point at the proxies' pose now (the caller has filled -// them) and vel to that point's velocity. Ends in rederive_active. remove(ATTACHMENT) refuses a pinned particle's anchor. +// nothing changed) a stale or dead handle, `pinned` not 0 or 1, a fluid particle, pinned 1 on a particle with no anchor, and what +// rederive_topology refuses. The wake sets pos to the anchor's point at the proxies' pose now (the caller has filled +// them) and vel to that point's velocity. Ends in rederive_topology. remove(ATTACHMENT) refuses a pinned particle's anchor. int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handle* h, uint32_t pinned); // Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else // support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 780703d..af83211 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -1261,7 +1261,7 @@ public sealed class Box3DSoaWorld : IDisposable Check(Box3DSoaNative.ymir_box3d_soa_destroy_particles(_handle, particles.Length, h)); } - /// Creates distance constraints; may be empty. Throws when the derived tethers would not fit the tether capacity. + /// Creates distance constraints; may be empty. Throws, changing nothing, when the derived tethers would not fit the tether capacity or a distance component would hold both a pinned particle and a tether. public unsafe void CreateDistances(ReadOnlySpan distances, Span handles = default) { ObjectDisposedException.ThrowIf(_handle == 0, this); @@ -1305,8 +1305,8 @@ public sealed class Box3DSoaWorld : IDisposable /// /// Ties each particle of to a body point or a world point, as one command ending in one derivation: - /// lanes are taken lowest first in order, and a refusal (a bad desc, a removed body, no free lanes, tethers past capacity, a tether on a particle - /// whose distance component holds a pinned particle) throws with nothing changed. A pinned particle's anchor is held whatever lane an attachment takes. may be empty. + /// lanes are taken lowest first in order, and a refusal (a bad desc, a removed body, no free lanes, tethers past capacity, a distance component + /// left holding both a pinned particle and a tether) throws with nothing changed. A pinned particle's anchor is held whatever lane an attachment takes. may be empty. /// public unsafe void Attach(ReadOnlySpan attachments, Span handles = default) { @@ -1375,7 +1375,7 @@ public sealed class Box3DSoaWorld : IDisposable /// lanes are stale, and a reader draws it from its anchor ( says which, names the attachment). A pinned particle that shares a /// live distance or bend with an unpinned one is held on its anchor each substep instead. A wake puts the particle on its anchor's point at the /// bodies' poses now, moving as that point moves. Refuses the whole batch, changing nothing, for a stale or dead handle, a fluid particle, or pinning - /// a particle with no non-tether attachment or whose distance component holds a tether attachment. Removing a pinned particle's anchor attachment is refused. + /// a particle with no non-tether attachment or whose distance component holds a tether attachment (no command leaves a component holding both). Removing a pinned particle's anchor attachment is refused. /// public unsafe void SetPinned(ReadOnlySpan particles, bool pinned) { diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs index bf0242e..4068453 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs @@ -1274,8 +1274,12 @@ public sealed class Box3DSoaParticleSourceTests Assert.Equal(0, Count(rest, @"->(component|tether_att|tether_particle|tether_parent|tether_edge|tether_bound)\[[^\]]*\]\s*=[^=]|->tether_count\s*=[^=]")); // every call names a mode; only a command that changed no distance and no attachment may derive the isolated lanes Assert.Equal(0, Count(c, @"rederive_topology\(p\)")); - foreach (var command in new[] { "create_particles", "destroy_particles", "create_distances", "create_bends", "attach", "remove" }) + foreach (var command in new[] { "create_particles", "destroy_particles", "create_distances", "create_bends", "attach", "remove", "set_pinned" }) Assert.Contains("rederive_topology(p, ", Body(c, $"int32_t ymir_particles_{command}(")); + // no pinned flesh and tether in one component has one check, in the derivation: no command asks it itself + Assert.Equal(1, Count(StripComments(c), @"static int pinned_meets_tether\(")); + Assert.Equal(0, Count(StripComments(c.Replace(Body(c, "static int32_t rederive_topology("), "")), @"pinned_meets_tether\(p")); + Assert.DoesNotContain("rederive_active", Body(c, "int32_t ymir_particles_set_pinned(")); foreach (var command in new[] { "create_distances", "create_bends", "attach", "remove" }) Assert.DoesNotContain("TOPO_ISOLATED", Body(c, $"int32_t ymir_particles_{command}(")); // emission derives the isolated lanes only (a new particle holds no constraint); destroy names both, the graph changing when a victim held one @@ -1288,7 +1292,8 @@ public sealed class Box3DSoaParticleSourceTests Assert.Equal(0, Count(c + h, @"PxReal|physx")); // 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"); + "Chain" + "Handle", "Create" + "Chain", "Split" + "Chain", "Destroy" + "Chain", "FreeChain" + "Slots", "link_" + "tension", "Link" + "Tension", + "component_" + "pinned", "component_" + "tethered"); 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); diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTetherTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTetherTests.cs new file mode 100644 index 0000000..93241b1 --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTetherTests.cs @@ -0,0 +1,264 @@ +using System.Runtime.InteropServices; +using Ymir.Box3D; + +namespace Ymir.Box3D.Soa.Tests; + +/// +/// No distance component holds both a pinned particle and a live TETHER attachment (docs/soa-world.md, pinned): a tether loads every lane of its +/// component and no walk moves a pinned one. rederive_topology checks it once for every command; these read it through each door a +/// command opens, and through random command sequences. +/// +public sealed class Box3DSoaPinTetherTests +{ + private const float R = 0.0125f; + + private static ulong Fnv(ulong h, ReadOnlySpan bytes) + { + foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; } + return h; + } + + /// Every lane the view exposes for particles, constraints, tethers and bodies, with the counts and free slots. + private static ulong State(Box3DSoaWorld w) + { + var v = w.View; + var h = 1469598103934665603ul; + void L(ReadOnlySpan lane) where T : unmanaged => h = Fnv(h, MemoryMarshal.AsBytes(lane)); + void I(long x) => h = Fnv(h, BitConverter.GetBytes(x)); + I(v.ParticleCount); I(v.DistanceCount); I(v.BendCount); I(v.AttachmentCount); I(v.TetherCount); + I(w.FreeDistanceSlots); I(w.FreeBendSlots); I(w.FreeAttachmentSlots); + L(v.ParticleX); L(v.ParticleY); L(v.ParticleZ); L(v.ParticleVx); L(v.ParticleVy); L(v.ParticleVz); L(v.ParticleInvMass); + L(v.ParticleLive); L(v.ParticleGeneration); L(v.ParticleComponent); L(v.ParticlePinned); L(v.ParticleAnchor); + L(v.ParticleImpulseX); L(v.ParticleImpulseY); L(v.ParticleImpulseZ); + L(v.DistanceA); L(v.DistanceB); L(v.DistanceRest); L(v.DistanceCompliance); L(v.DistanceTension); L(v.DistanceLive); L(v.DistanceGeneration); + L(v.BendA); L(v.BendB); L(v.BendC); L(v.BendE1); L(v.BendE2); L(v.BendLive); L(v.BendGeneration); + L(v.AttachmentKind); L(v.AttachmentFlags); L(v.AttachmentGeneration); L(v.AttachmentParticle); L(v.AttachmentBody); + L(v.AttachmentPointX); L(v.AttachmentPointY); L(v.AttachmentPointZ); L(v.AttachmentForceX); L(v.AttachmentForceY); L(v.AttachmentForceZ); + L(v.TetherAttachment); L(v.TetherParticle); L(v.TetherParent); L(v.TetherEdge); L(v.TetherOther); L(v.TetherBound); + L(v.PositionX); L(v.PositionY); L(v.PositionZ); L(v.RotationX); L(v.RotationY); L(v.RotationZ); L(v.RotationW); + L(v.VelocityX); L(v.VelocityY); L(v.VelocityZ); L(v.AngularVelocityX); L(v.AngularVelocityY); L(v.AngularVelocityZ); + return h; + } + + private static void Step(Box3DSoaWorld w, int n) => Box3DSoaParticleTests.Run(w, n); + + /// Soul's scenes: rope A (4 particles, R0..R2 on a bone, `pinA` pins them) and rope B (3 particles, B0 tethered to a ball), apart. + private sealed class Scene : IDisposable + { + public Box3DSoaWorld W = null!; + public int Bone, Ball; + public Box3DSoaParticleHandle[] A = null!, B = null!; + public void Dispose() => W.Dispose(); + } + + private static Scene Make(bool pinA = true, bool tetherB = true) + { + var s = new Scene { W = new Box3DSoaWorld(8, gravityY: 0f, particles: new Box3DSoaParticleCapacities(64, 32, 32, 32, 64, 2, 0, 0, 0)) }; + var w = s.W; + s.Bone = w.AddAnchor(1, (0f, 1f, 0f)); + s.Ball = w.AddSphere(5, (0.45f, 1.0f, 0f), 0.05f, 1000f); + s.A = Graph.Rope(w, Graph.Line((0f, 1f, 0f), (0.05f, 0f, 0f), 4), 0.02f, R, Box3DSoaPhase.Of(4, noParticleContact: true)).Particles; + for (var k = 0; k < 3; k++) w.Attach(Box3DSoaAttachKind.Body, s.A[k], s.Bone, (0.05f * k, 0f, 0f), limb: true, oneWay: true); + s.B = Graph.Rope(w, Graph.Line((0.2f, 1f, 0f), (0.05f, 0f, 0f), 3), 0.02f, R, Box3DSoaPhase.Of(5, noParticleContact: true)).Particles; + if (tetherB) w.Attach(Box3DSoaAttachKind.Body, s.B[2], s.Ball, (-0.15f, 0f, 0f), tether: true); + if (pinA) w.SetPinned(s.A[..3], true); + Step(w, 3); + return s; + } + + /// The command is refused (status 1) with every lane as in a twin that never saw it, and stays so over ten steps (the active lists too). + private static void RefusedLikeTwin(string what, Action command, Func? make = null) + { + make ??= () => Make(); + using var s = make(); + using var twin = make(); + Assert.Equal(State(twin.W), State(s.W)); + var e = Assert.Throws(() => command(s)); + Assert.Contains("status 1", e.Message); + Assert.True(State(twin.W) == State(s.W), $"{what}: the refusal changed a lane"); + Step(s.W, 10); + Step(twin.W, 10); + Assert.True(State(twin.W) == State(s.W), $"{what}: the refused world steps differently"); + } + + [Fact] + public void A_tether_on_pinned_flesh_is_refused_whole() + { + RefusedLikeTwin("a tether on a pinned particle", s => s.W.Attach(Box3DSoaAttachKind.Body, s.A[1], s.Ball, (-0.4f, 0f, 0f), tether: true)); + RefusedLikeTwin("a batch: a plain attach, then a tether on a pinned particle", s => s.W.Attach([ + new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, s.A[3], s.Bone, (0.15f, 0f, 0f)), + new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, s.A[0], s.Ball, (-0.45f, 0f, 0f), tether: true)])); + } + + [Fact] + public void A_tether_on_a_live_neighbour_of_pinned_flesh_is_refused_whole() + { + RefusedLikeTwin("a tether on live R3 of a component with pinned R0..R2", s => s.W.Attach(Box3DSoaAttachKind.Body, s.A[3], s.Ball, (-0.3f, 0f, 0f), tether: true)); + } + + [Fact] + public void A_distance_joining_pinned_flesh_to_a_tethered_component_is_refused_whole() + { + RefusedLikeTwin("one distance A3-B0", s => s.W.CreateDistances([new Box3DSoaDistanceDesc(s.A[3], s.B[0])])); + RefusedLikeTwin("a batch: one harmless distance, then the join", s => s.W.CreateDistances([ + new Box3DSoaDistanceDesc(s.B[0], s.B[2]), new Box3DSoaDistanceDesc(s.A[3], s.B[0])])); + // the controls: woken, or with nothing tethered, the same join is accepted + using (var woke = Make()) + { + woke.W.SetPinned(woke.A[..3], false); + woke.W.CreateDistances([new Box3DSoaDistanceDesc(woke.A[3], woke.B[0])]); + Assert.Equal(woke.W.View.ParticleComponent[woke.A[0]], woke.W.View.ParticleComponent[woke.B[2]]); + } + using (var untethered = Make(tetherB: false)) + untethered.W.CreateDistances([new Box3DSoaDistanceDesc(untethered.A[3], untethered.B[0])]); + } + + [Fact] + public void A_pin_in_a_tethered_component_is_refused_whole() + { + static Scene Joined() + { + var s = Make(pinA: false); + s.W.CreateDistances([new Box3DSoaDistanceDesc(s.A[3], s.B[0])]); + return s; + } + RefusedLikeTwin("a pin of R0..R2 joined to tethered B", s => s.W.SetPinned(s.A[..3], true), Joined); + RefusedLikeTwin("a pin of R1 alone", s => s.W.SetPinned([s.A[1]], true), Joined); + } + + // ---- random command sequences --------------------------------------------------------------------------- + + private static bool Holds(Box3DSoaView v, out string why) + { + var n = v.ParticleCount; + var root = new int[n]; + for (var i = 0; i < n; i++) root[i] = i; + int Find(int i) { while (root[i] != i) i = root[i] = root[root[i]]; return i; } + for (var e = 0; e < v.DistanceCount; e++) + if (v.DistanceLive[e] != 0) root[Find(v.DistanceA[e])] = Find(v.DistanceB[e]); + var pinned = new HashSet(); + var tethered = new HashSet(); + for (var i = 0; i < n; i++) if (v.ParticleLive[i] != 0 && v.ParticlePinned[i] != 0) pinned.Add(Find(i)); + for (var a = 0; a < v.AttachmentCount; a++) + if (v.AttachmentKind[a] != (uint)Box3DSoaAttachKind.Removed && (v.AttachmentFlags[a] & 1u) != 0) tethered.Add(Find(v.AttachmentParticle[a])); + // the view's component lane names the same partition + for (var i = 0; i < n; i++) + for (var j = i + 1; j < n; j++) + if (v.ParticleLive[i] != 0 && v.ParticleLive[j] != 0 && (Find(i) == Find(j)) != (v.ParticleComponent[i] == v.ParticleComponent[j])) + { + why = $"particles {i} and {j}: component lane disagrees with the distances"; + return false; + } + pinned.IntersectWith(tethered); + why = pinned.Count == 0 ? "" : $"component of {pinned.First()} holds pinned flesh and a tether"; + return pinned.Count == 0; + } + + [Theory] + [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] [InlineData(7)] [InlineData(8)] + public void No_command_sequence_puts_pinned_flesh_and_a_tether_in_one_component(int seed) + { + const int N = 12; + var rng = new Random(seed); + using var w = new Box3DSoaWorld(8, gravityY: -10f, particles: new Box3DSoaParticleCapacities(N, 48, 32, 64, 8192, 2, 0, 0, 0)); + var bone = w.AddAnchor(1, (0f, 1f, 0f)); + var ball = w.AddSphere(5, (0f, 0.5f, 0.5f), 0.05f, 100f); + var p = new Box3DSoaParticleHandle[N]; + var desc = new Box3DSoaParticleDesc[N]; + for (var i = 0; i < N; i++) desc[i] = new Box3DSoaParticleDesc((0.06f * i, 1f, 0f), 0.02f, R, Box3DSoaPhase.Of((uint)(1 + i % 3), noParticleContact: true)); + w.CreateParticles(desc, p); + for (var i = 0; i < N; i++) w.Attach(Box3DSoaAttachKind.Body, p[i], bone, (0.06f * i, 0f, 0f), compliance: 1e-4f, limb: true, oneWay: true); + Box3DSoaParticleHandle Any() => p[rng.Next(N)]; + Box3DSoaAttachmentDesc Tether(Box3DSoaParticleHandle q) => rng.Next(2) == 0 + ? new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, q, -1, (w.View.ParticleX[q], w.View.ParticleY[q], 0f), tether: true) + : new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, q, ball, (0f, 0.5f, -0.5f), tether: true); + int accepted = 0, refused = 0, pins = 0, joins = 0, tethers = 0; + var refusedBy = new int[12]; + for (var c = 0; c < 400; c++) + { + var v = w.View; + var kind = rng.Next(12); + Action command; + switch (kind) + { + case 0: + { + var d = new Box3DSoaDistanceDesc[1 + rng.Next(2)]; + for (var k = 0; k < d.Length; k++) + { + var a = rng.Next(N); + d[k] = new Box3DSoaDistanceDesc(p[a], p[(a + 1 + rng.Next(N - 1)) % N], 1e-4f); + } + command = () => { w.CreateDistances(d); joins++; }; + break; + } + case 1: case 2: + { + var d = rng.Next(2) == 0 ? new[] { Tether(Any()) } : new[] { new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, Any(), bone, (0f, 0f, 0f)), Tether(Any()) }; + command = () => { w.Attach(d); tethers++; }; + break; + } + case 3: case 4: + { + var set = Enumerable.Range(0, 1 + rng.Next(4)).Select(_ => Any()).ToArray(); + command = () => { w.SetPinned(set, true); pins++; }; + break; + } + case 5: + { + var set = Enumerable.Range(0, 1 + rng.Next(4)).Select(_ => Any()).ToArray(); + command = () => w.SetPinned(set, false); + break; + } + case 6: case 7: case 8: + { + var live = Enumerable.Range(0, v.DistanceCount).Where(e => v.DistanceLive[e] != 0).ToArray(); + if (live.Length == 0) continue; + var e = live[rng.Next(live.Length)]; + var h = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, e, v.DistanceGeneration[e]); + command = () => w.Remove(h); + break; + } + case 9: case 10: + { + // mostly a tether, so components free up for pins again + var tethered = rng.Next(3) != 0; + var live = Enumerable.Range(0, v.AttachmentCount).Where(a => v.AttachmentKind[a] != (uint)Box3DSoaAttachKind.Removed && (!tethered || (v.AttachmentFlags[a] & 1u) != 0)).ToArray(); + if (live.Length == 0) continue; + var a = live[rng.Next(live.Length)]; + var h = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Attachment, a, v.AttachmentGeneration[a]); + command = () => w.Remove(h); + break; + } + default: + { + // a bend over two live distances sharing a particle, else a step + var live = Enumerable.Range(0, v.DistanceCount).Where(e => v.DistanceLive[e] != 0 && v.DistanceRest[e] > 0f).ToArray(); + var pair = live.SelectMany(e1 => live.Where(e2 => e2 > e1 && + ((v.DistanceA[e1] == v.DistanceA[e2] ? 1 : 0) + (v.DistanceA[e1] == v.DistanceB[e2] ? 1 : 0) + (v.DistanceB[e1] == v.DistanceA[e2] ? 1 : 0) + (v.DistanceB[e1] == v.DistanceB[e2] ? 1 : 0)) == 1) + .Select(e2 => (e1, e2))).ToArray(); + if (pair.Length == 0 || rng.Next(2) == 0) { command = () => Step(w, 1); break; } + var (x, y) = pair[rng.Next(pair.Length)]; + var b = new Box3DSoaBendDesc(new(Box3DSoaConstraintType.Distance, x, v.DistanceGeneration[x]), new(Box3DSoaConstraintType.Distance, y, v.DistanceGeneration[y])); + command = () => w.CreateBends([b]); + break; + } + } + var before = State(w); + try + { + command(); + accepted++; + } + catch (InvalidOperationException) + { + refused++; + refusedBy[kind]++; + Assert.True(before == State(w), $"seed {seed} command {c} (kind {kind}): a refusal changed a lane"); + } + Assert.True(Holds(w.View, out var why), $"seed {seed} after command {c} (kind {kind}): {why}"); + } + Console.Error.WriteLine($"PIN_TETHER seed {seed}: accepted {accepted}, refused {refused}, pins {pins}, joins {joins}, tethers {tethers}; refused joins {refusedBy[0]}, tethers {refusedBy[1] + refusedBy[2]}, pins {refusedBy[3] + refusedBy[4]}"); + Assert.True(pins > 10 && joins > 10 && tethers > 10, $"seed {seed}: the sequence exercised too little (refused {refused}, pins {pins}, joins {joins}, tethers {tethers})"); + } +}