peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
solver_position.hpp
Go to the documentation of this file.
1
10#ifndef DEM_SOLVER_POSITION_HPP
11#define DEM_SOLVER_POSITION_HPP
12
13#include <Kokkos_Core.hpp>
14#include <vector>
15
16#include "contact_preprocessing.hpp" // ContactC, CpExec/CpMem
17#include "dem_portable.hpp"
18#include "solver_fused.hpp"
19
20namespace peclet::dem {
21
22namespace detail {
23KOKKOS_INLINE_FUNCTION float computeW(F3 r, F3 dir, float invM, F3 invI) {
24 const F3 rn = cross3v(r, dir);
25 return invM + rn.x * rn.x * invI.x + rn.y * rn.y * invI.y + rn.z * rn.z * invI.z;
26}
27} // namespace detail
28
33inline void countPositionJacobi(Kokkos::View<const ContactC*, CpMem> contacts, int numContacts,
34 Kokkos::View<int*, CpMem> counts) {
35 CpExec space;
36 Kokkos::parallel_for(
37 "peclet::dem::count_position_jacobi", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
38 KOKKOS_LAMBDA(int idx) {
39 const ContactC c = contacts(idx);
40 Kokkos::atomic_add(&counts(c.bodyA), 1);
41 if (c.bodyB >= 0)
42 Kokkos::atomic_add(&counts(c.bodyB), 1);
43 });
44 space.fence();
45}
46
59inline void solvePosition(Kokkos::View<const ContactC*, CpMem> contacts, int numContacts,
60 const BodyState& bodies, const BodyPred& pred, const BodyDelta& delta,
61 Kokkos::View<float, CpMem> maxOverlap,
62 Kokkos::View<const int*, CpMem> onlyColor = {}, int colorFilter = 0,
63 bool massSplit = false) {
64 const Kokkos::View<const float*, CpMem> invMass = bodies.invMass;
65 const Kokkos::View<const float* [3], CpMem> posPred = pred.posPred;
66 const Kokkos::View<const float* [4], CpMem> quatPred = pred.quatPred;
67 const Kokkos::View<const float* [4], CpMem> quatStatic = bodies.quat;
68 const Kokkos::View<float* [3], CpMem> deltaPos = delta.deltaPos;
69 const Kokkos::View<int*, CpMem> constraintCounts = delta.constraintCounts;
70 CpExec space;
71 const bool filt = onlyColor.extent(0) > 0;
72 Kokkos::parallel_for(
73 "peclet::dem::solve_position", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
74 KOKKOS_LAMBDA(int idx) {
75 if (filt && onlyColor(idx) != colorFilter)
76 return; // colour filter (kernel unit test only; no production caller)
77 const ContactC c = contacts(idx);
78 const int idA = c.bodyA, idB = c.bodyB;
79 const float invMassA = invMass(idA);
80 const float invMassB = (idB >= 0) ? invMass(idB) : 0.0f;
81
82 const F3 pA = ldF3(posPred, idA);
83 const F4 qA = ldF4(quatPred, idA);
84 F3 pB{0, 0, 0};
85 F4 qB{0, 0, 0, 1};
86 if (idB >= 0) {
87 pB = ldF3(posPred, idB);
88 qB = ldF4(quatPred, idB);
89 }
90
91 // Delta-rotate the stored lever arms / normal from the static frame to the predicted one.
92 const F4 qAdelta = quatMult(qA, quatInverse(ldF4(quatStatic, idA)));
93 F3 rA = rotateVector(qAdelta, F3{c.rA.x, c.rA.y, c.rA.z});
94 F3 rB{c.rB.x, c.rB.y, c.rB.z};
95 F3 n{c.normal.x, c.normal.y, c.normal.z};
96 if (idB >= 0) {
97 const F4 qBdelta = quatMult(qB, quatInverse(ldF4(quatStatic, idB)));
98 rB = rotateVector(qBdelta, rB);
99 n = rotateVector(normalOfA(c) ? qAdelta : qBdelta, n); // the normal's own body
100 }
101
102 float C;
103 if (idB < 0) {
104 n = F3{c.normal.x, c.normal.y, c.normal.z}; // wall normal is static
105 const F3 pAsurf = add3(pA, rA);
106 C = dot3(sub3(pAsurf, F3{c.rB.x, c.rB.y, c.rB.z}), n);
107 } else {
108 const F3 pAc = add3(pA, rA);
109 const F3 pBc = add3(pB, rB);
110 C = dot3(sub3(pAc, pBc), n);
111 }
112 if (C >= 0.0f)
113 return;
114
115 // The translational effective mass of the solve views: the correction is translation
116 // only, so the diagonal carries no rotational term (docs/contact_physics_followups.md
117 // §3.3, WO-B1).
118 const float wA = invMassA;
119 const float wB = invMassB;
120 const float wTotal = wA + wB;
121 if (wTotal < 1e-6f)
122 return;
123 // Mass-split Jacobi: the same numerator against copies of mass m / n.
124 const float wSolve =
125 massSplit ? static_cast<float>(constraintCounts(idA)) * wA +
126 ((idB >= 0) ? static_cast<float>(constraintCounts(idB)) * wB : 0.0f)
127 : wTotal;
128
129 const float dLambda = -C / wSolve;
130
131 // Translation-only correction (applyUpdates commits deltaPos only).
132 Kokkos::atomic_add(&deltaPos(idA, 0), n.x * dLambda * invMassA);
133 Kokkos::atomic_add(&deltaPos(idA, 1), n.y * dLambda * invMassA);
134 Kokkos::atomic_add(&deltaPos(idA, 2), n.z * dLambda * invMassA);
135 if (idB >= 0) {
136 Kokkos::atomic_add(&deltaPos(idB, 0), -n.x * dLambda * invMassB);
137 Kokkos::atomic_add(&deltaPos(idB, 1), -n.y * dLambda * invMassB);
138 Kokkos::atomic_add(&deltaPos(idB, 2), -n.z * dLambda * invMassB);
139 if (!massSplit)
140 Kokkos::atomic_add(&constraintCounts(idB), 1);
141 }
142 if (!massSplit)
143 Kokkos::atomic_add(&constraintCounts(idA), 1);
144
145 if (C < 0.0f)
146 Kokkos::atomic_max(&maxOverlap(), -C);
147 });
148 space.fence();
149}
150
151// ============================ colored Gauss–Seidel position solve ============================
152// The overlap solve above is the position-side twin of the Jacobi restitution solve: one thread per
153// contact scatters an XPBD non-penetration correction, and the caller relaxes the per-body SUM by
154// the contact count (applyUpdates, 1/count). Same trade-off — stable but under-converged, so
155// a body wedged by many neighbours keeps residual overlap. The colored path removes the averaging:
156// graph- colour the CONTACT graph (vertices = body slots, edges = contacts; raw bodyA/bodyB, the
157// same indices the solve writes) so no two contacts sharing a body get one colour, then sweep
158// colour-by- colour applying each correction IN PLACE. Within a colour the contacts are an
159// independent set, so the read-modify-write is race-free without atomics, and each sweep sees the
160// previous colours' moves — a true sequential projection that resolves stacked contacts far better
161// per iteration. Translation only, matching the Jacobi path (applyUpdates applies deltaPos,
162// not deltaQuat; the angular contact response lives in the velocity solve), and it never touches
163// velocity — overlap removal stays decoupled from the velocity update.
164
166KOKKOS_INLINE_FUNCTION bool unitAsleep(const PosUnits& units,
167 const Kokkos::View<const unsigned char*, CpMem>& sleepMask,
168 int u) {
169 for (int k = units.begin(u); k < units.end(u); ++k)
170 if (!sleepMask(units.contact(k)))
171 return false;
172 return true;
173}
174
177struct UnitEdges {
178 Kokkos::View<const ContactC*, CpMem> contacts;
179 Kokkos::View<const unsigned char*, CpMem> sleepMask;
183 static constexpr ColorLabels labels() {
184 return {"peclet::dem::pcolor_init_bodies", "peclet::dem::pcolor_init_contacts",
185 "peclet::dem::pcolor_reset_winner", "peclet::dem::pcolor_contend",
186 "peclet::dem::pcolor_commit", "peclet::dem::pcolor_max",
187 "peclet::dem::pcolor_leftover"};
188 }
189 KOKKOS_INLINE_FUNCTION int initialColor(int idx) const {
190 return (sleepOn && unitAsleep(units, sleepMask, idx)) ? -2 : -1;
191 }
192 KOKKOS_INLINE_FUNCTION ColorEdge edge(int idx) const {
193 const int lead = units.leader(idx); // a unit's edge: its leader's bodies and key
194 const ContactC c = contacts(lead);
195 const int ea = ov.slotA(idx, c.bodyA);
196 const int eb = (c.bodyB >= 0) ? ov.slotB(idx, c.bodyB) : -1; // <0: wall/boundary
197 return {ea, eb, colorKey(lead)}; // hashed priority (see colorKey)
198 }
199};
200
210inline int colorContacts(Kokkos::View<const ContactC*, CpMem> contacts, int numContacts,
211 int numBodies, Kokkos::View<int*, CpMem> cColor,
212 const ColorScratch& scratch, int& leftover,
213 Kokkos::View<const unsigned char*, CpMem> sleepMask = {},
214 PosUnits units = {}, SlotOverride ov = {}, int vertexSpan = 0) {
215 const UnitEdges edges{contacts, sleepMask, units, ov, sleepMask.extent(0) > 0};
216 return colorEdges(edges, numContacts, numBodies, vertexSpan, cColor, scratch, leftover);
217}
218
228inline int colorContactsIncremental(Kokkos::View<const ContactC*, CpMem> contacts, int numContacts,
229 int numBodies, const CarriedColors& carried,
230 Kokkos::View<int*, CpMem> cColor,
231 Kokkos::View<unsigned long long*, CpMem> keysOut,
232 const ColorScratch& scratch, int& leftover, bool forceFull,
233 Kokkos::View<const unsigned char*, CpMem> sleepMask = {},
234 PosUnits units = {}) {
235 const Kokkos::View<const unsigned long long*, CpMem> prevKeys = carried.keys;
236 const Kokkos::View<const int*, CpMem> prevColor = carried.color;
237 const int prevCount = carried.count;
238 const Kokkos::View<long long*, CpMem> bodyWinner = scratch.bodyWinner;
239 const Kokkos::View<std::uint64_t*, CpMem> bodyMask = scratch.bodyColorMask;
240 leftover = 0;
241 CpExec space;
242 if (numContacts <= 0 || numBodies <= 0)
243 return 0;
244 const bool full0 = forceFull || prevCount <= 0;
245 const bool sleepOn = sleepMask.extent(0) > 0;
246 // Key every contact and seed its colour from the carried ledger (or -1 on a full recolour, or
247 // -2 for a frozen both-asleep contact — excluded from the sweeps like an inactive one).
248 Kokkos::parallel_for(
249 "peclet::dem::pcolor_i_seed", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
250 KOKKOS_LAMBDA(int idx) {
251 // Every contact of the unit records its own pair key for the per-contact commit; the unit
252 // is seeded from its leader's key (identical to the per-contact seed for a one-point unit).
253 for (int k2 = units.begin(idx); k2 < units.end(idx); ++k2) {
254 const int ci = units.contact(k2);
255 keysOut(ci) = pairKey(contacts(ci));
256 }
257 const unsigned long long k = keysOut(units.leader(idx));
258 if (sleepOn && unitAsleep(units, sleepMask, idx)) {
259 cColor(idx) = -2;
260 return;
261 }
262 int col = -1;
263 if (!full0) {
264 int lo = 0, hi = prevCount;
265 while (lo < hi) {
266 const int mid = (lo + hi) >> 1;
267 if (prevKeys(mid) < k)
268 lo = mid + 1;
269 else
270 hi = mid;
271 }
272 if (lo < prevCount && prevKeys(lo) == k) {
273 const int pc = prevColor(lo);
274 if (pc >= 0)
275 col = pc;
276 }
277 }
278 cColor(idx) = col;
279 });
280 Kokkos::parallel_for(
281 "peclet::dem::pcolor_i_init_bodies", Kokkos::RangePolicy<CpExec>(space, 0, numBodies),
282 KOKKOS_LAMBDA(int i) { bodyMask(i) = 0; });
283 if (!full0) {
284 // Seed the per-body masks from carried colours, self-healing any conflict WITHOUT a host sync
285 // (a host readback here stalls the async submission pipeline and measured net-slower than the
286 // launches it saves). atomic_fetch_or serialises the claim: a contact that finds its colour bit
287 // already set at either endpoint DEMOTES itself to -1 and is re-arbitrated in the rounds below.
288 // A demoted contact may leave a spurious set bit at its other endpoint, but a spurious bit only
289 // over-constrains (forbids one colour there) — it never lets two same-colour contacts share a
290 // body, so the colouring stays valid. The sphere / non-periodic bed has no conflicts (one
291 // contact per pair, stable slots) and hits the pure carry path.
292 Kokkos::parallel_for(
293 "peclet::dem::pcolor_i_mask", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
294 KOKKOS_LAMBDA(int idx) {
295 const int col = cColor(idx);
296 if (col < 0)
297 return;
298 const ContactC c = contacts(units.leader(idx));
299 const std::uint64_t bit = std::uint64_t(1) << col;
300 bool conflict = ((Kokkos::atomic_fetch_or(&bodyMask(c.bodyA), bit) >> col) & 1) != 0;
301 if (c.bodyB >= 0)
302 conflict |= ((Kokkos::atomic_fetch_or(&bodyMask(c.bodyB), bit) >> col) & 1) != 0;
303 if (conflict)
304 cColor(idx) = -1; // re-arbitrate in the rounds
305 });
306 }
307 // Jones-Plassmann rounds over the uncoloured (-1) contacts only (identical to
308 // colorContacts).
309 int remaining = 1, prevRemaining = -1;
310 // Round cap (docs/contact_solve_framework.md §12 S7): the vertices coloured are the UNITS
311 // (numContacts here), so the bound is their count + 2. Each round commits at least the
312 // globally highest-key uncoloured unit (colorKey(leader) is unique: the leader index is its
313 // low word), so the loop terminates within numContacts rounds; O(log n) in practice.
314 const int maxRounds = numContacts + 2;
315 for (int round = 0; round < maxRounds && remaining > 0; ++round) {
316 Kokkos::parallel_for(
317 "peclet::dem::pcolor_i_reset_winner", Kokkos::RangePolicy<CpExec>(space, 0, numBodies),
318 KOKKOS_LAMBDA(int i) { bodyWinner(i) = -1; });
319 Kokkos::parallel_for(
320 "peclet::dem::pcolor_i_contend", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
321 KOKKOS_LAMBDA(int idx) {
322 if (cColor(idx) != -1)
323 return;
324 const int lead = units.leader(idx); // a unit's edge: its leader's bodies and key
325 const ContactC c = contacts(lead);
326 const long long key = colorKey(lead);
327 Kokkos::atomic_max(&bodyWinner(c.bodyA), key);
328 if (c.bodyB >= 0)
329 Kokkos::atomic_max(&bodyWinner(c.bodyB), key);
330 });
331 int rem = 0;
332 Kokkos::parallel_reduce(
333 "peclet::dem::pcolor_i_commit", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
334 KOKKOS_LAMBDA(int idx, int& acc) {
335 if (cColor(idx) != -1)
336 return;
337 const int lead = units.leader(idx);
338 const ContactC c = contacts(lead);
339 const int ea = c.bodyA;
340 const int eb = c.bodyB;
341 const long long key = colorKey(lead);
342 if (bodyWinner(ea) != key || (eb >= 0 && bodyWinner(eb) != key)) {
343 acc += 1;
344 return;
345 }
346 std::uint64_t forbidden = bodyMask(ea);
347 if (eb >= 0)
348 forbidden |= bodyMask(eb);
349 int col = 0; // lowest free colour of 64; never forced (§4.2 item 1)
350 while (col < kColorPalette && ((forbidden >> col) & 1))
351 ++col;
352#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 3
353 if (col > 62)
354 col = 62; // G13 mutant 3: the old forced colour 62
355#endif
356 if (col == kColorPalette) {
357 cColor(idx) = kColorUncolourable;
358 return;
359 }
360 cColor(idx) = col;
361 const std::uint64_t bit = std::uint64_t(1) << col;
362 bodyMask(ea) |= bit;
363 if (eb >= 0)
364 bodyMask(eb) |= bit;
365 },
366 rem);
367 space.fence();
368 if (rem == prevRemaining)
369 break;
370 prevRemaining = rem;
371 remaining = rem;
372 }
373 int maxc = -1;
374 Kokkos::parallel_reduce(
375 "peclet::dem::pcolor_i_max", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
376 KOKKOS_LAMBDA(int idx, int& mx) {
377 if (cColor(idx) > mx)
378 mx = cColor(idx);
379 },
380 Kokkos::Max<int>(maxc));
381 Kokkos::parallel_reduce(
382 "peclet::dem::pcolor_i_leftover", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
383 KOKKOS_LAMBDA(int idx, int& acc) {
384 if (cColor(idx) == -1 || cColor(idx) == kColorUncolourable)
385 acc += 1;
386 },
387 leftover);
388 space.fence();
389 return maxc + 1;
390}
391
393inline void expandUnitColors(const PosUnits& units, int numUnits,
394 Kokkos::View<const int*, CpMem> unitColor,
395 Kokkos::View<int*, CpMem> contactColor) {
396 if (numUnits <= 0)
397 return;
398 CpExec space;
399 Kokkos::parallel_for(
400 "peclet::dem::pcolor_expand", Kokkos::RangePolicy<CpExec>(space, 0, numUnits),
401 KOKKOS_LAMBDA(int u) {
402 const int col = unitColor(u);
403 for (int k = units.begin(u); k < units.end(u); ++k)
404 contactColor(units.contact(k)) = col;
405 });
406}
407
409inline void commitContactColor(Kokkos::View<const unsigned long long*, CpMem> keys,
410 Kokkos::View<const int*, CpMem> color,
411 Kokkos::View<unsigned long long*, CpMem> prevKeys,
412 Kokkos::View<int*, CpMem> prevColor, Kokkos::View<int*, CpMem> perm,
413 int numContacts) {
414 if (numContacts <= 0)
415 return;
416 CpExec space;
417 const int n = numContacts;
418 const auto rng = Kokkos::pair<int, int>(0, n);
419 auto kd = Kokkos::subview(prevKeys, rng);
420 Kokkos::deep_copy(space, kd, Kokkos::subview(keys, rng));
421 Kokkos::parallel_for(
422 "peclet::dem::pcolor_commit_iota", Kokkos::RangePolicy<CpExec>(space, 0, n),
423 KOKKOS_LAMBDA(int i) { perm(i) = i; });
424 {
425 auto pd = Kokkos::subview(perm, rng);
426 Kokkos::Experimental::sort_by_key(space, kd, pd);
427 }
428 Kokkos::View<int*, CpMem> pc = prevColor;
429 Kokkos::View<const int*, CpMem> c = color;
430 Kokkos::parallel_for(
431 "peclet::dem::pcolor_commit_gather", Kokkos::RangePolicy<CpExec>(space, 0, n),
432 KOKKOS_LAMBDA(int i) { pc(i) = c(perm(i)); });
433 space.fence();
434}
435
440 Kokkos::View<const ContactC*, CpMem> contacts;
441 Kokkos::View<const float*, CpMem> invMass;
442 Kokkos::View<float* [3], CpMem> posPred;
443 Kokkos::View<const float* [4], CpMem> quatPred;
444 Kokkos::View<const float* [4], CpMem> quatStatic;
445 Kokkos::View<const float* [3], CpMem> invInertia;
446 Kokkos::View<float, CpMem> maxOverlap;
447 Kokkos::View<float*, CpMem> posLambdaAcc;
448
449 PosUnits units; // empty = one contact per work item (the identity)
450 // Hub-copy slot overrides per UNIT (docs/contact_solve_framework.md §4.4); empty = the raw
451 // contact bodies.
453 // Accumulated projection (WO-12, §13.5; USER 2026-09-26): with a stop residual view and the
454 // per-contact ledger posLambdaAcc, each contact's net push Lambda >= 0 is projected,
455 // Lambda' = max(0, Lambda - omega C / w), and the CHANGE d = Lambda' - Lambda is applied -- it
456 // may be negative (an overshoot is retracted), so over-relaxation omega in (0, 2) is legitimate
457 // and the fixed point is the unique least-displacement solution. posResidual collects max |d| w
458 // (the position change), the stop quantity; maxOverlap keeps "the largest violation seen". Empty
459 // posResidual = the pre-WO-12 incremental projection at omega 1 (kernel unit tests only).
460 Kokkos::View<float, CpMem> posResidual{};
461 float omega = 1.0f;
462
466 KOKKOS_FUNCTION void solveOne(int u) const {
467 for (int k = units.begin(u); k < units.end(u); ++k)
468 solveContact(units.contact(k), u);
469 }
470
471 KOKKOS_FUNCTION void solveContact(int idx, int u) const {
472 const ContactC c = contacts(idx);
473 int idA = c.bodyA, idB = c.bodyB;
474 if (ov.a.extent(0) > 0) {
475 // The unit's overrides are keyed by its leader's (bodyA, bodyB); a contact of the unit may
476 // list the pair in either order, so map each end by body.
477 const ContactC L = contacts(units.leader(u));
478 idA = (c.bodyA == L.bodyA) ? ov.slotA(u, c.bodyA) : ov.slotB(u, c.bodyA);
479 if (c.bodyB >= 0)
480 idB = (c.bodyB == L.bodyA) ? ov.slotA(u, c.bodyB) : ov.slotB(u, c.bodyB);
481 }
482 const float invMassA = invMass(idA);
483 const float invMassB = (idB >= 0) ? invMass(idB) : 0.0f;
484
485 const F3 pA = ldF3(posPred, idA);
486 const F4 qA = ldF4(quatPred, idA);
487 F3 pB{0, 0, 0};
488 F4 qB{0, 0, 0, 1};
489 if (idB >= 0) {
490 pB = ldF3(posPred, idB);
491 qB = ldF4(quatPred, idB);
492 }
493
494 const F4 qAdelta = quatMult(qA, quatInverse(ldF4(quatStatic, idA)));
495 F3 rA = rotateVector(qAdelta, F3{c.rA.x, c.rA.y, c.rA.z});
496 F3 rB{c.rB.x, c.rB.y, c.rB.z};
497 F3 n{c.normal.x, c.normal.y, c.normal.z};
498 if (idB >= 0) {
499 const F4 qBdelta = quatMult(qB, quatInverse(ldF4(quatStatic, idB)));
500 rB = rotateVector(qBdelta, rB);
501 n = rotateVector(normalOfA(c) ? qAdelta : qBdelta, n); // the normal's own body
502 }
503
504 float C;
505 if (idB < 0) {
506 n = F3{c.normal.x, c.normal.y, c.normal.z};
507 const F3 pAsurf = add3(pA, rA);
508 C = dot3(sub3(pAsurf, F3{c.rB.x, c.rB.y, c.rB.z}), n);
509 } else {
510 const F3 pAc = add3(pA, rA);
511 const F3 pBc = add3(pB, rB);
512 C = dot3(sub3(pAc, pBc), n);
513 }
514 const bool accumulated = posResidual.extent(0) > 0 && posLambdaAcc.extent(0) > 0;
515 const float lam = accumulated ? posLambdaAcc(idx) : 0.0f;
516 if (C >= 0.0f && lam <= 0.0f)
517 return; // separated and never pushed: nothing to project or retract
518
519 // The translational effective mass of the solve views (invMass* = k invM under mass
520 // splitting; a wall side 0): the correction below is translation only, so the diagonal has
521 // no rotational term, and |dLambda| wTotal is the true relative position change
522 // (docs/contact_physics_followups.md §3.3, WO-B1).
523 const float wTotal = invMassA + invMassB;
524 if (wTotal < 1e-6f)
525 return;
526 if (C < 0.0f)
527 Kokkos::atomic_max(&maxOverlap(), -C);
528 float dLambda;
529 if (accumulated) {
530#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 7
531 // G13 mutant 7: over-relaxed WITHOUT retraction (the pre-WO-12 defect: a permanent gap).
532 const float lamNew = Kokkos::fmax(lam, lam - omega * C / wTotal);
533#else
534 const float lamNew = Kokkos::fmax(0.0f, lam - omega * C / wTotal);
535#endif
536 dLambda = lamNew - lam;
537 if (dLambda == 0.0f)
538 return;
539 posLambdaAcc(idx) = lamNew; // the unit's work item owns the contact: plain RMW
540 Kokkos::atomic_max(&posResidual(), Kokkos::fabs(dLambda) * wTotal);
541 } else {
542 dLambda = -C / wTotal;
543 if (posLambdaAcc.extent(0) > 0)
544 Kokkos::atomic_add(&posLambdaAcc(idx), dLambda);
545 }
546 // Position-channel normal load bookkeeping: posLambdaAcc is the contact's NET position
547 // impulse (the friction cone must see the TOTAL normal force; the caller converts it to
548 // impulse units and carries it into the next substep's Coulomb bound -- else a jostled bed's
549 // bound under-counts and stick leaks, measured as 99% sliding wall contacts in the drum).
550
551 // Translation-only correction, in place (rotation discarded to match applyUpdates).
552 posPred(idA, 0) += n.x * dLambda * invMassA;
553 posPred(idA, 1) += n.y * dLambda * invMassA;
554 posPred(idA, 2) += n.z * dLambda * invMassA;
555 if (idB >= 0) {
556 posPred(idB, 0) += -n.x * dLambda * invMassB;
557 posPred(idB, 1) += -n.y * dLambda * invMassB;
558 posPred(idB, 2) += -n.z * dLambda * invMassB;
559 }
560 }
561};
562
572 Kokkos::View<const ContactC*, CpMem> contacts, const PosUnits& units, int numContacts,
573 const ColorSchedule& sched, Kokkos::View<const float*, CpMem> invMass,
574 Kokkos::View<float* [3], CpMem> posPred, Kokkos::View<const float* [4], CpMem> quatPred,
575 Kokkos::View<const float* [4], CpMem> quatStatic,
576 Kokkos::View<const float* [3], CpMem> invInertia, Kokkos::View<float, CpMem> maxOverlap,
577 Kokkos::View<float*, CpMem> posLambdaAcc = {}, const FusedLoopSpec* loop = nullptr,
578 SlotOverride ov = {}, Kokkos::View<float, CpMem> posResidual = {}, float omega = 1.0f) {
579 const Kokkos::View<const int*, CpMem> cColor = sched.color;
580 const int numColors = sched.numColors;
581 const Kokkos::View<const int*, CpMem> colorPerm = sched.perm;
582 const std::vector<int>* colorOffs = sched.offs;
583 const FusedSweepCtx* fused = sched.fused;
584 CpExec space;
585 const PositionContactSweep f{contacts, invMass, posPred, quatPred, quatStatic, invInertia,
586 maxOverlap, posLambdaAcc, units, ov, posResidual, omega};
587#ifdef KOKKOS_ENABLE_CUDA
588 if (loop) {
589 // The device loop's stop residual: the position change under the accumulated projection
590 // (WO-12), else the overlap.
591 if (fused && fused->maxBucket > 0 && colorOffs)
592 return demLaunchFusedSweepLoop(
593 space, f, colorPerm, *fused, numColors, *loop,
594 posResidual.extent(0) > 0 ? posResidual.data() : maxOverlap.data());
595 return false;
596 }
597 if (fused && fused->maxBucket > 0 && colorOffs &&
598 demLaunchFusedColorSweep(space, f, colorPerm, *fused, numColors))
599 return true;
600#else
601 (void)fused;
602 if (loop)
603 return false;
604#endif
605 for (int color = 0; color < numColors; ++color) {
606 if (colorOffs) {
607 const int b = (*colorOffs)[color], e = (*colorOffs)[color + 1];
608 if (b == e)
609 continue;
610 Kokkos::parallel_for(
611 "peclet::dem::solve_position_gs", Kokkos::RangePolicy<CpExec>(space, b, e),
612 KOKKOS_LAMBDA(int i2) { f.solveOne(colorPerm(i2)); });
613 } else {
614 Kokkos::parallel_for(
615 "peclet::dem::solve_position_gs", Kokkos::RangePolicy<CpExec>(space, 0, numContacts),
616 KOKKOS_LAMBDA(int idx) {
617 if (cColor(idx) == color)
618 f.solveOne(idx);
619 });
620 }
621 // Stream-ordered on the device, so colour c+1 already sees colour c's moves — no host fence per
622 // colour (that would only stall the host). No trailing fence either: the caller's residual
623 // readback synchronizes, and a fence here would break CUDA-graph capture of the sweep.
624 }
625 return true;
626}
627
628} // namespace peclet::dem
629
630#endif // DEM_SOLVER_POSITION_HPP
dem — portable (Kokkos) contact->manifold reduction, replacing the thrust-based reduce_contacts_to_ma...
dem — portable POD types + math + analytic SDFs shared by the Kokkos kernel ports.
float computeW(F3 r, F3 dir, float invM, F3 invI)
F4 quatMult(F4 a, F4 b)
std::uint64_t pairKey(const ContactC &c)
Canonical pair key: (min<<32)|max, or (idA<<32)|0xFFFFFFFF for a boundary (idB<0) contact.
int colorEdges(const EdgeAccessor &edges, int numEdges, int numVertices, int vertexSpan, Kokkos::View< int *, CpMem > color, const ColorScratch &scratch, int &leftover)
Greedy graph colouring of an edge set: no two edges sharing a colouring vertex get the same colour.
bool solvePositionColoredGS(Kokkos::View< const ContactC *, CpMem > contacts, const PosUnits &units, int numContacts, const ColorSchedule &sched, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< float *[3], CpMem > posPred, Kokkos::View< const float *[4], CpMem > quatPred, Kokkos::View< const float *[4], CpMem > quatStatic, Kokkos::View< const float *[3], CpMem > invInertia, Kokkos::View< float, CpMem > maxOverlap, Kokkos::View< float *, CpMem > posLambdaAcc={}, const FusedLoopSpec *loop=nullptr, SlotOverride ov={}, Kokkos::View< float, CpMem > posResidual={}, float omega=1.0f)
Colored Gauss–Seidel XPBD overlap solve: sweep the numColors colour classes in order,...
F4 quatInverse(F4 q)
F3 cross3v(F3 a, F3 b)
int colorContacts(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, int numBodies, Kokkos::View< int *, CpMem > cColor, const ColorScratch &scratch, int &leftover, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, PosUnits units={}, SlotOverride ov={}, int vertexSpan=0)
Greedy graph-colour the contacts (raw bodyA/bodyB): no two contacts sharing a body get the same colou...
CpExec::memory_space CpMem
bool unitAsleep(const PosUnits &units, const Kokkos::View< const unsigned char *, CpMem > &sleepMask, int u)
A position unit is sleep-inactive iff all its contacts are sleep-masked (§4.3).
F3 ldF3(const V &v, int i)
F3 rotateVector(F4 q, F3 v)
int colorContactsIncremental(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, int numBodies, const CarriedColors &carried, Kokkos::View< int *, CpMem > cColor, Kokkos::View< unsigned long long *, CpMem > keysOut, const ColorScratch &scratch, int &leftover, bool forceFull, Kokkos::View< const unsigned char *, CpMem > sleepMask={}, PosUnits units={})
Incremental (warm-started) contact colouring for the single-GPU PGS position solve.
float dot3(F3 a, F3 b)
F3 sub3(F3 a, F3 b)
void commitContactColor(Kokkos::View< const unsigned long long *, CpMem > keys, Kokkos::View< const int *, CpMem > color, Kokkos::View< unsigned long long *, CpMem > prevKeys, Kokkos::View< int *, CpMem > prevColor, Kokkos::View< int *, CpMem > perm, int numContacts)
Commit this substep's per-contact (key, colour) sorted by key, for next substep's warm gather.
Kokkos::DefaultExecutionSpace CpExec
F4 ldF4(const V &v, int i)
long long colorKey(int idx)
splitmix32 finalizer: a well-mixed pseudo-random priority per edge index.
constexpr int kColorUncolourable
F3 add3(F3 a, F3 b)
void solvePosition(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, const BodyState &bodies, const BodyPred &pred, const BodyDelta &delta, Kokkos::View< float, CpMem > maxOverlap, Kokkos::View< const int *, CpMem > onlyColor={}, int colorFilter=0, bool massSplit=false)
Accumulate XPBD position corrections for numContacts contacts.
constexpr int kColorPalette
Colouring palette (docs/contact_solve_framework.md §4.2 item 1): the greedy takes the lowest colour f...
void countPositionJacobi(Kokkos::View< const ContactC *, CpMem > contacts, int numContacts, Kokkos::View< int *, CpMem > counts)
Mass-split Jacobi count pass (docs/contact_solve_framework.md §3.1, D3): per body slot,...
bool normalOfA(const ContactC &c)
Which body's surface a contact's normal belongs to.
void expandUnitColors(const PosUnits &units, int numUnits, Kokkos::View< const int *, CpMem > unitColor, Kokkos::View< int *, CpMem > contactColor)
Copy each position unit's colour onto its contacts (contactColor(i) = unitColor(unit of i)).
dem — fused colour sweeps: one persistent kernel per sweep instead of one kernel launch per colour.
The solve's per-body accumulators: position/orientation and velocity corrections and the per-body con...
Kokkos::View< float *[3], CpMem > deltaPos
Kokkos::View< int *, CpMem > constraintCounts
The substep's predicted body state (Particles::bodyPred()).
Kokkos::View< float *[3], CpMem > posPred
Kokkos::View< float *[4], CpMem > quatPred
A body's state, one row per particle slot (Particles::bodyState()).
Kokkos::View< float *, CpMem > invMass
Kokkos::View< float *[4], CpMem > quat
The previous substep's colour ledger for an incremental colouring: the key-sorted pair keys,...
Kokkos::View< const unsigned long long *, CpMem > keys
Kokkos::View< const int *, CpMem > color
One colouring edge as the arbitration sees it: the colouring vertices of its A / B ends (b = -1 for a...
Kernel labels of one colorEdges instantiation (each caller keeps its own profiling names).
The colour schedule of one coloured Gauss–Seidel sweep: each item's colour and the colour count,...
Kokkos::View< const int *, CpMem > perm
const FusedSweepCtx * fused
const std::vector< int > * offs
Kokkos::View< const int *, CpMem > color
Per-vertex scratch of the Jones-Plassmann colourings: the round's winning edge key and the committed-...
Kokkos::View< long long *, CpMem > bodyWinner
Kokkos::View< std::uint64_t *, CpMem > bodyColorMask
Portable mirror of ParticleSystem.cuh ContactConstraint (the fields this reduction touches).
Device-side context for a fused colour sweep: the colour offsets (numColors+1, uploaded from buildCol...
The position units of a contact list as a CSR (§4.3): unit u owns the contacts list(start(u)) .
The per-contact overlap-projection body lives in PositionContactSweep so the colored launch loop and ...
Kokkos::View< float *, CpMem > posLambdaAcc
Kokkos::View< const float *[4], CpMem > quatPred
Kokkos::View< float, CpMem > posResidual
Kokkos::View< const float *[4], CpMem > quatStatic
Kokkos::View< float, CpMem > maxOverlap
Kokkos::View< const float *[3], CpMem > invInertia
void solveContact(int idx, int u) const
Kokkos::View< const ContactC *, CpMem > contacts
Kokkos::View< float *[3], CpMem > posPred
void solveOne(int u) const
One work item: every contact of position unit u, sequentially in ascending contact index (a pair's po...
Kokkos::View< const float *, CpMem > invMass
Per-edge slot overrides of a phase's hub copies (docs/contact_solve_framework.md §4....
The position-unit edge source of colorEdges: a unit's edge is its leader contact's raw (bodyA,...
ColorEdge edge(int idx) const
Kokkos::View< const ContactC *, CpMem > contacts
Kokkos::View< const unsigned char *, CpMem > sleepMask
static constexpr ColorLabels labels()
int initialColor(int idx) const