载入中...
搜索中...
未找到
SoftBody3D.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <glm/gtc/quaternion.hpp>
5#include <initializer_list>
6#include <limits>
7#include <string>
8#include "common/Exception.h"
12
13// SoftBody3D.cpp
14namespace eve::physics {
15namespace {
16
17using V3 = glm::vec3;
18
19float tetraVolume(const V3& a, const V3& b, const V3& c, const V3& d) {
20 return std::fabs(glm::dot(b - a, glm::cross(c - a, d - a))) / 6.f;
21}
22
23glm::quat bestFitRotation(const glm::mat3& covariance) {
24 glm::quat rotation(1.f, 0.f, 0.f, 0.f);
25 for (int i = 0; i < 8; ++i) {
26 const glm::mat3 basis = glm::mat3_cast(rotation);
27 const V3 omega = (glm::cross(basis[0], covariance[0]) + glm::cross(basis[1], covariance[1]) +
28 glm::cross(basis[2], covariance[2])) /
29 (std::fabs(glm::dot(basis[0], covariance[0]) + glm::dot(basis[1], covariance[1]) +
30 glm::dot(basis[2], covariance[2])) +
31 1e-8f);
32 const float magnitude = glm::length(omega);
33 if (magnitude < 1e-6f) break;
34 rotation = glm::normalize(glm::angleAxis(magnitude, omega / magnitude) * rotation);
35 }
36 return rotation;
37}
38
39} // namespace
40
42 float originX, float originY, float originZ) {
43 SoftBody3DDefinition definition;
44 definition.cols = cols;
45 definition.rows = rows;
46 definition.layers = layers;
47 definition.spacing = spacing;
48 definition.originX = originX;
49 definition.originY = originY;
50 definition.originZ = originZ;
51 return create(definition);
52}
53
56 if (!registered) return eve::Result<std::unique_ptr<SoftBody3D>>::failure(registered.status());
57 auto valid = definition.validate();
58 if (!valid) return eve::Result<std::unique_ptr<SoftBody3D>>::failure(valid.status());
59 auto result = std::unique_ptr<SoftBody3D>(new SoftBody3D(definition.cols, definition.rows, definition.layers,
60 definition.spacing, definition.originX, definition.originY,
61 definition.originZ));
62 result->setGravity(definition.gravityX, definition.gravityY, definition.gravityZ);
63 result->setDeformationResistance(definition.deformationResistance);
64 result->setIterations(definition.iterations);
65 result->setDamping(definition.damping);
66 result->setParticleRadius(definition.particleRadius);
67 result->setParticleMass(definition.particleMass);
68 result->setPlasticity(definition.plasticYield, definition.plasticCreep, definition.plasticRecovery,
69 definition.maxDeformation);
70 result->setSelfCollision(definition.selfCollision);
71 return eve::Result<std::unique_ptr<SoftBody3D>>::success(std::move(result));
72}
73
74SoftBody3D::SoftBody3D(int cols, int rows, int layers, float spacing, float originX, float originY, float originZ)
75 : cols_(cols), rows_(rows), layers_(layers), spacing_(spacing) {
76 particles_.reserve(static_cast<size_t>(cols_) * rows_ * layers_);
77 for (int z = 0; z < layers_; ++z) {
78 for (int y = 0; y < rows_; ++y) {
79 for (int x = 0; x < cols_; ++x) {
80 const float px = originX + float(x) * spacing_;
81 const float py = originY + float(y) * spacing_;
82 const float pz = originZ + float(z) * spacing_;
83 particles_.push_back({px, py, pz, px, py, pz, px, py, pz, false});
84 }
85 }
86 }
87 clusters_.reserve(static_cast<size_t>(cols_ - 1) * (rows_ - 1) * (layers_ - 1));
88 for (int z = 0; z + 1 < layers_; ++z) {
89 for (int y = 0; y + 1 < rows_; ++y) {
90 for (int x = 0; x + 1 < cols_; ++x) {
91 Cluster cluster;
92 cluster.indices[0] = indexOf(x, y, z);
93 cluster.indices[1] = indexOf(x + 1, y, z);
94 cluster.indices[2] = indexOf(x, y + 1, z);
95 cluster.indices[3] = indexOf(x + 1, y + 1, z);
96 cluster.indices[4] = indexOf(x, y, z + 1);
97 cluster.indices[5] = indexOf(x + 1, y, z + 1);
98 cluster.indices[6] = indexOf(x, y + 1, z + 1);
99 cluster.indices[7] = indexOf(x + 1, y + 1, z + 1);
100 clusters_.push_back(cluster);
101 }
102 }
103 }
104 particleRadius_ = spacing_ * 0.35f;
105}
106
108
110 destroyed_ = true;
111 world_ = nullptr;
112 collisionWorld_ = nullptr;
113 ownedCollisionWorld_.reset();
114}
115
116bool SoftBody3D::validIndex(int index) const noexcept { return index >= 0 && index < getParticleCount(); }
117
118int SoftBody3D::indexOf(int x, int y, int z) const noexcept { return (z * rows_ + y) * cols_ + x; }
119
120void SoftBody3D::setGravity(float x, float y, float z) {
121 gravityX_ = std::isfinite(x) ? x : 0.f;
122 gravityY_ = std::isfinite(y) ? y : 0.f;
123 gravityZ_ = std::isfinite(z) ? z : 0.f;
124}
125
126void SoftBody3D::setDeformationResistance(float value) { deformationResistance_ = std::clamp(value, 0.f, 1.f); }
127
128float SoftBody3D::getDeformationResistance() const { return deformationResistance_; }
129
130void SoftBody3D::setIterations(int value) { iterations_ = std::clamp(value, 1, 32); }
131void SoftBody3D::setDamping(float value) { damping_ = std::clamp(value, 0.f, 1.f); }
133 if (std::isfinite(value)) particleRadius_ = std::max(0.f, value);
134}
135float SoftBody3D::getParticleRadius() const { return particleRadius_; }
137 if (std::isfinite(value)) particleMass_ = std::max(1e-5f, value);
138}
139
140void SoftBody3D::setPlasticity(float yield, float creep, float recovery, float maxDeformation) {
141 plasticYield_ = std::max(0.f, std::isfinite(yield) ? yield : 0.f);
142 plasticCreep_ = std::clamp(std::isfinite(creep) ? creep : 0.f, 0.f, 1.f);
143 plasticRecovery_ = std::max(0.f, std::isfinite(recovery) ? recovery : 0.f);
144 maxDeformation_ = std::max(0.f, std::isfinite(maxDeformation) ? maxDeformation : 0.f);
145}
146
147float SoftBody3D::getPlasticYield() const { return plasticYield_; }
148float SoftBody3D::getPlasticCreep() const { return plasticCreep_; }
149float SoftBody3D::getPlasticRecovery() const { return plasticRecovery_; }
150float SoftBody3D::getMaxDeformation() const { return maxDeformation_; }
151int SoftBody3D::getLayers() const { return layers_; }
152
153void SoftBody3D::setBounds(float x, float y, float z, float width, float height, float depth) {
154 boundX_ = x;
155 boundY_ = y;
156 boundZ_ = z;
157 boundW_ = std::max(0.f, width);
158 boundH_ = std::max(0.f, height);
159 boundD_ = std::max(0.f, depth);
160 hasBounds_ = std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && std::isfinite(width) &&
161 std::isfinite(height) && std::isfinite(depth);
162}
163
165 if (!validIndex(index)) throw Exception("SoftBody3D.pin: index out of range");
166 particles_[static_cast<size_t>(index)].pinned = true;
167}
169 if (!validIndex(index)) throw Exception("SoftBody3D.unpin: index out of range");
170 particles_[static_cast<size_t>(index)].pinned = false;
171}
173 if (!validIndex(index)) throw Exception("SoftBody3D.isPinned: index out of range");
174 return particles_[static_cast<size_t>(index)].pinned;
175}
176
177int SoftBody3D::grabAt(float x, float y, float z, float radius) {
178 float best = radius * radius;
179 int found = -1;
180 for (int i = 0; i < getParticleCount(); ++i) {
181 const Particle& p = particles_[static_cast<size_t>(i)];
182 const float dx = p.x - x, dy = p.y - y, dz = p.z - z;
183 const float distanceSquared = dx * dx + dy * dy + dz * dz;
184 if (!p.pinned && distanceSquared <= best) {
185 best = distanceSquared;
186 found = i;
187 }
188 }
189 if (found >= 0) {
190 grabIndex_ = found;
191 moveGrab(x, y, z);
192 }
193 return found;
194}
195
196void SoftBody3D::moveGrab(float x, float y, float z) {
197 if (grabIndex_ < 0) return;
198 grabX_ = x;
199 grabY_ = y;
200 grabZ_ = z;
201 Particle& p = particles_[static_cast<size_t>(grabIndex_)];
202 p.x = p.px = x;
203 p.y = p.py = y;
204 p.z = p.pz = z;
205}
206
207void SoftBody3D::applyForce(float x, float y, float z) {
208 if (std::isfinite(x)) forceX_ += x;
209 if (std::isfinite(y)) forceY_ += y;
210 if (std::isfinite(z)) forceZ_ += z;
211}
212
213void SoftBody3D::interactAt(float x, float y, float z, float radius, float strength) {
214 hasInteraction_ = radius > 0.f && std::isfinite(radius) && std::isfinite(strength);
215 interactX_ = x;
216 interactY_ = y;
217 interactZ_ = z;
218 interactRadius_ = radius;
219 interactStrength_ = strength;
220}
221
223 if (!validIndex(index)) throw Exception("SoftBody3D.getParticleX: index out of range");
224 return particles_[static_cast<size_t>(index)].x;
225}
227 if (!validIndex(index)) throw Exception("SoftBody3D.getParticleY: index out of range");
228 return particles_[static_cast<size_t>(index)].y;
229}
231 if (!validIndex(index)) throw Exception("SoftBody3D.getParticleZ: index out of range");
232 return particles_[static_cast<size_t>(index)].z;
233}
234void SoftBody3D::setParticlePosition(int index, float x, float y, float z) {
235 if (!validIndex(index)) throw Exception("SoftBody3D.setParticlePosition: index out of range");
236 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
237 throw Exception("SoftBody3D.setParticlePosition: coordinates must be finite");
238 Particle& p = particles_[static_cast<size_t>(index)];
239 p.x = p.px = x;
240 p.y = p.py = y;
241 p.z = p.pz = z;
242}
243
245 for (Particle& p : particles_) {
246 p.x = p.px = p.rx;
247 p.y = p.py = p.ry;
248 p.z = p.pz = p.rz;
249 p.pinned = false;
250 }
251 for (Cluster& cluster : clusters_)
252 for (auto& offset : cluster.plastic) offset[0] = offset[1] = offset[2] = 0.f;
253 grabIndex_ = -1;
254 forceX_ = forceY_ = forceZ_ = 0.f;
255 hasInteraction_ = false;
256}
257
258void SoftBody3D::integrate(float dt) {
259 const float velocityScale = std::max(0.f, 1.f - damping_);
260 for (int i = 0; i < getParticleCount(); ++i) {
261 Particle& p = particles_[static_cast<size_t>(i)];
262 if (p.pinned || i == grabIndex_) continue;
263 float ax = gravityX_ + forceX_ / particleMass_;
264 float ay = gravityY_ + forceY_ / particleMass_;
265 float az = gravityZ_ + forceZ_ / particleMass_;
266 if (hasInteraction_) {
267 const V3 delta = V3(interactX_ - p.x, interactY_ - p.y, interactZ_ - p.z);
268 const float distance = glm::length(delta);
269 if (distance > 1e-6f && distance < interactRadius_) {
270 const float falloff = 1.f - distance / interactRadius_;
271 const V3 field = delta * (interactStrength_ * falloff / distance);
272 ax += field.x;
273 ay += field.y;
274 az += field.z;
275 }
276 }
277 const float vx = (p.x - p.px) * velocityScale;
278 const float vy = (p.y - p.py) * velocityScale;
279 const float vz = (p.z - p.pz) * velocityScale;
280 p.px = p.x;
281 p.py = p.y;
282 p.pz = p.z;
283 p.x += vx + ax * dt * dt;
284 p.y += vy + ay * dt * dt;
285 p.z += vz + az * dt * dt;
286 }
287}
288
289void SoftBody3D::solveShapeMatching(float dt) {
290 const float stiffness = 1.f - std::pow(1.f - deformationResistance_, 1.f / float(iterations_));
291 for (Cluster& cluster : clusters_) {
292 V3 currentCom(0.f), restCom(0.f);
293 for (int i = 0; i < 8; ++i) {
294 const Particle& p = particles_[static_cast<size_t>(cluster.indices[i])];
295 currentCom += V3(p.x, p.y, p.z);
296 restCom += V3(p.rx + cluster.plastic[i][0], p.ry + cluster.plastic[i][1], p.rz + cluster.plastic[i][2]);
297 }
298 currentCom /= 8.f;
299 restCom /= 8.f;
300 glm::mat3 covariance(0.f);
301 for (int i = 0; i < 8; ++i) {
302 const Particle& p = particles_[static_cast<size_t>(cluster.indices[i])];
303 const V3 current = V3(p.x, p.y, p.z) - currentCom;
304 const V3 rest =
305 V3(p.rx + cluster.plastic[i][0], p.ry + cluster.plastic[i][1], p.rz + cluster.plastic[i][2]) - restCom;
306 covariance += glm::outerProduct(current, rest);
307 }
308 const glm::mat3 rotation = glm::mat3_cast(bestFitRotation(covariance));
309 float deformation = 0.f;
310 V3 restCurrent[8];
311 for (int i = 0; i < 8; ++i) {
312 Particle& p = particles_[static_cast<size_t>(cluster.indices[i])];
313 restCurrent[i] = glm::transpose(rotation) * (V3(p.x, p.y, p.z) - currentCom);
314 const V3 rest =
315 V3(p.rx + cluster.plastic[i][0], p.ry + cluster.plastic[i][1], p.rz + cluster.plastic[i][2]) - restCom;
316 deformation += glm::length(restCurrent[i] - rest) / spacing_;
317 if (!p.pinned && cluster.indices[i] != grabIndex_) {
318 const V3 goal = currentCom + rotation * rest;
319 p.x += (goal.x - p.x) * stiffness;
320 p.y += (goal.y - p.y) * stiffness;
321 p.z += (goal.z - p.z) * stiffness;
322 }
323 }
324 deformation /= 8.f;
325 const float creep = deformation > plasticYield_ ? plasticCreep_ * dt : 0.f;
326 const float recovery = plasticRecovery_ * dt;
327 if (maxDeformation_ > 0.f && (creep > 0.f || recovery > 0.f)) {
328 for (int i = 0; i < 8; ++i) {
329 const Particle& p = particles_[static_cast<size_t>(cluster.indices[i])];
330 const V3 original = V3(p.rx, p.ry, p.rz) - restCom;
331 V3 offset(cluster.plastic[i][0], cluster.plastic[i][1], cluster.plastic[i][2]);
332 offset += (restCurrent[i] - original - offset) * std::min(1.f, creep);
333 offset += (V3(0.f) - offset) * std::min(1.f, recovery);
334 const float limit = maxDeformation_ * spacing_;
335 const float length = glm::length(offset);
336 if (length > limit && length > 1e-6f) offset *= limit / length;
337 cluster.plastic[i][0] = offset.x;
338 cluster.plastic[i][1] = offset.y;
339 cluster.plastic[i][2] = offset.z;
340 }
341 }
342 }
343}
344
345void SoftBody3D::solveSelfCollision() {
346 if (!selfCollision_ || particleRadius_ <= 0.f) return;
347 const float minimum = particleRadius_ * 2.f;
348 const float minimumSquared = minimum * minimum;
349 for (int i = 0; i < getParticleCount(); ++i) {
350 for (int j = i + 1; j < getParticleCount(); ++j) {
351 Particle& a = particles_[static_cast<size_t>(i)];
352 Particle& b = particles_[static_cast<size_t>(j)];
353 V3 delta(b.x - a.x, b.y - a.y, b.z - a.z);
354 const float distanceSquared = glm::dot(delta, delta);
355 if (distanceSquared >= minimumSquared || distanceSquared < 1e-12f) continue;
356 const float distance = std::sqrt(distanceSquared);
357 const V3 correction = delta * ((minimum - distance) / distance * 0.5f);
358 if (!a.pinned && i != grabIndex_) {
359 a.x -= correction.x;
360 a.y -= correction.y;
361 a.z -= correction.z;
362 }
363 if (!b.pinned && j != grabIndex_) {
364 b.x += correction.x;
365 b.y += correction.y;
366 b.z += correction.z;
367 }
368 }
369 }
370}
371
372void SoftBody3D::collideWorld(float dt) {
373 if (!collisionWorld_ || !collisionWorld_->softBodyCollisionAvailable() || particleRadius_ <= 0.f) return;
374 softbody::SoftBodyContact contact;
375 const float inverseDt = dt > 1e-6f ? 1.f / dt : 0.f;
376 for (Particle& p : particles_) {
377 if (p.pinned ||
378 collisionWorld_->probeSoftBodyParticle(p.x, p.y, p.z, particleRadius_, contact) !=
380 !contact.hit)
381 continue;
382 const V3 velocity = V3(p.x - p.px, p.y - p.py, p.z - p.pz) * inverseDt;
383 p.x += contact.nx * contact.depth;
384 p.y += contact.ny * contact.depth;
385 p.z += contact.nz * contact.depth;
386 if (contact.dynamicBody) {
387 const float normalVelocity = glm::dot(velocity, V3(contact.nx, contact.ny, contact.nz));
388 if (normalVelocity < 0.f) {
389 const float impulse = std::min(-normalVelocity * particleMass_, particleMass_ * 8.f);
390 collisionWorld_->applySoftBodyImpulse(contact.bodyId, -contact.nx * impulse, -contact.ny * impulse,
391 -contact.nz * impulse);
392 }
393 }
394 }
395}
396
397void SoftBody3D::collideBounds() {
398 if (!hasBounds_) return;
399 const V3 minimum(boundX_, boundY_, boundZ_);
400 const V3 maximum(boundX_ + boundW_, boundY_ + boundH_, boundZ_ + boundD_);
401 for (Particle& p : particles_) {
402 if (p.pinned) continue;
403 p.x = std::clamp(p.x, minimum.x, maximum.x);
404 p.y = std::clamp(p.y, minimum.y, maximum.y);
405 p.z = std::clamp(p.z, minimum.z, maximum.z);
406 }
407}
408
410 if (destroyed_) return;
411 updateSubsteps(std::clamp(dt, 0.f, 0.05f), 2);
412}
413
414void SoftBody3D::updateSubsteps(float dt, int substeps) {
415 if (destroyed_ || substeps < 1) return;
416 const float h = dt / float(substeps);
417 for (int substep = 0; substep < substeps; ++substep) {
418 integrate(h);
419 for (int iteration = 0; iteration < iterations_; ++iteration) {
420 solveShapeMatching(h);
421 solveSelfCollision();
422 collideWorld(h);
423 collideBounds();
424 }
425 if (grabIndex_ >= 0) moveGrab(grabX_, grabY_, grabZ_);
426 }
427 forceX_ = forceY_ = forceZ_ = 0.f;
428 hasInteraction_ = false;
429}
430
432 if (destroyed_)
434 "Cannot step a destroyed soft body",
435 "physics.softbody3d.step"));
436 auto valid = detail::validateSimulationStep(stepValue, settings, observation_);
437 if (!valid) return valid;
438 auto next = detail::advanceSimulationObservation(observation_, stepValue);
439 if (!next) return eve::Result<void>::failure(next.status());
440 updateSubsteps(static_cast<float>(stepValue.delta.seconds()), settings.subStepCount);
441 observation_ = std::move(next).takeValue();
443}
444
446 auto valid = detail::validateSimulationObservation(observation, "physics.softbody3d.restoreObservation");
447 if (!valid) return valid;
448 if (destroyed_)
450 "Cannot restore a destroyed soft body",
451 "physics.softbody3d.restoreObservation"));
452 observation_ = observation;
454}
455
457 if (clusters_.empty()) return 1.f;
458 float volume = 0.f;
459 for (const Cluster& cluster : clusters_) {
460 V3 p[8];
461 for (int i = 0; i < 8; ++i) {
462 const Particle& particle = particles_[static_cast<size_t>(cluster.indices[i])];
463 p[i] = V3(particle.x, particle.y, particle.z);
464 }
465 volume += tetraVolume(p[0], p[1], p[3], p[7]) + tetraVolume(p[0], p[3], p[2], p[7]) +
466 tetraVolume(p[0], p[2], p[6], p[7]) + tetraVolume(p[0], p[6], p[4], p[7]) +
467 tetraVolume(p[0], p[4], p[5], p[7]) + tetraVolume(p[0], p[5], p[1], p[7]);
468 }
469 const float rest = float(clusters_.size()) * spacing_ * spacing_ * spacing_;
470 return rest > 0.f ? volume / rest : 1.f;
471}
472
473} // namespace eve::physics
474
475// SoftBodyModel.cpp
476namespace eve::physics {
477// namespace
478
480 if (sourceMesh.empty())
482 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "sourceMesh must not be empty", "sourceMesh"));
483 if (particles.empty())
485 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "model must contain particles", "particles"));
486 for (std::size_t index = 0; index < particles.size(); ++index) {
487 const auto& particle = particles[index];
488 if (!std::isfinite(particle.x) || !std::isfinite(particle.y) || !std::isfinite(particle.z))
490 "particle position must be finite",
491 "particles[" + std::to_string(index) + "]"));
492 }
493 if (surfaceIndices.empty() || surfaceIndices.size() % 3 != 0)
495 eve::DiagnosticCode::InvalidArgument, "surface indices must contain complete triangles", "surfaceIndices"));
496 for (const auto index : surfaceIndices)
497 if (index >= surfaceBindings.size())
499 eve::DiagnosticCode::InvalidArgument, "surface index is out of range", "surfaceIndices"));
500 if (surfaceBindings.empty())
502 eve::DiagnosticCode::InvalidArgument, "surface bindings must not be empty", "surfaceBindings"));
503 for (const auto& binding : surfaceBindings)
504 if (binding.particleIndex >= particles.size())
506 eve::DiagnosticCode::InvalidArgument, "surface binding particle is out of range", "surfaceBindings"));
507 if (clusters.empty())
509 "model must contain shape clusters", "clusters"));
510 for (const auto& cluster : clusters) {
511 if (cluster.particleIndices.size() < 3)
514 "shape cluster must contain at least three particles", "clusters"));
515 for (const auto index : cluster.particleIndices)
516 if (index >= particles.size())
518 eve::DiagnosticCode::InvalidArgument, "cluster particle is out of range", "clusters"));
519 }
521}
522
523} // namespace eve::physics
524
525// SoftBodyModelDefinition.cpp
526namespace eve::physics {
527namespace {
528const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
529 const auto found = object.find(std::string(name));
530 return found == object.end() ? nullptr : &found->second;
531}
532
533bool hasExactFields(const eve::Value::Object& object, std::initializer_list<std::string_view> expected) {
534 if (object.size() != expected.size()) return false;
535 for (const auto name : expected)
536 if (!object.contains(std::string(name))) return false;
537 return true;
538}
539
540std::string_view surfaceName(SoftBodySurfaceSampling value) {
541 switch (value) {
542 case SoftBodySurfaceSampling::None: return "none";
543 case SoftBodySurfaceSampling::Vertices: return "vertices";
544 case SoftBodySurfaceSampling::Voxels: return "voxels";
545 }
546 return "";
547}
548
549std::string_view volumeName(SoftBodyVolumeSampling value) {
550 switch (value) {
551 case SoftBodyVolumeSampling::None: return "none";
552 case SoftBodyVolumeSampling::Voxels: return "voxels";
553 }
554 return "";
555}
556
557} // namespace
558
560 if (sourceMesh.empty())
562 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "sourceMesh must not be empty", "sourceMesh"));
563 if (surfaceName(surfaceSampling).empty())
565 eve::DiagnosticCode::InvalidArgument, "unsupported surface sampling mode", "surfaceSampling"));
566 if (volumeName(volumeSampling).empty())
568 "unsupported volume sampling mode", "volumeSampling"));
569 if (surfaceResolution < 2 || surfaceResolution > 128 || volumeResolution < 2 || volumeResolution > 128 ||
570 shapeResolution < 2 || shapeResolution > 128)
572 eve::DiagnosticCode::InvalidArgument, "sampling resolutions must be in [2, 128]", "resolution"));
573 if (!std::isfinite(maxAnisotropy) || maxAnisotropy < 1.f || maxAnisotropy > 5.f)
575 "maxAnisotropy must be in [1, 5]", "maxAnisotropy"));
576 if (!std::isfinite(smoothing) || smoothing < 0.f || smoothing > 1.f)
578 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "smoothing must be in [0, 1]", "smoothing"));
581 eve::DiagnosticCode::InvalidArgument, "at least one sampling mode must be enabled", "sampling"));
583}
584
586 auto valid = validate();
587 if (!valid) return eve::Result<eve::Value>::failure(valid.status());
589 object["schema"] = std::string(SchemaId);
590 object["schemaVersion"] = static_cast<std::int64_t>(SchemaVersion);
591 object["sourceMesh"] = sourceMesh;
592 object["surfaceSampling"] = std::string(surfaceName(surfaceSampling));
593 object["surfaceResolution"] = static_cast<std::int64_t>(surfaceResolution);
594 object["volumeSampling"] = std::string(volumeName(volumeSampling));
595 object["volumeResolution"] = static_cast<std::int64_t>(volumeResolution);
596 object["shapeResolution"] = static_cast<std::int64_t>(shapeResolution);
597 object["maxAnisotropy"] = maxAnisotropy;
598 object["smoothing"] = smoothing;
599 return eve::Result<eve::Value>::success(eve::Value(std::move(object)));
600}
601
603 const auto* object = value.getIf<eve::Value::Object>();
604 if (!object)
606 eve::DiagnosticCode::InvalidArgument, "soft-body model must be an object", "softbodyModel"));
607 const std::initializer_list<std::string_view> names = {
608 "schema", "schemaVersion", "sourceMesh", "surfaceSampling", "surfaceResolution",
609 "volumeSampling", "volumeResolution", "shapeResolution", "maxAnisotropy", "smoothing"};
610 if (!hasExactFields(*object, names))
612 eve::DiagnosticCode::InvalidArgument, "soft-body model fields do not match version 1", "softbodyModel"));
613 const auto* schema = field(*object, "schema");
614 const auto* version = field(*object, "schemaVersion");
615 const auto* mesh = field(*object, "sourceMesh");
616 const auto* surface = field(*object, "surfaceSampling");
617 const auto* volume = field(*object, "volumeSampling");
618 if (!schema || !schema->isString() || schema->asString() != SchemaId)
620 eve::DiagnosticCode::InvalidArgument, "unexpected soft-body model schema", "schema"));
621 if (!version || !version->isInt64() || version->asInt() != SchemaVersion)
623 eve::DiagnosticCode::InvalidArgument, "unsupported soft-body model version", "schemaVersion"));
624 if (!mesh || !mesh->isString() || !surface || !surface->isString() || !volume || !volume->isString())
626 eve::DiagnosticCode::InvalidArgument, "model string field has the wrong type", "softbodyModel"));
627
629 result.sourceMesh = mesh->asString();
630 if (surface->asString() == "none")
631 result.surfaceSampling = SoftBodySurfaceSampling::None;
632 else if (surface->asString() == "vertices")
634 else if (surface->asString() == "voxels")
635 result.surfaceSampling = SoftBodySurfaceSampling::Voxels;
636 else
638 eve::DiagnosticCode::InvalidArgument, "unsupported surface sampling mode", "surfaceSampling"));
639 if (volume->asString() == "none")
640 result.volumeSampling = SoftBodyVolumeSampling::None;
641 else if (volume->asString() == "voxels")
642 result.volumeSampling = SoftBodyVolumeSampling::Voxels;
643 else
645 eve::DiagnosticCode::InvalidArgument, "unsupported volume sampling mode", "volumeSampling"));
646
647 auto integer = [&](std::string_view name, int& destination) -> bool {
648 const auto* item = field(*object, name);
649 if (!item || !item->isInt64() || item->asInt() < 0 || item->asInt() > 1000000) return false;
650 destination = static_cast<int>(item->asInt());
651 return true;
652 };
653 auto number = [&](std::string_view name, float& destination) -> bool {
654 const auto* item = field(*object, name);
655 if (!item || !item->isNumeric()) return false;
656 const double parsed = item->isDouble() ? item->asDouble() : static_cast<double>(item->asInt());
657 if (!std::isfinite(parsed)) return false;
658 destination = static_cast<float>(parsed);
659 return true;
660 };
661 if (!integer("surfaceResolution", result.surfaceResolution) ||
662 !integer("volumeResolution", result.volumeResolution) || !integer("shapeResolution", result.shapeResolution) ||
663 !number("maxAnisotropy", result.maxAnisotropy) || !number("smoothing", result.smoothing))
665 eve::DiagnosticCode::InvalidArgument, "model numeric field has the wrong type", "softbodyModel"));
666 auto valid = result.validate();
669}
670
674 auto field = [](const char* name, ValueType type, const char* title, std::string defaultJson) {
676 result.name = name;
677 result.type = type;
678 result.required = true;
679 result.title = title;
680 result.defaultJson = std::move(defaultJson);
681 return result;
682 };
683 auto resolution = [&](const char* name, const char* title, int value) {
684 auto result = field(name, ValueType::Integer, title, std::to_string(value));
685 result.minimum = 2;
686 result.maximum = 128;
687 return result;
688 };
690 schema.id = std::string(SchemaId);
691 schema.version = static_cast<int>(SchemaVersion);
692 schema.title = "Soft body model";
693 schema.description = "Mesh source and deterministic sampling settings used to cook a SoftBodyModel.";
694 schema.additionalProperties = false;
695 schema.fields = {field("schema", ValueType::String, "Schema", "\"physics:softbody-model\""),
696 resolution("schemaVersion", "Schema version", 1),
697 field("sourceMesh", ValueType::String, "Source mesh", "\"\""),
698 field("surfaceSampling", ValueType::String, "Surface sampling", "\"vertices\""),
699 resolution("surfaceResolution", "Surface resolution", 16),
700 field("volumeSampling", ValueType::String, "Volume sampling", "\"none\""),
701 resolution("volumeResolution", "Volume resolution", 16),
702 resolution("shapeResolution", "Shape resolution", 48),
703 field("maxAnisotropy", ValueType::Number, "Maximum anisotropy", "3.0"),
704 field("smoothing", ValueType::Number, "Smoothing", "0.25")};
705 schema.fields[1].minimum = schema.fields[1].maximum = 1;
706 schema.fields[8].minimum = 1;
707 schema.fields[8].maximum = 5;
708 schema.fields[9].minimum = 0;
709 schema.fields[9].maximum = 1;
710 return schema;
711}
712
720
721} // namespace eve::physics
double z
double y
double x
double volume
std::string title
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
int rows
int cols
float strength
float maximum[3]
float minimum[3]
std::int32_t c
eve::ResourcePin pinned
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
float length
size_t offset
std::array< float, 4 > rotation
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
OceanWakeSettings settings
OceanMeshSettings mesh
glm::dvec3 dx
glm::dvec3 velocity
glm::dvec3 dz
double dt
eve::action::ActionVfxBinding binding
Object::Ptr value
float d
double number
bool found
double current
std::string string
float dy
Definition Shadow.cpp:151
std::map< Cell, int > best
int spacing
Json object
int limit
Definition TreeMesh.cpp:166
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
uint32_t index
Contact contact
std::array< double, 3 > impulse
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.
Definition Time.cpp:29
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Volumetric particle soft body using overlapping shape-matching clusters.
Definition SoftBody3D.h:27
int getParticleCount() const
Definition SoftBody3D.h:174
void applyForce(float x, float y, float z)
Applies force.
void pin(int index)
Pin.
void setParticleMass(float value)
Sets the particle mass.
void update(float dt)
Advances using a legacy variable timestep clamped to 50 ms.
void setBounds(float x, float y, float z, float width, float height, float depth)
Sets the bounds.
SimulationObservation observation() const noexcept override
Returns completed fixed-step metadata by value.
Definition SoftBody3D.h:65
float getParticleZ(int index) const
void setIterations(int value)
Sets the iterations.
void setDeformationResistance(float value)
Sets the deformation resistance.
float getPlasticCreep() const
Returns the plastic creep.
eve::Result< void > step(const eve::SimulationStep &step, const SimulationSettings &settings) override
Advances through the checked fixed-step backend contract.
~SoftBody3D() override
Soft body 3 d.
float getMaxDeformation() const
Returns the max deformation.
float getVolumeRatio() const
Returns current cell volume divided by undeformed rest volume.
float getPlasticYield() const
Returns the plastic yield.
void moveGrab(float x, float y, float z)
Moves grab.
void setGravity(float x, float y, float z)
Sets the gravity.
void setPlasticity(float yield, float creep, float recovery, float maxDeformation)
Sets the plasticity.
void setParticlePosition(int index, float x, float y, float z)
float getDeformationResistance() const
Returns the deformation resistance.
static eve::Result< std::unique_ptr< SoftBody3D > > create(const SoftBody3DDefinition &definition)
Creates a soft body from the canonical versioned definition.
void interactAt(float x, float y, float z, float radius, float strength)
Interact at.
SoftBody3D(const SoftBody3D &)=delete
float getPlasticRecovery() const
Returns the plastic recovery.
eve::Result< void > restoreObservation(const SimulationObservation &observation) override
Restores checked progress metadata; particle state is unchanged.
void setParticleRadius(float value)
Sets the particle radius.
void setDamping(float value)
Sets the damping.
bool isPinned(int index) const
True when pinned.
float getParticleX(int index) const
float getParticleY(int index) const
int grabAt(float x, float y, float z, float radius)
Grab at.
void unpin(int index)
Unpin.
static eve::Result< std::unique_ptr< SoftBody3D > > create(int cols, int rows, int layers, float spacing, float originX, float originY, float originZ)
Creates a validated volumetric soft body.
void destroy()
Destroys .
float getParticleRadius() const
Returns the particle radius.
virtual void applySoftBodyImpulse(int bodyId, float x, float y, float z)=0
Apply a world-space impulse to a previously reported dynamic body id.
virtual SoftBodyContactState probeSoftBodyParticle(float x, float y, float z, float radius, SoftBodyContact &contact) const =0
Probe the deepest non-sensor contact for a spherical particle.
virtual bool softBodyCollisionAvailable() const noexcept=0
Whether the provider can currently answer contacts.
static eve::Result< SchemaRegistrationStatus > registerVersioned(const SchemaDefinition &definition)
Registers a new exact (id, version) entry without replacing it.
static const SchemaDefinition * resolve(const std::string &schemaId, int schemaVersion)
Resolves one exact (schemaId, schemaVersion) pair, or nullptr.
const Value * field(const Value::Object &object, std::string_view name)
Borrow an optional field only during the current synchronous codec call. @ownership Object owns the r...
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
SoftBodySurfaceSampling
SoftBodySurfaceSampling public API.
SoftBodyVolumeSampling
SoftBodyVolumeSampling public API.
float distanceSquared(float ax, float ay, float bx, float by)
ValueType
JSON-compatible value kinds understood by a schema field.
Definition SchemaTypes.h:16
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Duration delta
Fixed simulation duration for this step.
Definition Time.h:162
Owned field definition; insertion order determines floating-point accumulation order.
Definition FieldSet.h:14
Observable backend progress shared by CPU and accelerator providers.
Validated solver policy for one simulation step.
Versioned, owning creation definition for one volumetric soft body.
static eve::Result< void > ensureSchemaRegistered()
Idempotently register version 1 in the process schema registry.
Versioned authoring recipe used to cook a mesh-backed SoftBodyModel.
static eve::Result< void > ensureSchemaRegistered()
Idempotently register version 1 in the process schema registry.
eve::Result< void > validate() const
Validate the complete immutable cooking recipe.
static constexpr std::string_view SchemaId
static eve::schema::SchemaDefinition schemaDefinition()
Return the registry schema for tooling and generic JSON validation.
static eve::Result< SoftBodyModelDefinition > fromValue(const eve::Value &value)
Decode version 1 transactionally and reject unknown fields.
eve::Result< eve::Value > toValue() const
Encode every version-1 field into an owning persistent value.
static constexpr std::uint32_t SchemaVersion
eve::Result< void > validate() const
Validate all finite values, topology indices, bindings and clusters.
std::vector< std::uint32_t > surfaceIndices
std::vector< SoftBodyModelCluster > clusters
std::vector< SoftBodyModelParticle > particles
std::vector< SoftBodyModelSurfaceBinding > surfaceBindings
Metadata and validation constraints for one object member.
Definition SchemaTypes.h:77
Versioned runtime schema for a JSON object.
Definition SchemaTypes.h:93
std::vector< FieldDefinition > fields
Definition SchemaTypes.h:99