2#include <glm/mat4x4.hpp>
27constexpr float kPi = 3.14159265358979323846f;
29int64_t
pairKey(
int lo,
int hi) {
return (int64_t(lo) << 32) | int64_t(hi); }
33 float x = 0.f,
y = 0.f,
z = 0.f;
36V3
sub(
const V3&
a,
const V3&
b) {
return {
a.
x -
b.x,
a.y -
b.y,
a.z -
b.z}; }
37V3
add(
const V3&
a,
const V3&
b) {
return {
a.
x +
b.x,
a.y +
b.y,
a.z +
b.z}; }
38V3
mul(
float s,
const V3&
a) {
return {
s *
a.
x,
s *
a.y,
s *
a.z}; }
39V3 fma(
const V3&
a,
float s,
const V3&
b) {
return {
a.x *
s +
b.x,
a.y *
s +
b.y,
a.z *
s +
b.z}; }
40float dot(
const V3&
a,
const V3&
b) {
return a.x *
b.x +
a.y *
b.y +
a.z *
b.z; }
41V3
cross(
const V3&
a,
const V3&
b) {
return {
a.
y *
b.z -
a.z *
b.y,
a.z *
b.x -
a.x *
b.z,
a.x *
b.y -
a.y *
b.x}; }
42float vlen(
const V3&
a) {
return std::sqrt(
dot(
a,
a)); }
43V3 vnorm(
const V3&
a) {
44 const float l = vlen(
a);
45 return l > 1e-8f ?
mul(1.f / l,
a) : V3{0.f, 1.f, 0.f};
49V3 rotateAround(
const V3&
v,
const V3&
axis,
float angle) {
50 const float c = std::cos(
angle);
51 const float sn = std::sin(
angle);
58float signedAngle(
const V3&
a,
const V3&
b,
const V3&
u) {
return std::atan2(
dot(
cross(
a,
b),
u),
dot(
a,
b)); }
61V3 closestPointSegment(
const V3&
a,
const V3&
b,
const V3&
p) {
64 if (len2 < 1e-12f)
return a;
65 const float t = std::clamp(
dot(
sub(
p,
a),
ab) / len2, 0.f, 1.f);
70V3 closestPointTriangle(
const V3&
a,
const V3&
b,
const V3&
c,
const V3&
p) {
73 const V3 ap =
sub(
p,
a);
74 const float d1 =
dot(
ab, ap);
75 const float d2 =
dot(
ac, ap);
76 if (d1 <= 0.f && d2 <= 0.f)
return a;
78 const V3 bp =
sub(
p,
b);
79 const float d3 =
dot(
ab, bp);
80 const float d4 =
dot(
ac, bp);
81 if (d3 >= 0.f && d4 <= d3)
return b;
83 const float vc = d1 * d4 - d3 * d2;
84 if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f) {
85 const float t = d1 / (d1 - d3);
89 const V3 cp =
sub(
p,
c);
90 const float d5 =
dot(
ab, cp);
91 const float d6 =
dot(
ac, cp);
92 if (d6 >= 0.f && d5 <= d6)
return c;
94 const float vb = d5 * d2 - d1 * d6;
95 if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f) {
96 const float t = d2 / (d2 - d6);
100 const float va = d3 * d6 - d5 * d4;
101 if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f) {
102 const float t = (d4 - d3) / ((d4 - d3) + (d5 - d6));
106 const float denom = 1.f / (va + vb + vc);
107 const float v = vb * denom;
108 const float w = vc * denom;
113float closestPointSegments(
const V3& p1,
const V3& p2,
const V3& q1,
const V3& q2, V3& cp1, V3& cp2) {
114 const V3 d1 =
sub(p2, p1);
115 const V3 d2 =
sub(q2, q1);
116 const V3
r =
sub(p1, q1);
117 const float a =
dot(d1, d1);
118 const float e =
dot(d2, d2);
119 const float f =
dot(d2,
r);
122 if (
a <= 1e-12f && e <= 1e-12f) {
124 }
else if (
a <= 1e-12f) {
126 t = std::clamp(
f / e, 0.f, 1.f);
128 const float c =
dot(d1,
r);
131 s = std::clamp(-
c /
a, 0.f, 1.f);
133 const float b =
dot(d1, d2);
134 const float denom =
a * e -
b *
b;
135 s = denom > 1e-12f ? std::clamp((
b *
f -
c * e) / denom, 0.f, 1.f) : 0.f;
139 s = std::clamp(-
c /
a, 0.f, 1.f);
140 }
else if (
t > 1.f) {
142 s = std::clamp((
b -
c) /
a, 0.f, 1.f);
146 cp1 = fma(d1,
s, p1);
147 cp2 = fma(d2,
t, q1);
148 return vlen(
sub(cp1, cp2));
151bool pointInTriangle(
const V3&
p,
const V3&
a,
const V3&
b,
const V3&
c) {
156 return dot(pa,
n) >= -1e-8f &&
dot(pb,
n) >= -1e-8f &&
dot(pc,
n) >= -1e-8f;
161float triangleDistance(
const V3* A,
const V3* B,
int featA[3],
int featB[3],
int& countA,
int& countB, V3& cpA,
163 float best = std::numeric_limits<float>::max();
165 for (
int i = 0; i < 3; ++i) {
166 const V3 cp = closestPointTriangle(B[0], B[1], B[2], A[i]);
167 const float d = vlen(
sub(A[i], cp));
180 for (
int j = 0; j < 3; ++j) {
181 const V3 cp = closestPointTriangle(A[0], A[1], A[2], B[j]);
182 const float d = vlen(
sub(B[j], cp));
195 const int aEdges[3][2] = {{0, 1}, {1, 2}, {2, 0}};
196 const int bEdges[3][2] = {{0, 1}, {1, 2}, {2, 0}};
197 for (
const auto& ea : aEdges) {
198 for (
const auto& eb : bEdges) {
201 const float d = closestPointSegments(A[ea[0]], A[ea[1]], B[eb[0]], B[eb[1]], cp1, cp2);
220 : cols_(
cols), rows_(
rows), spacing_(
spacing), originX_(originX), originY_(originY), originZ_(originZ) {
223 throw Exception(
"%s",
model.error() ?
model.error()->message().c_str() :
"Cloth3D grid model creation failed");
224 initializeFromModel(
model.value());
234 particles_ = restParticles_;
236 forceX_ = forceY_ = forceZ_ = 0.f;
237 interactStrength_ = 0.f;
240void Cloth3D::rebuildLinks() {
242 auto add = [&](
int a,
int b) {
247 const Particle& pa = particles_[
static_cast<size_t>(
a)];
248 const Particle& pb = particles_[
static_cast<size_t>(
b)];
249 const float dx = pb.x - pa.x;
250 const float dy = pb.y - pa.y;
251 const float dz = pb.z - pa.z;
253 if (
link.rest > 1e-4f) links_.push_back(
link);
256 for (
int r = 0;
r < rows_; ++
r) {
257 for (
int c = 0;
c < cols_; ++
c) {
258 const int i =
r * cols_ +
c;
260 if (
c + 1 < cols_)
add(i, i + 1);
261 if (
r + 1 < rows_)
add(i, i + cols_);
263 if (
c + 1 < cols_ &&
r + 1 < rows_)
add(i, i + cols_ + 1);
264 if (
c > 0 &&
r + 1 < rows_)
add(i, i + cols_ - 1);
266 if (
c + 2 < cols_)
add(i, i + 2);
267 if (
r + 2 < rows_)
add(i, i + cols_ * 2);
273void Cloth3D::buildLinkKeys() {
275 for (
const Link&
link : links_) {
276 const int lo = std::min(
link.a,
link.b);
277 const int hi = std::max(
link.a,
link.b);
278 linkKeys_.insert(
pairKey(lo, hi));
282bool Cloth3D::areLinked(
int a,
int b)
const {
283 if (
a ==
b)
return true;
284 const int lo = std::min(
a,
b);
285 const int hi = std::max(
a,
b);
286 return linkKeys_.find(
pairKey(lo, hi)) != linkKeys_.end();
289void Cloth3D::rebuildTriangles() {
294 std::unordered_map<int64_t, std::vector<int>> edgeTris;
295 auto addTri = [&](
int a,
int b,
int c, std::unordered_map<int64_t, std::vector<int>>& map) {
300 const int idx =
static_cast<int>(triangles_.size());
302 for (
const auto& e :
edges) {
303 map[
pairKey(std::min(e[0], e[1]), std::max(e[0], e[1]))].push_back(
idx);
305 triangles_.push_back(tri);
308 for (
int r = 0;
r + 1 < rows_; ++
r) {
309 for (
int c = 0;
c + 1 < cols_; ++
c) {
310 const int a =
r * cols_ +
c;
311 const int b =
r * cols_ +
c + 1;
312 const int cc = (
r + 1) * cols_ +
c + 1;
313 const int d = (
r + 1) * cols_ +
c;
314 addTri(
a,
d,
b, edgeTris);
315 addTri(
d, cc,
b, edgeTris);
319 for (
const auto& entry : edgeTris) {
320 if (entry.second.size() != 2)
continue;
321 const Tri& t0 = triangles_[
static_cast<size_t>(entry.second[0])];
322 const Tri& t1 = triangles_[
static_cast<size_t>(entry.second[1])];
323 const int e0 = int(entry.first >> 32);
324 const int e1 =
static_cast<int>(
static_cast<uint32_t
>(entry.first));
328 if (
v != e0 &&
v != e1) {
335 if (
v != e0 &&
v != e1) {
340 if (k < 0 || l < 0)
continue;
346 foldPairs_.push_back(pair);
361 stretchCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
365 shearCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
369 bendCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
381 cols_ =
model.gridCols();
382 rows_ =
model.gridRows();
383 spacing_ =
model.gridSpacing();
384 if (!
model.particles().empty()) {
385 originX_ =
model.particles().front().x;
386 originY_ =
model.particles().front().y;
387 originZ_ =
model.particles().front().z;
390 particles_.reserve(
model.particles().size());
393 particle.x = particle.px =
source.x;
394 particle.y = particle.py =
source.y;
395 particle.z = particle.pz =
source.z;
396 particle.inverseMass =
source.inverseMass;
397 particle.pinned =
source.inverseMass == 0.f;
398 particles_.push_back(particle);
400 restParticles_ = particles_;
403 links_.reserve(
model.distanceConstraints().size());
404 for (
const ClothModelDistanceConstraint&
source :
model.distanceConstraints())
408 triangles_.reserve(
model.triangles().size());
413 foldPairs_.reserve(
model.foldConstraints().size());
414 for (
const ClothModelFoldConstraint&
source :
model.foldConstraints())
417 tethers_.reserve(
model.tetherConstraints().size());
418 for (
const ClothModelTetherConstraint&
source :
model.tetherConstraints())
420 restVolume_ =
model.restVolume();
437 airDensity_ = std::max(0.f, airDensity);
438 dragCoefficient_ = std::max(0.f, dragCoefficient);
439 liftCoefficient_ = std::max(0.f, liftCoefficient);
455 if (
w <= 0.f ||
h <= 0.f ||
d <= 0.f) {
471 collisionFriction_ = std::isfinite(
friction) ? std::clamp(
friction, 0.f, 1.f) : 0.f;
476 collisionCategoryBits_ = categoryBits;
477 collisionMaskBits_ = maskBits;
481 if (!validIndex(
index))
throw Exception(
"Cloth3D.pin: index out of range");
482 Particle& particle = particles_[
static_cast<size_t>(
index)];
483 particle.pinned =
true;
484 particle.inverseMass = 0.f;
488 if (!validIndex(
index))
throw Exception(
"Cloth3D.unpin: index out of range");
489 Particle& particle = particles_[
static_cast<size_t>(
index)];
490 particle.pinned =
false;
491 particle.inverseMass = 1.f;
495 for (
int c = 0;
c < cols_; ++
c)
pin(
c);
499 if (!validIndex(
index))
return false;
500 return particles_[
static_cast<size_t>(
index)].
pinned;
504 if (!validIndex(
index))
throw Exception(
"Cloth3D.setParticleInverseMass: index out of range");
505 Particle& particle = particles_[
static_cast<size_t>(
index)];
507 particle.pinned = particle.inverseMass == 0.f;
518 const Particle&
p = particles_[
static_cast<size_t>(i)];
519 if (
p.pinned)
continue;
520 const float dx =
p.x -
x;
521 const float dy =
p.y -
y;
522 const float dz =
p.z -
z;
537 if (!validIndex(grabIndex_))
return;
538 Particle&
p = particles_[
static_cast<size_t>(grabIndex_)];
559 interactRadius_ = std::max(0.f,
radius);
573 if (!validIndex(
index))
return 0.f;
574 return particles_[
static_cast<size_t>(
index)].
x;
578 if (!validIndex(
index))
return 0.f;
579 return particles_[
static_cast<size_t>(
index)].
y;
583 if (!validIndex(
index))
return 0.f;
584 return particles_[
static_cast<size_t>(
index)].
z;
588 if (!validIndex(
index))
throw Exception(
"Cloth3D.setParticlePosition: index out of range");
589 Particle&
p = particles_[
static_cast<size_t>(
index)];
595int64_t Cloth3D::cellKey(
int cx,
int cy,
int cz)
const {
597 return int64_t(uint32_t(
cx) & 0x1fffffu) | (int64_t(uint32_t(
cy) & 0x1fffffu) << 21) |
598 (int64_t(uint32_t(cz) & 0x1fffffu) << 42);
601void Cloth3D::rebuildHash() {
603 const float cell = std::max(1e-3f, particleSize_ * 2.f);
604 const float inv = 1.f /
cell;
606 const Particle&
p = particles_[
static_cast<size_t>(i)];
607 const int cx = int(std::floor(
p.x * inv));
608 const int cy = int(std::floor(
p.y * inv));
609 const int cz = int(std::floor(
p.z * inv));
610 hash_[cellKey(
cx,
cy, cz)].push_back(i);
614void Cloth3D::integrate(
float dt) {
615 if (
dt <= 0.f)
return;
616 const float ax = gravityX_ + forceX_;
617 const float ay = gravityY_ + forceY_;
618 const float az = gravityZ_ + forceZ_;
619 const float damp = 1.f - damping_;
620 const bool hasInteract = interactRadius_ > 0.f && interactStrength_ != 0.f;
622 std::vector<float> aerodynamicAcceleration;
623 if (airDensity_ > 0.f && (dragCoefficient_ > 0.f || liftCoefficient_ > 0.f)) {
624 aerodynamicAcceleration.assign(particles_.size() * 3, 0.f);
625 accumulateAerodynamicAcceleration(
dt, aerodynamicAcceleration);
628 for (
size_t particleIndex = 0; particleIndex < particles_.size(); ++particleIndex) {
629 Particle&
p = particles_[particleIndex];
636 const float vx = (
p.x -
p.px) * damp;
637 const float vy = (
p.y -
p.py) * damp;
638 const float vz = (
p.z -
p.pz) * damp;
642 const float aeroX = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3];
643 const float aeroY = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3 + 1];
644 const float aeroZ = aerodynamicAcceleration.empty() ? 0.f : aerodynamicAcceleration[particleIndex * 3 + 2];
645 p.x +=
vx + (ax + aeroX) *
dt *
dt;
646 p.y +=
vy + (ay + aeroY) *
dt *
dt;
647 p.z +=
vz + (az + aeroZ) *
dt *
dt;
649 const float dx = interactX_ -
p.x;
650 const float dy = interactY_ -
p.y;
651 const float dz = interactZ_ -
p.z;
653 const float R2 = interactRadius_ * interactRadius_;
654 if (r2 < R2 && r2 > 1e-6f) {
655 const float r = std::sqrt(r2);
656 const float w = 1.f -
r / interactRadius_;
657 const float a = interactStrength_ *
w *
dt *
dt;
663 constexpr float maxSpeed = 9.f;
664 const float maxDisp = maxSpeed *
dt;
665 const float dvx =
p.x -
p.px;
666 const float dvy =
p.y -
p.py;
667 const float dvz =
p.z -
p.pz;
668 const float v2 = dvx * dvx + dvy * dvy + dvz * dvz;
669 if (v2 > maxDisp * maxDisp) {
670 const float s = maxDisp / std::sqrt(v2);
671 p.px =
p.x - dvx *
s;
672 p.py =
p.y - dvy *
s;
673 p.pz =
p.z - dvz *
s;
678void Cloth3D::accumulateAerodynamicAcceleration(
float dt, std::vector<float>& accelerations)
const {
679 const float invDt =
dt > 1e-6f ? 1.f /
dt : 0.f;
680 const float invMass = 1.f / particleMass_;
681 for (
const Tri& tri : triangles_) {
682 const Particle&
a = particles_[
static_cast<size_t>(tri.v[0])];
683 const Particle&
b = particles_[
static_cast<size_t>(tri.v[1])];
684 const Particle&
c = particles_[
static_cast<size_t>(tri.v[2])];
686 const V3
ab{
b.x -
a.x,
b.y -
a.y,
b.z -
a.z};
687 const V3
ac{
c.x -
a.x,
c.y -
a.y,
c.z -
a.z};
689 const float twiceArea = vlen(areaNormal);
690 if (twiceArea < 1e-8f)
continue;
691 V3
normal =
mul(1.f / twiceArea, areaNormal);
693 const V3 clothVelocity{((
a.x -
a.px) + (
b.x -
b.px) + (
c.x -
c.px)) * (invDt / 3.f),
694 ((
a.y -
a.py) + (
b.y -
b.py) + (
c.y -
c.py)) * (invDt / 3.f),
695 ((
a.z -
a.pz) + (
b.z -
b.pz) + (
c.z -
c.pz)) * (invDt / 3.f)};
696 const V3 relativeWind{windVelocityX_ - clothVelocity.x, windVelocityY_ - clothVelocity.y,
697 windVelocityZ_ - clothVelocity.z};
698 const float speed = vlen(relativeWind);
699 if (speed < 1e-5f)
continue;
702 if (incidence < 0.f) {
704 incidence = -incidence;
706 if (incidence < 1e-5f)
continue;
708 const float dynamicPressureArea = 0.5f * airDensity_ * speed * speed * (twiceArea * 0.5f);
709 const V3 drag =
mul(dragCoefficient_ * incidence * dynamicPressureArea,
windDirection);
711 const float liftLength = vlen(liftDirection);
712 if (liftLength > 1e-6f)
713 liftDirection =
mul(1.f / liftLength, liftDirection);
715 liftDirection = V3{0.f, 0.f, 0.f};
716 const V3 lift =
mul(liftCoefficient_ * incidence * dynamicPressureArea, liftDirection);
719 for (
int vertex : tri.
v) {
720 if (particles_[
static_cast<size_t>(vertex)].
pinned)
continue;
721 accelerations[
static_cast<size_t>(vertex) * 3] +=
acceleration.x;
722 accelerations[
static_cast<size_t>(vertex) * 3 + 1] +=
acceleration.y;
723 accelerations[
static_cast<size_t>(vertex) * 3 + 2] +=
acceleration.z;
728void Cloth3D::solveConstraints(
float dt) {
729 for (Link&
link : links_)
link.lambda = 0.f;
730 for (Tether& tether : tethers_) tether.lambda = 0.f;
731 for (SkinConstraint& skin : skinConstraints_) skin.lambda = 0.f;
732 for (Attachment& attachment : attachments_) attachment.lambda = 0.f;
734 const float invDtSquared =
dt > 1e-8f ? 1.f / (
dt *
dt) : 0.f;
735 for (
int iter = 0; iter < iterations_; ++iter) {
736 for (Link&
link : links_) {
737 Particle&
a = particles_[
static_cast<size_t>(
link.a)];
738 Particle&
b = particles_[
static_cast<size_t>(
link.b)];
739 if (
a.pinned &&
b.pinned)
continue;
740 float dx =
b.x -
a.x;
741 float dy =
b.y -
a.y;
742 float dz =
b.z -
a.z;
743 const float dist = std::sqrt(
dx *
dx +
dy *
dy +
dz *
dz);
744 if (dist < 1e-5f)
continue;
745 float compliance = stretchCompliance_;
747 compliance = shearCompliance_;
749 compliance = bendCompliance_;
750 if (compliance > 0.f) {
751 const float weightA =
a.pinned ? 0.f :
a.inverseMass;
752 const float weightB =
b.pinned ? 0.f :
b.inverseMass;
753 const float alpha = compliance * invDtSquared;
754 const float deltaLambda = (-(dist -
link.rest) - alpha *
link.lambda) / (weightA + weightB + alpha);
755 link.lambda += deltaLambda;
756 const float nx =
dx / dist;
757 const float ny =
dy / dist;
758 const float nz =
dz / dist;
759 a.x -= weightA *
nx * deltaLambda;
760 a.y -= weightA *
ny * deltaLambda;
761 a.z -= weightA *
nz * deltaLambda;
762 b.x += weightB *
nx * deltaLambda;
763 b.y += weightB *
ny * deltaLambda;
764 b.z += weightB *
nz * deltaLambda;
767 const float diff = (dist -
link.rest) / dist * stiffness_;
772 }
else if (
b.pinned) {
777 const float half = diff * 0.5f;
786 solveTetherConstraints(
dt);
787 solveVolumeConstraint(
dt);
788 solveSkinConstraints(
dt);
789 solveAttachments(
dt);
790 if (validIndex(grabIndex_)) {
791 Particle&
g = particles_[
static_cast<size_t>(grabIndex_)];
802void Cloth3D::solveFoldConstraint() {
803 if (foldStiffness_ <= 0.f || maxFoldAngle_ >= kPi || foldPairs_.empty())
return;
809 const float thetaMin = kPi - maxFoldAngle_;
810 const float s = foldStiffness_;
811 for (
const FoldPair& pair : foldPairs_) {
812 Particle& pa = particles_[
static_cast<size_t>(pair.a)];
813 Particle& pb = particles_[
static_cast<size_t>(pair.b)];
814 Particle& pk = particles_[
static_cast<size_t>(pair.k)];
815 Particle& pl = particles_[
static_cast<size_t>(pair.l)];
816 if (pa.pinned && pb.pinned && pk.pinned && pl.pinned)
continue;
818 const V3 paV{pa.x, pa.y, pa.z};
819 const V3 pbV{pb.x, pb.y, pb.z};
820 V3 pkV{pk.x, pk.y, pk.z};
821 V3 plV{pl.x, pl.y, pl.z};
823 const V3
u = vnorm(
sub(pbV, paV));
824 const V3 vk =
sub(pkV, paV);
825 const V3 vl =
sub(plV, paV);
828 const float b1 = vlen(h1);
829 const float b2 = vlen(h2);
830 if (b1 < 1e-6f || b2 < 1e-6f)
continue;
831 const V3 m1 =
mul(1.f / b1, h1);
832 const V3 m2 =
mul(1.f / b2, h2);
833 const float theta = std::acos(std::clamp(
dot(m1, m2), -1.f, 1.f));
834 if (theta >= thetaMin)
continue;
839 const float phi = signedAngle(m1, m2,
u);
840 const float sign =
phi >= 0.f ? 1.f : -1.f;
841 const float delta = thetaMin - theta;
842 const float a1 = -sign * delta * 0.5f *
s;
843 const float a2 = sign * delta * 0.5f *
s;
845 pkV =
add(paV, rotateAround(vk,
u, a1 *
s));
851 plV =
add(paV, rotateAround(vl,
u, a2 *
s));
859void Cloth3D::solveSelfCollision() {
861 const float minDist = particleSize_ * 2.f;
862 if (minDist <= 0.f)
return;
864 const float cell = std::max(1e-3f, minDist);
865 const float inv = 1.f /
cell;
867 Particle& pi = particles_[
static_cast<size_t>(i)];
868 const int cx = int(std::floor(pi.x * inv));
869 const int cy = int(std::floor(pi.y * inv));
870 const int cz = int(std::floor(pi.z * inv));
871 for (
int oz = -1; oz <= 1; ++oz) {
872 for (
int oy = -1;
oy <= 1; ++
oy) {
873 for (
int ox = -1;
ox <= 1; ++
ox) {
874 auto it = hash_.find(cellKey(
cx +
ox,
cy +
oy, cz + oz));
875 if (it == hash_.end())
continue;
876 for (
int j : it->
second) {
877 if (j <= i)
continue;
878 if (areLinked(i, j))
continue;
879 Particle& pj = particles_[
static_cast<size_t>(j)];
880 float dx = pj.x - pi.x;
881 float dy = pj.y - pi.y;
882 float dz = pj.z - pi.z;
884 if (d2 >= minDist * minDist || d2 < 1e-8f)
continue;
885 if (pi.pinned && pj.pinned)
continue;
886 const float d = std::sqrt(d2);
887 const float corr = std::min(0.5f, (minDist -
d) /
d);
890 if (pi.pinned && !pj.pinned) {
893 }
else if (pj.pinned && !pi.pinned) {
897 pi.x -=
dx * corr * wa;
898 pi.y -=
dy * corr * wa;
899 pi.z -=
dz * corr * wa;
900 pj.x +=
dx * corr * wb;
901 pj.y +=
dy * corr * wb;
902 pj.z +=
dz * corr * wb;
910void Cloth3D::solveSelfCollisionTriangles() {
911 if (!selfCollision_ || triangles_.size() < 2)
return;
912 const float thickness = std::max(1e-3f, particleSize_ * 2.f);
913 const int triCount =
static_cast<int>(triangles_.size());
915 std::vector<V3>
pos(particles_.size());
916 for (
size_t i = 0; i < particles_.size(); ++i) {
917 pos[i] = {particles_[i].x, particles_[i].y, particles_[i].z};
921 const float inv = 1.f /
cell;
922 std::unordered_map<int64_t, std::vector<int>> triHash;
923 auto triCellKey = [](
int cx,
int cy,
int cz) -> int64_t {
924 return int64_t(uint32_t(
cx) & 0x1fffffu) | (int64_t(uint32_t(
cy) & 0x1fffffu) << 21) |
925 (int64_t(uint32_t(cz) & 0x1fffffu) << 42);
927 const auto insertTri = [&](
int ti) {
928 const Tri& tri = triangles_[
static_cast<size_t>(ti)];
929 V3 mn =
pos[
static_cast<size_t>(tri.v[0])];
931 for (
int k = 1; k < 3; ++k) {
932 const V3&
p =
pos[
static_cast<size_t>(tri.v[k])];
933 mn.x = std::min(mn.x,
p.x);
934 mn.y = std::min(mn.y,
p.y);
935 mn.z = std::min(mn.z,
p.z);
936 mx.x = std::max(mx.x,
p.x);
937 mx.y = std::max(mx.y,
p.y);
938 mx.z = std::max(mx.z,
p.z);
943 const int x0 = int(std::floor(mn.x * inv));
944 const int y0 = int(std::floor(mn.y * inv));
945 const int z0 = int(std::floor(mn.z * inv));
946 const int x1 = int(std::floor(mx.x * inv));
947 const int y1 = int(std::floor(mx.y * inv));
948 const int z1 = int(std::floor(mx.z * inv));
949 for (
int cz = z0; cz <= z1; ++cz)
950 for (
int cy = y0;
cy <= y1; ++
cy)
951 for (
int cx = x0;
cx <= x1; ++
cx) triHash[triCellKey(
cx,
cy, cz)].push_back(ti);
953 for (
int ti = 0; ti < triCount; ++ti) insertTri(ti);
955 const auto sharesVertex = [&](
const Tri&
a,
const Tri&
b) {
956 for (
int i = 0; i < 3; ++i)
957 for (
int j = 0; j < 3; ++j)
958 if (
a.v[i] ==
b.v[j])
return true;
962 std::unordered_set<int64_t> processed;
963 std::vector<int>
cells;
967 for (
int i = 0; i < triCount; ++i) {
968 const Tri& triI = triangles_[
static_cast<size_t>(i)];
969 const V3& pa0 =
pos[
static_cast<size_t>(triI.v[0])];
972 for (
int k = 1; k < 3; ++k) {
973 const V3&
p =
pos[
static_cast<size_t>(triI.v[k])];
974 mn.x = std::min(mn.x,
p.x);
975 mn.y = std::min(mn.y,
p.y);
976 mn.z = std::min(mn.z,
p.z);
977 mx.x = std::max(mx.x,
p.x);
978 mx.y = std::max(mx.y,
p.y);
979 mx.z = std::max(mx.z,
p.z);
984 const int x0 = int(std::floor(mn.x * inv));
985 const int y0 = int(std::floor(mn.y * inv));
986 const int z0 = int(std::floor(mn.z * inv));
987 const int x1 = int(std::floor(mx.x * inv));
988 const int y1 = int(std::floor(mx.y * inv));
989 const int z1 = int(std::floor(mx.z * inv));
991 for (
int cz = z0; cz <= z1; ++cz)
992 for (
int cy = y0;
cy <= y1; ++
cy)
993 for (
int cx = x0;
cx <= x1; ++
cx) {
994 auto it = triHash.find(triCellKey(
cx,
cy, cz));
995 if (it != triHash.end())
cells.insert(
cells.end(), it->second.begin(), it->second.end());
997 for (
int j :
cells) {
998 if (j <= i)
continue;
1000 if (!processed.insert(
key).second)
continue;
1001 const Tri& triJ = triangles_[
static_cast<size_t>(j)];
1002 if (sharesVertex(triI, triJ))
continue;
1004 const V3
A[3] = {
pos[
static_cast<size_t>(triI.v[0])],
pos[
static_cast<size_t>(triI.v[1])],
1005 pos[
static_cast<size_t>(triI.v[2])]};
1006 const V3
B[3] = {
pos[
static_cast<size_t>(triJ.v[0])],
pos[
static_cast<size_t>(triJ.v[1])],
1007 pos[
static_cast<size_t>(triJ.v[2])]};
1012 const float d = triangleDistance(A, B, featA, featB, countA, countB, cpA, cpB);
1015 V3
n = vnorm(
sub(cpB, cpA));
1016 if (vlen(
sub(cpB, cpA)) < 1e-6f) {
1019 const float corr = (
thickness -
d) * stiffness_;
1020 if (corr <= 0.f)
continue;
1022 const auto freeCount = [&](
const int* feat,
int count) {
1024 for (
int k = 0; k <
count; ++k)
1025 if (!particles_[
static_cast<size_t>(feat[k])].pinned) ++free;
1028 const int freeA = freeCount(featA, countA);
1029 const int freeB = freeCount(featB, countB);
1030 if (freeA == 0 && freeB == 0)
continue;
1031 const float wA = freeA > 0 ? (freeB > 0 ? 0.5f : 1.f) : 0.f;
1032 const float wB = freeB > 0 ? (freeA > 0 ? 0.5f : 1.f) : 0.f;
1033 const auto pushFeature = [&](
const int* feat,
int count,
const V3&
dir) {
1034 for (
int k = 0; k <
count; ++k) {
1035 Particle& pv = particles_[
static_cast<size_t>(feat[k])];
1036 if (pv.pinned)
continue;
1043 const V3
dir =
mul(-corr * wA /
float(freeA),
n);
1044 pushFeature(featA, countA,
dir);
1047 const V3
dir =
mul(corr * wB /
float(freeB),
n);
1048 pushFeature(featB, countB,
dir);
1055 for (
int i = 0; i < triCount; ++i) {
1056 const Tri& triI = triangles_[
static_cast<size_t>(i)];
1057 const V3
A[3] = {
pos[
static_cast<size_t>(triI.v[0])],
pos[
static_cast<size_t>(triI.v[1])],
1058 pos[
static_cast<size_t>(triI.v[2])]};
1059 const V3 nI = vnorm(
cross(
sub(A[1], A[0]),
sub(A[2], A[0])));
1060 for (
int j = i + 1; j < triCount; ++j) {
1061 const Tri& triJ = triangles_[
static_cast<size_t>(j)];
1062 if (sharesVertex(triI, triJ))
continue;
1063 const V3
B[3] = {
pos[
static_cast<size_t>(triJ.v[0])],
pos[
static_cast<size_t>(triJ.v[1])],
1064 pos[
static_cast<size_t>(triJ.v[2])]};
1065 const V3 nJ = vnorm(
cross(
sub(B[1], B[0]),
sub(B[2], B[0])));
1067 for (
int k = 0; k < 3; ++k) {
1068 Particle& pv = particles_[
static_cast<size_t>(triI.v[k])];
1069 if (pv.pinned)
continue;
1071 const float d =
dot(
sub(va, B[0]), nJ);
1074 if (!pointInTriangle(
q, B[0], B[1], B[2]))
continue;
1075 const float push = (
thickness - std::fabs(
d)) * stiffness_ * 0.5f;
1076 const V3
dir =
mul(
d >= 0.f ? push : -push, nJ);
1082 for (
int k = 0; k < 3; ++k) {
1083 Particle& pv = particles_[
static_cast<size_t>(triJ.v[k])];
1084 if (pv.pinned)
continue;
1086 const float d =
dot(
sub(vb, A[0]), nI);
1089 if (!pointInTriangle(
q, A[0], A[1], A[2]))
continue;
1090 const float push = (
thickness - std::fabs(
d)) * stiffness_ * 0.5f;
1091 const V3
dir =
mul(
d >= 0.f ? push : -push, nI);
1100void Cloth3D::collideWorld(
float dt) {
1101 if (!world_ || !world_->
isValid() || particleSize_ <= 0.f)
return;
1102 const float invDt =
dt > 1e-6f ? 1.f /
dt : 0.f;
1105 Particle&
p = particles_[
static_cast<size_t>(i)];
1106 if (
p.pinned)
continue;
1111 const float vpx = (
p.x -
p.px) * invDt;
1112 const float vpy = (
p.y -
p.py) * invDt;
1113 const float vpz = (
p.z -
p.pz) * invDt;
1121 float bodyMass = 0.f;
1124 vbx =
contact.body->getLinearVelocityX();
1125 vby =
contact.body->getLinearVelocityY();
1126 vbz =
contact.body->getLinearVelocityZ();
1127 bodyMass =
contact.body->getMass();
1132 const float friction = std::clamp(std::sqrt(collisionFriction_ * std::max(0.f,
contact.friction)), 0.f, 1.f);
1133 const float relativeX = vpx - vbx;
1134 const float relativeY = vpy - vby;
1135 const float relativeZ = vpz - vbz;
1137 const float tangentY = relativeY - vn *
contact.ny;
1141 const float nextVy = vby + tangentY * (1.f -
friction) +
contact.ny * nextNormal;
1143 p.px =
p.x - nextVx *
dt;
1144 p.py =
p.y - nextVy *
dt;
1145 p.pz =
p.z - nextVz *
dt;
1146 const float m = particleMass_;
1147 const float reduced = bodyMass > 0.f ? (
m * bodyMass) / (
m + bodyMass) :
m;
1149 const float maxKick = 9.f;
1150 j = std::min(j, maxKick *
m);
1151 const float kick = (j /
m) *
dt;
1155 if (
dynamic && bodyMass > 0.f) {
1162void Cloth3D::collideBounds() {
1163 if (!hasBounds_)
return;
1164 const float minX = boundX_;
1165 const float minY = boundY_;
1166 const float minZ = boundZ_;
1167 const float maxX = boundX_ + boundW_;
1168 const float maxY = boundY_ + boundH_;
1169 const float maxZ = boundZ_ + boundD_;
1170 const float bounce = collisionRestitution_;
1172 for (Particle&
p : particles_) {
1173 if (
p.pinned)
continue;
1175 const float vx =
p.x -
p.px;
1178 }
else if (
p.x > maxX) {
1179 const float vx =
p.x -
p.px;
1184 const float vy =
p.y -
p.py;
1187 }
else if (
p.y > maxY) {
1188 const float vy =
p.y -
p.py;
1193 const float vz =
p.z -
p.pz;
1196 }
else if (
p.z > maxZ) {
1197 const float vz =
p.z -
p.pz;
1205 if (destroyed_)
return;
1206 if (
dt < 0.f)
dt = 0.f;
1207 if (
dt > 0.05f)
dt = 0.05f;
1209 updateSubsteps(
dt, 2);
1212void Cloth3D::updateSubsteps(
float dt,
int substeps) {
1213 if (destroyed_ || substeps < 1)
return;
1215 const float h =
dt / float(substeps);
1216 for (
int s = 0;
s < substeps; ++
s) {
1218 applyAutomaticTearing();
1219 solveConstraints(
h);
1220 solveFoldConstraint();
1221 solveSelfCollision();
1222 solveSelfCollisionTriangles();
1225 if (grabIndex_ >= 0) {
1226 Particle&
p = particles_[
static_cast<size_t>(grabIndex_)];
1235 interactStrength_ = 0.f;
1242 auto valid = detail::validateSimulationStep(stepValue,
settings, observation_);
1244 auto next = detail::advanceSimulationObservation(observation_, stepValue);
1248 }
catch (
const std::exception&
error) {
1255 observation_ = std::move(next).takeValue();
1260 auto valid = detail::validateSimulationObservation(
observation,
"physics.cloth3d.restoreObservation");
1264 "Cannot restore a destroyed cloth",
1265 "physics.cloth3d.restoreObservation"));
1271 if (!gfx || destroyed_ ||
getParticleCount() < 3 || triangles_.empty())
return;
1277 const int indexCount =
static_cast<int>(triangles_.size()) * 6;
1280 std::vector<float> nrm(
static_cast<size_t>(
vertexCount) * 3, 0.f);
1281 std::vector<float>
uv(
static_cast<size_t>(
vertexCount) * 2);
1283 const size_t i =
static_cast<size_t>(
index);
1284 const Particle&
p = particles_[i];
1285 const float u = cols_ > 1 ? float(
index % cols_) / float(cols_ - 1) :
p.x;
1286 const float v = rows_ > 1 ? float(
index / cols_) / float(rows_ - 1) :
p.z;
1287 for (
int side = 0; side < 2; ++side) {
1288 const size_t vi = i +
static_cast<size_t>(side) * gridVertices;
1289 pos[vi * 3 + 0] =
p.x;
1290 pos[vi * 3 + 1] =
p.y;
1291 pos[vi * 3 + 2] =
p.z;
1298 for (
const Tri& tri : triangles_) {
1299 const float* pa = &
pos[
static_cast<size_t>(tri.v[0]) * 3];
1300 const float* pb = &
pos[
static_cast<size_t>(tri.v[1]) * 3];
1301 const float* pc = &
pos[
static_cast<size_t>(tri.v[2]) * 3];
1302 float e1x = pb[0] - pa[0], e1y = pb[1] - pa[1], e1z = pb[2] - pa[2];
1303 float e2x = pc[0] - pa[0], e2y = pc[1] - pa[1], e2z = pc[2] - pa[2];
1304 float nx = e1y * e2z - e1z * e2y;
1305 float ny = e1z * e2x - e1x * e2z;
1306 float nz = e1x * e2y - e1y * e2x;
1307 const float len = std::sqrt(
nx *
nx +
ny *
ny +
nz *
nz);
1317 for (
int v : tri.v) {
1318 nrm[
static_cast<size_t>(
v) * 3 + 0] +=
nx;
1319 nrm[
static_cast<size_t>(
v) * 3 + 1] +=
ny;
1320 nrm[
static_cast<size_t>(
v) * 3 + 2] +=
nz;
1321 nrm[(
static_cast<size_t>(
v) + gridVertices) * 3 + 0] -=
nx;
1322 nrm[(
static_cast<size_t>(
v) + gridVertices) * 3 + 1] -=
ny;
1323 nrm[(
static_cast<size_t>(
v) + gridVertices) * 3 + 2] -=
nz;
1326 for (
int i = 0; i < gridVertices; ++i) {
1327 const float nx = nrm[
static_cast<size_t>(i) * 3 + 0];
1328 const float ny = nrm[
static_cast<size_t>(i) * 3 + 1];
1329 const float nz = nrm[
static_cast<size_t>(i) * 3 + 2];
1330 const float len = std::sqrt(
nx *
nx +
ny *
ny +
nz *
nz);
1331 for (
int side = 0; side < 2; ++side) {
1332 const size_t vi =
static_cast<size_t>(i) +
static_cast<size_t>(side) * gridVertices;
1333 const float sign = side == 0 ? 1.f : -1.f;
1335 nrm[vi * 3 + 0] = sign *
nx / len;
1336 nrm[vi * 3 + 1] = sign *
ny / len;
1337 nrm[vi * 3 + 2] = sign *
nz / len;
1339 nrm[vi * 3 + 1] = sign;
1347 for (
const Tri&
triangle : triangles_) {
1348 for (
int corner = 0; corner < 3; ++corner) {
1349 indices[
static_cast<size_t>(
out + corner)] =
static_cast<uint32_t
>(
triangle.v[corner]);
1350 indices[
static_cast<size_t>(
out + 3 + corner)] =
1351 static_cast<uint32_t
>(
triangle.v[2 - corner] + gridVertices);
1363 gfx->
drawMesh(mesh_, glm::mat4(1.f),
nullptr,
Color(colorR_, colorG_, colorB_, colorA_));
1369 if (count < 1 || count > 32 || !std::isfinite(
gap) ||
gap <= 0.f || !std::isfinite(
x) || !std::isfinite(
y) ||
1370 !std::isfinite(
z) || !std::isfinite(
spacing) || !std::isfinite(
y +
float(
count - 1) *
gap))
1371 throw Exception(
"LayeredCloth3D: invalid count, gap or coordinates");
1372 for (
int i = 0; i <
count; ++i) {
1374 cloth->setParticleSize(std::min(
spacing * 0.2f,
gap * 0.4f));
1375 cloth->setStretchCompliance(1e-7f);
1376 cloth->setBendCompliance(1e-4f *
float(i + 1));
1377 cloth->setParticleMass(0.08f + 0.04f *
float(i));
1378 cloth->setAerodynamics(1.225f, 0.6f, 0.05f);
1379 const float t =
count > 1 ? float(i) / float(
count - 1) : 0.f;
1380 cloth->setColor(0.2f +
t * 0.7f, 0.65f -
t * 0.3f, 0.9f -
t * 0.65f, 1.f);
1381 layers_.push_back(std::move(cloth));
1386 if (models.empty())
throw Exception(
"LayeredCloth3D: models cannot be empty");
1387 for (
const auto&
model : models) layers_.push_back(std::make_unique<Cloth3D>(
model));
1392 return *layers_[
static_cast<size_t>(
index)];
1396 if (substeps < 1 || substeps > 32 || passes < 1 || passes > 16)
1397 throw Exception(
"LayeredCloth3D: invalid solver budget");
1398 substeps_ = substeps;
1405 if (!std::isfinite(
x) || !std::isfinite(
y) || !std::isfinite(
z))
throw Exception(
"LayeredCloth3D: invalid wind");
1406 for (
auto& cloth : layers_) cloth->setWindVelocity(
x,
y,
z);
1409 for (
auto& cloth : layers_) cloth->reset();
1413 for (
auto& cloth : layers_) cloth->draw(gfx);
1416 if (!std::isfinite(
dt) || dt < 0.f || dt > 0.05f)
1417 throw Exception(
"LayeredCloth3D: dt must be finite and in [0,0.05]");
1418 for (
const auto& cloth : layers_)
1419 if (cloth->destroyed_)
throw Exception(
"LayeredCloth3D: layer was destroyed");
1421 if (
dt == 0.f)
return;
1422 const float h =
dt / float(substeps_);
1424 for (
auto&
c : layers_) {
1426 c->applyAutomaticTearing();
1428 for (
int pass = 0; pass < passes_; ++pass) {
1429 for (
auto&
c : layers_) {
1430 c->solveConstraints(
h);
1431 c->solveFoldConstraint();
1432 c->solveSelfCollision();
1433 c->solveSelfCollisionTriangles();
1437 if (interCollision_)
1438 for (
size_t a = 0;
a < layers_.size(); ++
a)
1439 for (
size_t b =
a + 1;
b < layers_.size(); ++
b) solveContacts(*layers_[
a], *layers_[
b]);
1441 for (
auto&
c : layers_)
1442 if (
c->grabIndex_ >= 0) {
1443 auto&
p =
c->particles_[
static_cast<size_t>(
c->grabIndex_)];
1449 for (
auto&
c : layers_) {
1450 c->forceX_ =
c->forceY_ =
c->forceZ_ = 0.f;
1451 c->interactStrength_ = 0.f;
1456 if (!(
a.collisionCategoryBits_ &
b.collisionMaskBits_) || !(
b.collisionCategoryBits_ &
a.collisionMaskBits_))
1458 const float thickness =
a.particleSize_ +
b.particleSize_;
1464 auto bounds = [](
const Cloth3D& cloth) {
1465 std::vector<Bounds>
result;
1466 result.reserve(cloth.triangles_.size());
1467 for (
size_t i = 0; i < cloth.triangles_.size(); ++i) {
1468 Bounds box{{INFINITY, INFINITY, INFINITY}, {-INFINITY, -INFINITY, -INFINITY}, i};
1469 for (
int index : cloth.triangles_[i].
v) {
1470 const auto&
p = cloth.particles_[
static_cast<size_t>(
index)];
1471 const float xyz[3] = {
p.x,
p.y,
p.z};
1472 for (
int k = 0; k < 3; ++k) {
1473 box.lo[k] = std::min(box.lo[k], xyz[k]);
1474 box.hi[k] = std::max(box.hi[k], xyz[k]);
1480 [](
const Bounds&
x,
const Bounds&
y) { return x.lo[0] < y.lo[0]; });
1486 for (
const auto& ba : boxesA)
1487 for (const auto& bb : boxesB) {
1488 if (bb.lo[0] > ba.hi[0] +
thickness)
break;
1492 const auto&
ta =
a.triangles_[ba.triangle];
1493 const auto&
tb =
b.triangles_[bb.triangle];
1495 for (
int i = 0; i < 3; ++i) {
1496 const auto&
p =
a.particles_[
static_cast<size_t>(
ta.v[i])];
1497 const auto&
q =
b.particles_[
static_cast<size_t>(
tb.v[i])];
1498 pa[i] = {
p.x,
p.y,
p.z};
1499 pb[i] = {
q.x,
q.y,
q.z};
1502 int fa[3], fb[3], na = 0, nb = 0;
1503 const float distance = triangleDistance(pa, pb, fa, fb, na, nb, ca, cb);
1506 auto weights = [](
const V3*
p,
const int* feature,
int count, V3 cp) {
1507 std::array<float, 3>
w{};
1509 w[
static_cast<size_t>(feature[0])] = 1.f;
1510 else if (
count == 2) {
1511 const V3
edge =
sub(
p[feature[1]],
p[feature[0]]);
1514 w[
static_cast<size_t>(feature[0])] = 1.f -
t;
1515 w[
static_cast<size_t>(feature[1])] =
t;
1519 const float det = uu * vv -
uv *
uv;
1520 if (det <= 1e-12f) {
1524 w[1] = std::clamp((vv *
dot(
q,
u) -
uv *
dot(
q,
v)) / det, 0.f, 1.f);
1525 w[2] = std::clamp((uu *
dot(
q,
v) -
uv *
dot(
q,
u)) / det, 0.f, 1.f -
w[1]);
1526 w[0] = 1.f -
w[1] -
w[2];
1530 const auto wa =
weights(pa, fa, na, ca), wb =
weights(pb, fb, nb, cb);
1531 V3 previousA{}, previousB{};
1532 float denominator = 0.f;
1533 for (
int i = 0; i < 3; ++i) {
1534 const auto&
p =
a.particles_[
static_cast<size_t>(
ta.v[i])];
1535 const auto&
q =
b.particles_[
static_cast<size_t>(
tb.v[i])];
1536 previousA =
add(previousA,
mul(wa[i], {
p.px,
p.py,
p.pz}));
1537 previousB =
add(previousB,
mul(wb[i], {
q.px,
q.py,
q.pz}));
1538 denominator += (
p.pinned ||
ta.v[i] ==
a.grabIndex_ ? 0.f :
p.inverseMass) * wa[i] * wa[i];
1539 denominator += (
q.pinned ||
tb.v[i] ==
b.grabIndex_ ? 0.f :
q.inverseMass) * wb[i] * wb[i];
1541 if (denominator <= 1e-12f)
continue;
1546 const float length = vlen(tangent);
1547 const float friction = std::sqrt(
a.collisionFriction_ *
b.collisionFriction_);
1548 const V3 frictionDelta =
1550 for (
int i = 0; i < 3; ++i) {
1552 auto&
p =
c.particles_[
static_cast<size_t>(
index)];
1553 if (
p.pinned ||
index ==
c.grabIndex_)
return;
1558 p.px += frictionDelta.x *
scale;
1559 p.py += frictionDelta.y *
scale;
1560 p.pz += frictionDelta.z *
scale;
ScriptForceVector acceleration
std::uint32_t vertexCount
std::array< double, 10 > q
std::vector< std::uint32_t > indices
HexDirection windDirection
std::array< float, 3 > scale
OceanWakeSettings settings
std::vector< BakedParticleSample > particles
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::map< Cell, int > best
std::vector< double > phi
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
virtual void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint)=0
Draw one mesh with model matrix. Requires begin3DFrame() (or an open swapchain pass).
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
GPU mesh handle (+ optional CPU morph targets).
Interactive 3D cloth — Verlet particles + distance constraints. Meter space, +Y up,...
void clearBounds()
Clears bounds.
float getWindVelocityZ() const
Return configured air velocity along Z in m/s.
void setGravity(float gx, float gy, float gz)
Sets the gravity.
void setCollisionMaterial(float friction, float restitution)
Configure cloth contact friction and restitution in [0,1].
void setParticleInverseMass(int index, float inverseMass)
Set per-particle inverse mass; zero makes the particle kinematic/pinned.
void interactAt(float x, float y, float z, float radius, float strength)
Pointer-field interaction like Fluid2D::interactAt (3D): positive strength attracts,...
Cloth3D(int cols, int rows, float spacing, float originX, float originY, float originZ)
Cloth 3 d.
void setShearCompliance(float compliance)
Set XPBD shear compliance in m/N; zero preserves legacy PBD.
float getDragCoefficient() const
Return the aerodynamic drag coefficient.
void moveGrab(float x, float y, float z)
Moves grab.
void setCollideWorld(World3D *world)
Attach a World3D so free particles collide with its non-sensor shapes in meter space....
void draw(graphics::Graphics *gfx)
Draw the cloth as a triangle mesh (requires an open 3D frame).
float getLiftCoefficient() const
Return the aerodynamic lift coefficient.
void setWindVelocity(float vx, float vy, float vz)
Set world-space air velocity used by the aerodynamic model (m/s).
void setStretchCompliance(float compliance)
Set XPBD stretch compliance in m/N; zero preserves legacy PBD.
void setSelfCollision(bool on)
Enable proximity-based self-collision between non-adjacent particles and triangles (default true)....
int grabAt(float x, float y, float z, float radius=0.3f)
Grab nearest free particle within radius (meters). Returns particle index, or -1 if none.
bool isPinned(int index) const
True when pinned.
void pinTopRow()
Pin top row.
void setColor(float r, float g, float b, float a=1.f)
Sets the color.
void setStiffness(float stiffness)
Constraint relaxation strength in [0,1] (default 0.85).
eve::Result< void > step(const eve::SimulationStep &step, const SimulationSettings &settings) override
Advances cloth with the shared ticked backend contract.
void setCollisionFilter(uint64_t categoryBits, uint64_t maskBits)
Configure symmetric category/mask filtering for World3D contacts.
float getParticleX(int index) const
void setBendCompliance(float compliance)
Set XPBD distance-bend compliance in m/N; zero preserves legacy PBD.
void unpin(int index)
Unpin.
eve::Result< void > restoreObservation(const SimulationObservation &observation) override
Restores tick/progress metadata after an owner-level restore.
void setBounds(float x, float y, float z, float w, float h, float d)
Axis-aligned box (origin + extents, meters); particles bounce inside.
void reset()
Restore the flat grid pose (top row pinned) and clear transient state.
void releaseGrab()
Release grab.
SimulationObservation observation() const noexcept override
Returns completed tick/time observables.
void setParticleSize(float size)
Particle radius in meters (default 0.1): self-collision separation, draw scale and rigid-body collisi...
void setIterations(int iterations)
Constraint solver iterations per substep (default 4).
void update(float dt)
Updates .
void setDamping(float damping)
Damping applied to Verlet velocity [0,1] (default 0.01).
float getWindVelocityY() const
Return configured air velocity along Y in m/s.
float getParticleInverseMass(int index) const
Return per-particle inverse mass, or zero for an invalid index.
void setParticleMass(float mass)
Implicit particle mass in kg (default 0.1). Used for mass-proportional momentum exchange when collidi...
void applyForce(float fx, float fy, float fz)
Applies force.
float getParticleZ(int index) const
Returns the particle z.
void setParticlePosition(int index, float x, float y, float z)
Sets the particle position.
void setMaxFoldAngle(float degrees)
Maximum fold angle between adjacent triangles in degrees Range is 0..180 degrees; default is 120....
int getParticleCount() const
Returns the particle count.
float getParticleY(int index) const
Returns the particle y.
float getAirDensity() const
Return aerodynamic fluid density in kg/m³.
float getWindVelocityX() const
Return configured air velocity along X in m/s.
void setFoldStiffness(float k)
Strength of the dihedral fold clamp [0,1] (default 0.5).
void setAerodynamics(float airDensity, float dragCoefficient, float liftCoefficient)
Configure two-sided triangle aerodynamics.
Reusable, validated cloth simulation asset.
static eve::Result< ClothModel > grid(int cols, int rows, float spacing, float originX, float originY, float originZ)
Bake a regular XZ cloth grid with its top row pinned.
void setInterCollision(bool enabled)
Enable or disable only contacts between different sheets.
~LayeredCloth3D()
Release owned runtime layers; render resources follow the graphics owner.
void reset()
Restore every layer's authored pose and clear contact statistics.
void update(float dt)
Advance all layers by finite dt in [0,0.05], without dropping time.
Cloth3D & layer(int index)
Borrow a layer for synchronous configuration; valid until owner destruction. Do not destroy or indepe...
int getLayerCount() const
Return the number of owned sheets.
void setSolver(int substeps, int passes)
Configure substeps [1,32] and coupling passes [1,16]; throws on invalid input.
void setWindVelocity(float x, float y, float z)
Set the air velocity of every sheet; throws on nonfinite input.
int getContactCount() const
Return projected contacts in the most recent update, including repeated passes.
LayeredCloth3D(int count, int cols, int rows, float spacing, float gap, float x, float y, float z)
Construct parallel XZ grids, separated along +Y.
void draw(graphics::Graphics *gfx)
Draw owned cloth surfaces in an open 3D frame.
bool getInterCollision() const
Return whether inter-layer contacts are enabled.
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
bool isValid() const
True while the underlying Box3D world is alive.
ClothProbeStatus pointProbeFiltered(float x, float y, float z, float radius, ClothContact3D *out, uint64_t categoryBits, uint64_t maskBits) const
Probe a cloth particle using symmetric category/mask filtering.
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
ForceVector add(ForceVector a, ForceVector b)
double dot(ForceVector a, ForceVector b)
JPH::uint64 pairKey(JPH::BodyID a, JPH::BodyID b)
Counts suppression references for one native pair; sequence numbers prevent reuse aliases.
JPH::SixDOFConstraint::EAxis A
Optional physics backend for vehicle mobility and body attach.
Vec3 mul(Vec3 a, float scale)
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
One deterministic fixed-step emitted by SimulationClock.
Duration delta
Fixed simulation duration for this step.
Observable backend progress shared by CPU and accelerator providers.
Validated solver policy for one simulation step.