载入中...
搜索中...
未找到
Cloth3DConstraints.cpp
浏览该文件的文档.
2
3#include "common/Exception.h"
4
5#include <algorithm>
6#include <cmath>
7#include <vector>
8
9namespace eve::physics {
10
11float Cloth3D::getStretchCompliance() const { return stretchCompliance_; }
12float Cloth3D::getShearCompliance() const { return shearCompliance_; }
13float Cloth3D::getBendCompliance() const { return bendCompliance_; }
14float Cloth3D::getTetherScale() const { return tetherScale_; }
15float Cloth3D::getTetherCompliance() const { return tetherCompliance_; }
16float Cloth3D::getPressure() const { return pressure_; }
17float Cloth3D::getVolumeCompliance() const { return volumeCompliance_; }
18float Cloth3D::getCollisionFriction() const { return collisionFriction_; }
19float Cloth3D::getCollisionRestitution() const { return collisionRestitution_; }
20uint64_t Cloth3D::getCollisionCategoryBits() const { return collisionCategoryBits_; }
21uint64_t Cloth3D::getCollisionMaskBits() const { return collisionMaskBits_; }
23 std::vector<std::uint32_t> indices;
24 indices.reserve(triangles_.size() * 3);
25 for (const auto& triangle : triangles_)
26 for (int vertex : triangle.v) indices.push_back(static_cast<std::uint32_t>(vertex));
27 return eve::Result<std::vector<std::uint32_t>>::success(std::move(indices));
28}
29int Cloth3D::getTriangleCount() const { return static_cast<int>(triangles_.size()); }
30int Cloth3D::getDistanceConstraintCount() const { return static_cast<int>(links_.size()); }
31int Cloth3D::getTetherConstraintCount() const { return static_cast<int>(tethers_.size()); }
32int Cloth3D::getSkinConstraintCount() const { return static_cast<int>(skinConstraints_.size()); }
33namespace {
34
35struct Vec3 {
36 float x = 0.f;
37 float y = 0.f;
38 float z = 0.f;
39};
40
41Vec3 cross(const Vec3& a, const Vec3& b) {
42 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};
43}
44
45float dot(const Vec3& a, const Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
46
47float length(const Vec3& value) { return std::sqrt(dot(value, value)); }
48
49} // namespace
50
51bool Cloth3D::supportsFeature(const std::string& feature) const {
52 return feature == "arbitrary_topology" || feature == "xpbd_material" || feature == "tether" ||
53 feature == "volume_pressure" || feature == "skin_backstop" || feature == "attachment" ||
54 feature == "world_collision" || feature == "collision_filter" || feature == "friction" ||
55 feature == "self_collision" || feature == "aerodynamics" || feature == "runtime_tearing";
56}
57
58void Cloth3D::setSkinConstraint(int index, float x, float y, float z, float nx, float ny, float nz, float radius,
59 float backstopDistance, float backstopRadius, float compliance) {
60 if (!validIndex(index)) throw Exception("Cloth3D.setSkinConstraint: index out of range");
61 const float normalLength = std::sqrt(nx * nx + ny * ny + nz * nz);
62 if (!std::isfinite(normalLength) || normalLength <= 1e-7f)
63 throw Exception("Cloth3D.setSkinConstraint: normal must be finite and non-zero");
64 auto found = std::find_if(skinConstraints_.begin(), skinConstraints_.end(),
65 [index](const SkinConstraint& item) { return item.particle == index; });
66 SkinConstraint value{index,
67 x,
68 y,
69 z,
70 nx / normalLength,
71 ny / normalLength,
72 nz / normalLength,
73 std::isfinite(radius) ? std::max(0.f, radius) : 0.f,
74 std::isfinite(backstopDistance) ? backstopDistance : -1.f,
75 std::isfinite(backstopRadius) ? std::max(0.f, backstopRadius) : 0.f,
76 std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f,
77 0.f};
78 if (found == skinConstraints_.end())
79 skinConstraints_.push_back(value);
80 else
81 *found = value;
82}
83
84void Cloth3D::updateSkinReference(int index, float x, float y, float z, float nx, float ny, float nz) {
85 auto found = std::find_if(skinConstraints_.begin(), skinConstraints_.end(),
86 [index](const SkinConstraint& item) { return item.particle == index; });
87 if (found == skinConstraints_.end()) throw Exception("Cloth3D.updateSkinReference: particle is not constrained");
88 const float normalLength = std::sqrt(nx * nx + ny * ny + nz * nz);
89 if (!std::isfinite(normalLength) || normalLength <= 1e-7f)
90 throw Exception("Cloth3D.updateSkinReference: normal must be finite and non-zero");
91 found->x = x;
92 found->y = y;
93 found->z = z;
94 found->nx = nx / normalLength;
95 found->ny = ny / normalLength;
96 found->nz = nz / normalLength;
97}
98
100 std::erase_if(skinConstraints_, [index](const SkinConstraint& item) { return item.particle == index; });
101}
102
104 return std::any_of(skinConstraints_.begin(), skinConstraints_.end(),
105 [index](const SkinConstraint& item) { return item.particle == index; });
106}
107
108void Cloth3D::attachParticle(int index, float x, float y, float z, float compliance) {
109 if (!validIndex(index)) throw Exception("Cloth3D.attachParticle: index out of range");
110 auto found = std::find_if(attachments_.begin(), attachments_.end(),
111 [index](const Attachment& item) { return item.particle == index; });
112 const Attachment value{index, x, y, z, std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f, 0.f};
113 if (found == attachments_.end())
114 attachments_.push_back(value);
115 else
116 *found = value;
117}
118
119void Cloth3D::updateAttachment(int index, float x, float y, float z) {
120 auto found = std::find_if(attachments_.begin(), attachments_.end(),
121 [index](const Attachment& item) { return item.particle == index; });
122 if (found == attachments_.end()) throw Exception("Cloth3D.updateAttachment: particle is not attached");
123 found->x = x;
124 found->y = y;
125 found->z = z;
126}
127
129 std::erase_if(attachments_, [index](const Attachment& item) { return item.particle == index; });
130}
131
132bool Cloth3D::isAttached(int index) const {
133 return std::any_of(attachments_.begin(), attachments_.end(),
134 [index](const Attachment& item) { return item.particle == index; });
135}
136
137void Cloth3D::setTetherScale(float scale) { tetherScale_ = std::isfinite(scale) ? std::max(0.f, scale) : 0.f; }
138
139void Cloth3D::setTetherCompliance(float compliance) {
140 tetherCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
141}
142
143void Cloth3D::setPressure(float pressure) { pressure_ = std::isfinite(pressure) ? std::max(0.f, pressure) : 0.f; }
144
145void Cloth3D::setVolumeCompliance(float compliance) {
146 volumeCompliance_ = std::isfinite(compliance) ? std::max(0.f, compliance) : 0.f;
147}
148
150 if (restVolume_ == 0.f) return 0.f;
151 double volume = 0.0;
152 for (const Tri& triangle : triangles_) {
153 const Particle& a = particles_[static_cast<size_t>(triangle.v[0])];
154 const Particle& b = particles_[static_cast<size_t>(triangle.v[1])];
155 const Particle& c = particles_[static_cast<size_t>(triangle.v[2])];
156 volume += (double(a.x) * (double(b.y) * c.z - double(b.z) * c.y) +
157 double(a.y) * (double(b.z) * c.x - double(b.x) * c.z) +
158 double(a.z) * (double(b.x) * c.y - double(b.y) * c.x)) /
159 6.0;
160 }
161 return static_cast<float>(volume);
162}
163
164void Cloth3D::solveTetherConstraints(float dt) {
165 if (tetherScale_ <= 0.f || tethers_.empty() || dt <= 0.f) return;
166 const float alpha = tetherCompliance_ / (dt * dt);
167 for (Tether& tether : tethers_) {
168 Particle& particle = particles_[static_cast<size_t>(tether.particle)];
169 const Particle& anchor = particles_[static_cast<size_t>(tether.anchor)];
170 if (particle.pinned) continue;
171 const float dx = particle.x - anchor.x;
172 const float dy = particle.y - anchor.y;
173 const float dz = particle.z - anchor.z;
174 const float distance = std::sqrt(dx * dx + dy * dy + dz * dz);
175 const float maximum = tether.maxLength * tetherScale_;
176 if (distance <= maximum || distance <= 1e-7f) continue;
177 const float weight = particle.inverseMass;
178 const float deltaLambda = (-(distance - maximum) - alpha * tether.lambda) / (weight + alpha);
179 tether.lambda += deltaLambda;
180 particle.x += weight * dx / distance * deltaLambda;
181 particle.y += weight * dy / distance * deltaLambda;
182 particle.z += weight * dz / distance * deltaLambda;
183 }
184}
185
186void Cloth3D::solveVolumeConstraint(float dt) {
187 if (pressure_ <= 0.f || restVolume_ == 0.f || dt <= 0.f) return;
188 std::vector<Vec3> gradients(particles_.size());
189 for (const Tri& triangle : triangles_) {
190 const Particle& a = particles_[static_cast<size_t>(triangle.v[0])];
191 const Particle& b = particles_[static_cast<size_t>(triangle.v[1])];
192 const Particle& c = particles_[static_cast<size_t>(triangle.v[2])];
193 const Vec3 av{a.x, a.y, a.z};
194 const Vec3 bv{b.x, b.y, b.z};
195 const Vec3 cv{c.x, c.y, c.z};
196 const Vec3 ga = cross(bv, cv);
197 const Vec3 gb = cross(cv, av);
198 const Vec3 gc = cross(av, bv);
199 for (const auto& [index, gradient] :
200 {std::pair{triangle.v[0], ga}, std::pair{triangle.v[1], gb}, std::pair{triangle.v[2], gc}}) {
201 gradients[static_cast<size_t>(index)].x += gradient.x / 6.f;
202 gradients[static_cast<size_t>(index)].y += gradient.y / 6.f;
203 gradients[static_cast<size_t>(index)].z += gradient.z / 6.f;
204 }
205 }
206
207 float denominator = 0.f;
208 for (size_t i = 0; i < particles_.size(); ++i)
209 if (!particles_[i].pinned) denominator += particles_[i].inverseMass * dot(gradients[i], gradients[i]);
210 const float alpha = volumeCompliance_ / (dt * dt);
211 denominator += alpha;
212 if (denominator <= 1e-10f) return;
213 const float constraint = getCurrentVolume() - restVolume_ * pressure_;
214 const float deltaLambda = (-constraint - alpha * volumeLambda_) / denominator;
215 volumeLambda_ += deltaLambda;
216 for (size_t i = 0; i < particles_.size(); ++i) {
217 if (particles_[i].pinned) continue;
218 particles_[i].x += particles_[i].inverseMass * gradients[i].x * deltaLambda;
219 particles_[i].y += particles_[i].inverseMass * gradients[i].y * deltaLambda;
220 particles_[i].z += particles_[i].inverseMass * gradients[i].z * deltaLambda;
221 }
222}
223
224void Cloth3D::solveSkinConstraints(float dt) {
225 if (dt <= 0.f) return;
226 for (SkinConstraint& skin : skinConstraints_) {
227 Particle& particle = particles_[static_cast<size_t>(skin.particle)];
228 if (particle.pinned) continue;
229 Vec3 delta{particle.x - skin.x, particle.y - skin.y, particle.z - skin.z};
230 float distance = length(delta);
231 if (skin.radius > 0.f && distance > skin.radius && distance > 1e-7f) {
232 const float alpha = skin.compliance / (dt * dt);
233 const float weight = particle.inverseMass;
234 const float dl = (-(distance - skin.radius) - alpha * skin.lambda) / (weight + alpha);
235 skin.lambda += dl;
236 particle.x += weight * delta.x / distance * dl;
237 particle.y += weight * delta.y / distance * dl;
238 particle.z += weight * delta.z / distance * dl;
239 }
240 if (skin.backstopDistance < 0.f || skin.backstopRadius <= 0.f) continue;
241 const Vec3 center{skin.x - skin.nx * skin.backstopDistance, skin.y - skin.ny * skin.backstopDistance,
242 skin.z - skin.nz * skin.backstopDistance};
243 delta = {particle.x - center.x, particle.y - center.y, particle.z - center.z};
244 distance = length(delta);
245 if (distance >= skin.backstopRadius) continue;
246 Vec3 direction = distance > 1e-7f ? Vec3{delta.x / distance, delta.y / distance, delta.z / distance}
247 : Vec3{skin.nx, skin.ny, skin.nz};
248 const float correction = skin.backstopRadius - distance;
249 particle.x += direction.x * correction;
250 particle.y += direction.y * correction;
251 particle.z += direction.z * correction;
252 }
253}
254
255void Cloth3D::solveAttachments(float dt) {
256 if (dt <= 0.f) return;
257 for (Attachment& attachment : attachments_) {
258 Particle& particle = particles_[static_cast<size_t>(attachment.particle)];
259 const Vec3 delta{particle.x - attachment.x, particle.y - attachment.y, particle.z - attachment.z};
260 const float distance = length(delta);
261 if (distance <= 1e-7f) continue;
262 const float alpha = attachment.compliance / (dt * dt);
263 const float weight = std::max(particle.inverseMass, 1.f);
264 const float dl = (-distance - alpha * attachment.lambda) / (weight + alpha);
265 attachment.lambda += dl;
266 particle.x += weight * delta.x / distance * dl;
267 particle.y += weight * delta.y / distance * dl;
268 particle.z += weight * delta.z / distance * dl;
269 }
270}
271
272} // namespace eve::physics
double z
double y
double x
double volume
int triangle
Definition FluidSdf.cpp:554
float maximum[3]
std::vector< std::uint32_t > indices
std::int32_t c
eve::ResourcePin pinned
float length
std::array< float, 3 > scale
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
double dt
Object::Ptr value
RoadLaneDirection direction
bool found
SceneSpatialConstraint constraint
float dy
Definition Shadow.cpp:151
double weight
uint32_t index
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
float getBendCompliance() const
Return XPBD distance-bend compliance in m/N.
float getPressure() const
Return the closed-mesh target volume ratio.
uint64_t getCollisionCategoryBits() const
Return cloth collision category bits.
void setPressure(float pressure)
Set closed-mesh target volume ratio; zero disables volume solving.
uint64_t getCollisionMaskBits() const
Return cloth collision mask bits.
bool isAttached(int index) const
Return whether a particle currently has an attachment.
void setTetherScale(float scale)
Set tether maximum-length scale; zero disables tethers, one uses baked lengths.
void updateSkinReference(int index, float x, float y, float z, float nx, float ny, float nz)
Update the animated reference pose of an existing skin constraint.
bool supportsFeature(const std::string &feature) const
Query a stable cloth feature name without assuming CPU/GPU parity.
int getTetherConstraintCount() const
Return baked geodesic tether count.
float getVolumeCompliance() const
Return XPBD closed-volume compliance.
float getTetherScale() const
Return the current tether length scale.
void clearSkinConstraint(int index)
Remove a particle's skin/backstop constraint.
int getDistanceConstraintCount() const
Return the current distance-constraint count.
void detachParticle(int index)
Detach a particle; its simulated velocity remains continuous.
float getShearCompliance() const
Return XPBD shear compliance in m/N.
float getCurrentVolume() const
Return current signed mesh volume, or zero for an open model.
bool hasSkinConstraint(int index) const
Return whether a particle has a skin/backstop constraint.
eve::Result< std::vector< std::uint32_t > > captureTriangleIndices() const
Copy current surviving triangle corners into an owning ordered index stream. @ownership Owns returned...
float getTetherCompliance() const
Return XPBD tether compliance in m/N.
void updateAttachment(int index, float x, float y, float z)
Move an existing attachment target without recreating it.
void setVolumeCompliance(float compliance)
Set XPBD closed-volume compliance in m^3/N.
float getStretchCompliance() const
Return XPBD stretch compliance in m/N.
float getCollisionRestitution() const
Return cloth-side restitution.
int getSkinConstraintCount() const
Return active skin-constraint count.
int getTriangleCount() const
Return the current render/collision triangle count, reduced by tearing.
void setTetherCompliance(float compliance)
Set XPBD tether compliance in m/N.
void attachParticle(int index, float x, float y, float z, float compliance=0.f)
Attach a particle to a world-space target using an XPBD point constraint.
void setSkinConstraint(int index, float x, float y, float z, float nx, float ny, float nz, float radius, float backstopDistance=-1.f, float backstopRadius=0.f, float compliance=0.f)
Constrain a particle around an animated skin reference and optional backstop sphere.
float getCollisionFriction() const
Return cloth-side Coulomb friction.
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29