载入中...
搜索中...
未找到
Shape3D.cpp
浏览该文件的文档.
1#include "physics/Shape3D.h"
2#include "common/Assert.h"
3#include "physics/Body3D.h"
4#include "physics/World3D.h"
5
6#include "common/Exception.h"
7
8
9#include <cstdint>
10#include <cmath>
11#include <utility>
12
13namespace eve::physics {
14namespace {
15
16constexpr uint64_t materialIdMask = 0xFFFFFFFFull;
17constexpr int frictionModeShift = 32;
18constexpr int restitutionModeShift = 35;
19constexpr uint64_t combineModeMask = 0x7ull;
20
21uint64_t parseCombineMode(const std::string &mode, const char *operation) {
22 if (mode == "default") return 0;
23 if (mode == "average") return 1;
24 if (mode == "minimum" || mode == "min") return 2;
25 if (mode == "multiply") return 3;
26 if (mode == "maximum" || mode == "max") return 4;
27 throw eve::Exception("%s: mode must be default|average|minimum|multiply|maximum",
28 operation);
29}
30
31std::string combineModeName(uint64_t mode) {
32 switch (mode) {
33 case 0: return "default";
34 case 1: return "average";
35 case 2: return "minimum";
36 case 3: return "multiply";
37 case 4: return "maximum";
38 default: return "default";
39 }
40}
41
42template <class T>
43T shapeValue(eve::Result<T> result) {
44 if (!result.ok()) throw eve::Exception("%s", result.error()->message().c_str());
45 return std::move(result).value();
46}
47void shapeValue(eve::Result<void> result) {
48 if (!result.ok()) throw eve::Exception("%s", result.error()->message().c_str());
49}
50} // namespace
51
52Shape3D::Shape3D(World3D *world, Body3D *body, std::unique_ptr<IShapeBackend3D> backend,
54 : world_(world),
55 body_(body),
56 backend_(std::move(backend)),
57 runtimeHandle_(runtimeHandle),
58 geometry_(std::move(geometry)),
59 id_(world ? world->nextShapeId() : 0) {
60 EV_PARAM_CHECK(backend_ != nullptr, "Shape3D requires a backend");
61 backend_->bindOwner(*this);
62 if (geometry_.kind == Kind::TriangleMesh) {
63 const int count = shapeValue(backend_->meshMaterialCount());
64 for (int i = 0; i < count; ++i) meshMaterials_.push_back(shapeValue(backend_->meshMaterial(i)));
65 }
66 if (world_) world_->registerShapeHandle(this);
67}
69bool Shape3D::isValid() const { return backend_ && backend_->isValid(); }
71 if (backend_) backend_->invalidate();
72 if (world_) world_->forgetShape(this);
73 body_ = nullptr;
74 world_ = nullptr;
75 runtimeHandle_ = PhysicsShapeHandle::invalid();
76}
78 if (backend_) backend_->destroy();
79 invalidate();
80}
81void Shape3D::rebuildGeometry(const ShapeGeometry3D &geometry, bool sensor) {
82 if (!body_ || !body_->isValid()) throw eve::Exception("Shape3D: cannot rebuild geometry after body destruction");
83 if (geometry.kind == Kind::TriangleMesh && isValid() && !meshMaterialsDirty_) {
84 const int count = shapeValue(backend_->meshMaterialCount());
85 std::vector<SurfaceMaterial3D> refreshed;
86 refreshed.reserve(static_cast<size_t>(count));
87 for (int i = 0; i < count; ++i) refreshed.push_back(shapeValue(backend_->meshMaterial(i)));
88 meshMaterials_ = std::move(refreshed);
89 }
90 shapeValue(backend_->rebuild(
91 geometry, {sensor, hitEventsEnabled_, oneWayEnabled_, contactOverrideFiltering_, explosionScale_},
92 meshMaterials_));
93 meshMaterialsDirty_ = false;
94 if (world_) world_->registerShapeHandle(this);
95}
96void Shape3D::recreate(bool sensor) { rebuildGeometry(geometry_, sensor); }
97void Shape3D::applyGeometry(ShapeGeometry3D geometry, bool sensor) {
98 rebuildGeometry(geometry, sensor);
99 geometry_ = std::move(geometry);
100}
101
102void Shape3D::setSensor(bool sensor) {
103 if (!body_ || !body_->isValid()) return;
104 if (isValid() && shapeValue(backend_->isSensor()) == sensor) return;
105 recreate(sensor);
106}
107
108void Shape3D::enableContactOverrideFiltering() {
109 if (contactOverrideFiltering_) return;
110 const bool sensor = isSensor();
111 contactOverrideFiltering_ = true;
112 try {
113 recreate(sensor);
114 } catch (...) {
115 contactOverrideFiltering_ = false;
116 throw;
117 }
118}
119
121 tag_ = tag;
122 if (world_) world_->updateShapeTag(this);
123}
124
126 if (isValid()) shapeValue(backend_->enableHitEvents(enabled && !isSensor()));
127 hitEventsEnabled_ = enabled;
128}
129
131 return hitEventsEnabled_;
132}
133
134void Shape3D::setOneWay(float nx, float ny, float nz, float planeOffset, float margin,
135 float minNormalDot) {
136 if (!std::isfinite(nx) || !std::isfinite(ny) || !std::isfinite(nz) ||
137 !std::isfinite(planeOffset) || !std::isfinite(margin) ||
138 !std::isfinite(minNormalDot))
139 throw eve::Exception("Shape3D.setOneWay: all values must be finite");
140 const float lengthSquared = nx * nx + ny * ny + nz * nz;
141 if (!(lengthSquared > 1e-12f))
142 throw eve::Exception("Shape3D.setOneWay: normal must be non-zero");
143 if (margin < 0.f)
144 throw eve::Exception("Shape3D.setOneWay: margin must be >= 0");
145 if (minNormalDot < -1.f || minNormalDot > 1.f)
146 throw eve::Exception("Shape3D.setOneWay: minNormalDot must be in [-1,1]");
147 if (isValid()) shapeValue(backend_->enablePreSolveEvents(!isSensor()));
148 const float inverseLength = 1.f / std::sqrt(lengthSquared);
149 oneWayLocalNormalX_ = nx * inverseLength;
150 oneWayLocalNormalY_ = ny * inverseLength;
151 oneWayLocalNormalZ_ = nz * inverseLength;
152 oneWayPlaneOffset_ = planeOffset;
153 oneWayMargin_ = margin;
154 oneWayMinNormalDot_ = minNormalDot;
155 oneWayEnabled_ = true;
156}
157
159 if (isValid()) shapeValue(backend_->enablePreSolveEvents(false));
160 oneWayEnabled_ = false;
161}
162
163void Shape3D::refreshOneWayWorldData() {
164 if (!oneWayEnabled_ || !body_ || !body_->isValid()) return;
165 const auto plane = shapeValue(backend_->oneWayPlane(
166 geometry_, {oneWayLocalNormalX_, oneWayLocalNormalY_, oneWayLocalNormalZ_}, oneWayPlaneOffset_));
167 oneWayWorldPointX_ = plane.x;
168 oneWayWorldPointY_ = plane.y;
169 oneWayWorldPointZ_ = plane.z;
170 oneWayWorldNormalX_ = plane.nx;
171 oneWayWorldNormalY_ = plane.ny;
172 oneWayWorldNormalZ_ = plane.nz;
173}
174
175bool Shape3D::allowsOneWayContact(double pointX, double pointY, double pointZ, float normalX,
176 float normalY, float normalZ) const {
177 if (!oneWayEnabled_) return true;
178 const double side = (pointX - oneWayWorldPointX_) * oneWayWorldNormalX_ +
179 (pointY - oneWayWorldPointY_) * oneWayWorldNormalY_ +
180 (pointZ - oneWayWorldPointZ_) * oneWayWorldNormalZ_;
181 const float alignment = normalX * oneWayWorldNormalX_ + normalY * oneWayWorldNormalY_ +
182 normalZ * oneWayWorldNormalZ_;
183 return side >= -static_cast<double>(oneWayMargin_) && alignment >= oneWayMinNormalDot_;
184}
185
186std::string Shape3D::getKind() const {
187 switch (geometry_.kind) {
188 case Kind::Box: return "box";
189 case Kind::Sphere: return "sphere";
190 case Kind::Capsule: return "capsule";
191 case Kind::ConvexHull: return "convexHull";
192 case Kind::TriangleMesh: return "triangleMesh";
193 case Kind::HeightField: return "heightField";
194 }
195 return "box";
196}
197
198void Shape3D::setBoxSize(float width, float height, float depth) {
199 if (geometry_.kind != Kind::Box) throw eve::Exception("Shape3D.setBoxSize: shape is not a box");
200 if (!(width > 0.f) || !(height > 0.f) || !(depth > 0.f) || !std::isfinite(width) ||
201 !std::isfinite(height) || !std::isfinite(depth))
202 throw eve::Exception("Shape3D.setBoxSize: dimensions must be finite and > 0");
203 if (!body_ || !body_->isValid())
204 throw eve::Exception("Shape3D.setBoxSize: body destroyed");
205 const float halfWidth = 0.5f * width;
206 const float halfHeight = 0.5f * height;
207 const float halfDepth = 0.5f * depth;
208 if (geometry_.a == halfWidth && geometry_.b == halfHeight && geometry_.c == halfDepth) return;
209 const bool sensor = isSensor();
210 auto candidate = geometry_;
211 candidate.a = halfWidth;
212 candidate.b = halfHeight;
213 candidate.c = halfDepth;
214 applyGeometry(std::move(candidate), sensor);
215}
216
218 if (geometry_.kind != Kind::Sphere) throw eve::Exception("Shape3D.setSphereRadius: shape is not a sphere");
219 if (!(radius > 0.f) || !std::isfinite(radius))
220 throw eve::Exception("Shape3D.setSphereRadius: radius must be finite and > 0");
221 if (!body_ || !body_->isValid())
222 throw eve::Exception("Shape3D.setSphereRadius: body destroyed");
223 if (geometry_.a == radius) return;
224 const bool sensor = isSensor();
225 auto candidate = geometry_;
226 candidate.a = radius;
227 applyGeometry(std::move(candidate), sensor);
228}
229
231 if (geometry_.kind != Kind::Capsule) throw eve::Exception("Shape3D.setCapsuleSize: shape is not a capsule");
232 if (!(height >= 0.f) || !(radius > 0.f) || !std::isfinite(height) ||
233 !std::isfinite(radius))
234 throw eve::Exception(
235 "Shape3D.setCapsuleSize: height must be finite and >= 0; radius finite and > 0");
236 if (!body_ || !body_->isValid())
237 throw eve::Exception("Shape3D.setCapsuleSize: body destroyed");
238 const float halfHeight = 0.5f * height;
239 if (geometry_.a == halfHeight && geometry_.b == radius) return;
240 const bool sensor = isSensor();
241 auto candidate = geometry_;
242 candidate.a = halfHeight;
243 candidate.b = radius;
244 applyGeometry(std::move(candidate), sensor);
245}
246
247void Shape3D::setConvexHullVertices(const std::vector<float> &vertices, int maxVertices) {
248 if (geometry_.kind != Kind::ConvexHull)
249 throw eve::Exception("Shape3D.setConvexHullVertices: shape is not a convex hull");
250 if (!body_ || !body_->isValid())
251 throw eve::Exception("Shape3D.setConvexHullVertices: body destroyed");
252 if (vertices == geometry_.hullVertices && maxVertices == geometry_.hullMaxVertices) return;
253 const bool sensor = isSensor();
254 auto candidate = geometry_;
255 candidate.hullVertices = vertices;
256 candidate.hullMaxVertices = maxVertices;
257 applyGeometry(std::move(candidate), sensor);
258}
259
260void Shape3D::setTriangleMeshData(const std::vector<float> &vertices,
261 const std::vector<int32_t> &indices, bool weldVertices,
262 float weldTolerance, bool identifyEdges,
263 bool useMedianSplit) {
264 if (geometry_.kind != Kind::TriangleMesh)
265 throw eve::Exception("Shape3D.setTriangleMeshData: shape is not a triangle mesh");
266 if (!body_ || !body_->isValid())
267 throw eve::Exception("Shape3D.setTriangleMeshData: body destroyed");
268 if (body_->getType() != "static")
269 throw eve::Exception("Shape3D.setTriangleMeshData: triangle meshes require a static body");
270 if (vertices == geometry_.meshVertices && indices == geometry_.meshIndices &&
271 weldVertices == geometry_.meshWeldVertices && weldTolerance == geometry_.meshWeldTolerance &&
272 identifyEdges == geometry_.meshIdentifyEdges && useMedianSplit == geometry_.meshUseMedianSplit)
273 return;
274 const bool sensor = isSensor();
275 auto candidate = geometry_;
276 candidate.meshVertices = vertices;
277 candidate.meshIndices = indices;
278 candidate.meshWeldVertices = weldVertices;
279 candidate.meshWeldTolerance = weldTolerance;
280 candidate.meshIdentifyEdges = identifyEdges;
281 candidate.meshUseMedianSplit = useMedianSplit;
282 const auto previousMaterials = meshMaterials_;
283 const bool previousDirty = meshMaterialsDirty_;
284 if (candidate.meshMaterialIndices.size() != indices.size() / 3) {
285 candidate.meshMaterialIndices.clear();
286 if (meshMaterials_.size() > 1) meshMaterials_.resize(1);
287 meshMaterialsDirty_ = true;
288 }
289 try {
290 applyGeometry(std::move(candidate), sensor);
291 } catch (...) {
292 meshMaterials_ = previousMaterials;
293 meshMaterialsDirty_ = previousDirty;
294 throw;
295 }
296}
297
299 const std::vector<int32_t> &materialIndices) {
300 if (geometry_.kind != Kind::TriangleMesh)
301 throw eve::Exception(
302 "Shape3D.setTriangleMeshMaterialIndices: shape is not a triangle mesh");
303 const size_t triangleCount = geometry_.meshIndices.size() / 3;
304 if (materialIndices.size() != triangleCount)
305 throw eve::Exception(
306 "Shape3D.setTriangleMeshMaterialIndices: one index is required per triangle");
307 std::vector<uint8_t> encoded;
308 encoded.reserve(materialIndices.size());
309 int requiredCount = 1;
310 for (int32_t index : materialIndices) {
311 if (index < 0 || index > 254)
312 throw eve::Exception(
313 "Shape3D.setTriangleMeshMaterialIndices: indices must be in [0, 254]");
314 encoded.push_back(static_cast<uint8_t>(index));
315 requiredCount = std::max(requiredCount, static_cast<int>(index) + 1);
316 }
317 if (encoded == geometry_.meshMaterialIndices && requiredCount == static_cast<int>(meshMaterials_.size())) return;
318 const bool sensor = isSensor();
319 const auto oldIndices = geometry_.meshMaterialIndices;
320 const auto oldMaterials = meshMaterials_;
321 geometry_.meshMaterialIndices = std::move(encoded);
322 if (meshMaterials_.empty()) meshMaterials_.push_back(SurfaceMaterial3D{});
323 meshMaterials_.resize(static_cast<size_t>(requiredCount), meshMaterials_.front());
324 meshMaterialsDirty_ = true;
325 try {
326 recreate(sensor);
327 } catch (...) {
328 geometry_.meshMaterialIndices = oldIndices;
329 meshMaterials_ = oldMaterials;
330 meshMaterialsDirty_ = false;
331 throw;
332 }
333}
334
335int Shape3D::getTriangleMeshMaterialIndex(int triangleIndex) const {
336 if (geometry_.kind != Kind::TriangleMesh)
337 throw eve::Exception(
338 "Shape3D.getTriangleMeshMaterialIndex: shape is not a triangle mesh");
339 const int triangleCount = static_cast<int>(geometry_.meshIndices.size() / 3);
340 if (triangleIndex < 0 || triangleIndex >= triangleCount)
341 throw eve::Exception("Shape3D.getTriangleMeshMaterialIndex: triangle out of range");
342 return geometry_.meshMaterialIndices.empty() ? 0
343 : geometry_.meshMaterialIndices[static_cast<size_t>(triangleIndex)];
344}
345
347 return geometry_.kind == Kind::TriangleMesh ? std::max(1, static_cast<int>(meshMaterials_.size())) : 0;
348}
349
351 float rollingResistance, float tangentX,
352 float tangentY, float tangentZ, int materialId,
353 const std::string &frictionMode,
354 const std::string &restitutionMode) {
355 if (geometry_.kind != Kind::TriangleMesh)
356 throw eve::Exception("Shape3D.setTriangleMeshMaterial: shape is not a triangle mesh");
357 if (slot < 0 || slot >= getTriangleMeshMaterialCount())
358 throw eve::Exception("Shape3D.setTriangleMeshMaterial: slot out of range");
359 if (!std::isfinite(friction) || friction < 0.f || !std::isfinite(restitution) ||
360 restitution < 0.f || !std::isfinite(rollingResistance) || rollingResistance < 0.f ||
361 !std::isfinite(tangentX) || !std::isfinite(tangentY) || !std::isfinite(tangentZ))
362 throw eve::Exception(
363 "Shape3D.setTriangleMeshMaterial: numeric values must be finite and non-negative where required");
364 const uint64_t frictionCode =
365 parseCombineMode(frictionMode, "Shape3D.setTriangleMeshMaterial");
366 const uint64_t restitutionCode =
367 parseCombineMode(restitutionMode, "Shape3D.setTriangleMeshMaterial");
370 material.restitution = restitution;
371 material.rollingResistance = rollingResistance;
372 material.tangentVelocity = {tangentX, tangentY, tangentZ};
373 material.userMaterialId = static_cast<uint32_t>(materialId) |
374 (frictionCode << frictionModeShift) |
375 (restitutionCode << restitutionModeShift);
376 if (meshMaterials_.empty()) meshMaterials_.push_back(SurfaceMaterial3D{});
377 if (isValid()) shapeValue(backend_->setMeshMaterial(material, slot));
378 meshMaterials_[static_cast<size_t>(slot)] = material;
379}
380
381float Shape3D::getTriangleMeshMaterialFriction(int slot) const {
382 if (geometry_.kind != Kind::TriangleMesh || slot < 0 || slot >= getTriangleMeshMaterialCount())
383 throw eve::Exception("Shape3D.getTriangleMeshMaterialFriction: slot out of range");
384 return meshMaterials_.empty() ? getFriction() : meshMaterials_[static_cast<size_t>(slot)].friction;
385}
386
387float Shape3D::getTriangleMeshMaterialRestitution(int slot) const {
388 if (geometry_.kind != Kind::TriangleMesh || slot < 0 || slot >= getTriangleMeshMaterialCount())
389 throw eve::Exception("Shape3D.getTriangleMeshMaterialRestitution: slot out of range");
390 return meshMaterials_.empty() ? getRestitution() : meshMaterials_[static_cast<size_t>(slot)].restitution;
391}
392
393float Shape3D::getTriangleMeshMaterialRollingResistance(int slot) const {
394 if (geometry_.kind != Kind::TriangleMesh || slot < 0 || slot >= getTriangleMeshMaterialCount())
395 throw eve::Exception(
396 "Shape3D.getTriangleMeshMaterialRollingResistance: slot out of range");
397 return meshMaterials_.empty() ? getRollingResistance()
398 : meshMaterials_[static_cast<size_t>(slot)].rollingResistance;
399}
400
401int Shape3D::getTriangleMeshMaterialId(int slot) const {
402 if (geometry_.kind != Kind::TriangleMesh || slot < 0 || slot >= getTriangleMeshMaterialCount())
403 throw eve::Exception("Shape3D.getTriangleMeshMaterialId: slot out of range");
404 const uint64_t id = meshMaterials_.empty() ? shapeValue(backend_->material()).userMaterialId
405 : meshMaterials_[static_cast<size_t>(slot)].userMaterialId;
406 return static_cast<int>(static_cast<uint32_t>(id));
407}
408
409void Shape3D::setHeightFieldHeights(const std::vector<float> &heights) {
410 if (geometry_.kind != Kind::HeightField)
411 throw eve::Exception("Shape3D.setHeightFieldHeights: shape is not a height field");
412 if (!body_ || !body_->isValid())
413 throw eve::Exception("Shape3D.setHeightFieldHeights: body destroyed");
414 if (heights == geometry_.heightValues) return;
415 const bool sensor = isSensor();
416 auto candidate = geometry_;
417 candidate.heightValues = heights;
418 applyGeometry(std::move(candidate), sensor);
419}
420
421void Shape3D::setHeightFieldRegion(int x, int z, int width, int depth,
422 const std::vector<float> &heights) {
423 if (geometry_.kind != Kind::HeightField)
424 throw eve::Exception("Shape3D.setHeightFieldRegion: shape is not a height field");
425 if (x < 0 || z < 0 || width < 1 || depth < 1 || x > geometry_.heightCountX - width ||
426 z > geometry_.heightCountZ - depth)
427 throw eve::Exception("Shape3D.setHeightFieldRegion: region is outside the sample grid");
428 if (heights.size() != static_cast<size_t>(width) * static_cast<size_t>(depth))
429 throw eve::Exception("Shape3D.setHeightFieldRegion: data size must equal width * depth");
430 std::vector<float> updated = geometry_.heightValues;
431 for (int row = 0; row < depth; ++row) {
432 for (int column = 0; column < width; ++column) {
433 updated[static_cast<size_t>(z + row) * static_cast<size_t>(geometry_.heightCountX) +
434 static_cast<size_t>(x + column)] =
435 heights[static_cast<size_t>(row) * static_cast<size_t>(width) + static_cast<size_t>(column)];
436 }
437 }
438 setHeightFieldHeights(updated);
439}
440
441float Shape3D::getHeightFieldHeight(int x, int z) const {
442 if (geometry_.kind != Kind::HeightField)
443 throw eve::Exception("Shape3D.getHeightFieldHeight: shape is not a height field");
444 if (x < 0 || x >= geometry_.heightCountX || z < 0 || z >= geometry_.heightCountZ)
445 throw eve::Exception("Shape3D.getHeightFieldHeight: sample index out of range");
446 return geometry_
447 .heightValues[static_cast<size_t>(z) * static_cast<size_t>(geometry_.heightCountX) + static_cast<size_t>(x)];
448}
449
450void Shape3D::setLocalTransform(float px, float py, float pz, float qx, float qy, float qz,
451 float qw) {
452 if (!body_ || !body_->isValid())
453 throw eve::Exception("Shape3D.setLocalTransform: body destroyed");
454 if (!std::isfinite(px) || !std::isfinite(py) || !std::isfinite(pz) ||
455 !std::isfinite(qx) || !std::isfinite(qy) || !std::isfinite(qz) ||
456 !std::isfinite(qw))
457 throw eve::Exception("Shape3D.setLocalTransform: values must be finite");
458 const float lengthSquared = qx * qx + qy * qy + qz * qz + qw * qw;
459 if (!(lengthSquared > 1e-12f))
460 throw eve::Exception("Shape3D.setLocalTransform: quaternion must be non-zero");
461 const float inverseLength = 1.f / std::sqrt(lengthSquared);
462 const float normalizedQx = qx * inverseLength;
463 const float normalizedQy = qy * inverseLength;
464 const float normalizedQz = qz * inverseLength;
465 const float normalizedQw = qw * inverseLength;
466 if (geometry_.kind == Kind::HeightField && (px != 0.f || py != 0.f || pz != 0.f || normalizedQx != 0.f ||
467 normalizedQy != 0.f || normalizedQz != 0.f || normalizedQw != 1.f))
468 throw eve::Exception(
469 "Shape3D.setLocalTransform: height fields use their Body transform and require an identity local transform");
470 if (geometry_.localX == px && geometry_.localY == py && geometry_.localZ == pz &&
471 geometry_.localQx == normalizedQx && geometry_.localQy == normalizedQy && geometry_.localQz == normalizedQz &&
472 geometry_.localQw == normalizedQw)
473 return;
474
475 const bool sensor = isSensor();
476 auto candidate = geometry_;
477 candidate.localX = px;
478 candidate.localY = py;
479 candidate.localZ = pz;
480 candidate.localQx = normalizedQx;
481 candidate.localQy = normalizedQy;
482 candidate.localQz = normalizedQz;
483 candidate.localQw = normalizedQw;
484 applyGeometry(std::move(candidate), sensor);
485}
486
487void Shape3D::setLocalPosition(float x, float y, float z) {
488 setLocalTransform(x, y, z, geometry_.localQx, geometry_.localQy, geometry_.localQz, geometry_.localQw);
489}
490
491void Shape3D::setLocalRotation(float qx, float qy, float qz, float qw) {
492 setLocalTransform(geometry_.localX, geometry_.localY, geometry_.localZ, qx, qy, qz, qw);
493}
494
495bool Shape3D::isSensor() const { return isValid() ? shapeValue(backend_->isSensor()) : false; }
496
497void Shape3D::setFriction(float friction) {
498 if (!std::isfinite(friction) || friction < 0.f)
499 throw eve::Exception("Shape3D.setFriction: friction must be finite and >= 0");
500 if (!isValid()) return;
501 shapeValue(backend_->setFriction(friction));
502}
503
504float Shape3D::getFriction() const { return isValid() ? shapeValue(backend_->friction()) : 0.f; }
505
506void Shape3D::setRestitution(float restitution) {
507 if (!std::isfinite(restitution) || restitution < 0.f)
508 throw eve::Exception("Shape3D.setRestitution: restitution must be finite and >= 0");
509 if (!isValid()) return;
510 shapeValue(backend_->setRestitution(restitution));
511}
512
513float Shape3D::getRestitution() const { return isValid() ? shapeValue(backend_->restitution()) : 0.f; }
514
515void Shape3D::setRollingResistance(float resistance) {
516 if (!std::isfinite(resistance) || resistance < 0.f)
517 throw eve::Exception(
518 "Shape3D.setRollingResistance: resistance must be finite and >= 0");
519 if (!isValid()) return;
520 SurfaceMaterial3D material = shapeValue(backend_->material());
521 material.rollingResistance = resistance;
522 shapeValue(backend_->setMaterial(material));
523}
524
525float Shape3D::getRollingResistance() const {
526 return isValid() ? shapeValue(backend_->material()).rollingResistance : 0.f;
527}
528
529void Shape3D::setTangentVelocity(float x, float y, float z) {
530 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
531 throw eve::Exception("Shape3D.setTangentVelocity: components must be finite");
532 if (!isValid()) return;
533 SurfaceMaterial3D material = shapeValue(backend_->material());
534 material.tangentVelocity = PhysicsVector3D{x, y, z};
535 shapeValue(backend_->setMaterial(material));
536}
537
538float Shape3D::getTangentVelocityX() const {
539 return isValid() ? shapeValue(backend_->material()).tangentVelocity.x : 0.f;
540}
541
542float Shape3D::getTangentVelocityY() const {
543 return isValid() ? shapeValue(backend_->material()).tangentVelocity.y : 0.f;
544}
545
546float Shape3D::getTangentVelocityZ() const {
547 return isValid() ? shapeValue(backend_->material()).tangentVelocity.z : 0.f;
548}
549
550void Shape3D::setMaterialId(int id) {
551 if (!isValid()) return;
552 SurfaceMaterial3D material = shapeValue(backend_->material());
553 material.userMaterialId =
554 (material.userMaterialId & ~materialIdMask) | static_cast<uint32_t>(id);
555 shapeValue(backend_->setMaterial(material));
556}
557
558void Shape3D::setFrictionCombineMode(const std::string &mode) {
559 const uint64_t encoded = parseCombineMode(mode, "Shape3D.setFrictionCombineMode");
560 if (!isValid()) return;
561 SurfaceMaterial3D material = shapeValue(backend_->material());
562 material.userMaterialId &= ~(combineModeMask << frictionModeShift);
563 material.userMaterialId |= encoded << frictionModeShift;
564 shapeValue(backend_->setMaterial(material));
565}
566
567std::string Shape3D::getFrictionCombineMode() const {
568 if (!isValid()) return "default";
569 return combineModeName((shapeValue(backend_->material()).userMaterialId >> frictionModeShift) & combineModeMask);
570}
571
572void Shape3D::setRestitutionCombineMode(const std::string &mode) {
573 const uint64_t encoded = parseCombineMode(mode, "Shape3D.setRestitutionCombineMode");
574 if (!isValid()) return;
575 SurfaceMaterial3D material = shapeValue(backend_->material());
576 material.userMaterialId &= ~(combineModeMask << restitutionModeShift);
577 material.userMaterialId |= encoded << restitutionModeShift;
578 shapeValue(backend_->setMaterial(material));
579}
580
581std::string Shape3D::getRestitutionCombineMode() const {
582 if (!isValid()) return "default";
583 return combineModeName((shapeValue(backend_->material()).userMaterialId >> restitutionModeShift) & combineModeMask);
584}
585
586int Shape3D::getMaterialId() const {
587 return isValid() ? static_cast<int>(static_cast<uint32_t>(shapeValue(backend_->material()).userMaterialId)) : 0;
588}
589
590void Shape3D::setExplosionScale(float scale) {
591 if (!std::isfinite(scale) || scale < 0.f)
592 throw eve::Exception("Shape3D.setExplosionScale: scale must be finite and >= 0");
593 if (scale == explosionScale_) return;
594 const float previous = explosionScale_;
595 explosionScale_ = scale;
596 try {
597 if (body_ && body_->isValid()) recreate(isSensor());
598 } catch (...) {
599 explosionScale_ = previous;
600 throw;
601 }
602}
603
604void Shape3D::setDensity(float density) {
605 if (!std::isfinite(density) || density < 0.f)
606 throw eve::Exception("Shape3D.setDensity: density must be finite and >= 0");
607 if (!isValid()) return;
608 shapeValue(backend_->setDensity(density, true));
609}
610
611float Shape3D::getDensity() const { return isValid() ? shapeValue(backend_->density()) : 0.f; }
612
613void Shape3D::setFilterBits(uint64_t categoryBits, uint64_t maskBits) {
614 if (!isValid()) return;
615 ShapeFilter3D filter = shapeValue(backend_->filter());
616 filter.categoryBits = categoryBits;
617 filter.maskBits = maskBits;
618 shapeValue(backend_->setFilter(filter, false));
619}
620
621uint64_t Shape3D::getCategoryBits() const { return isValid() ? shapeValue(backend_->filter()).categoryBits : 0; }
622
623void Shape3D::setCategoryBits(uint64_t bits) {
624 if (!isValid()) return;
625 ShapeFilter3D filter = shapeValue(backend_->filter());
626 filter.categoryBits = bits;
627 shapeValue(backend_->setFilter(filter, true));
628}
629
630void Shape3D::setMaskBits(uint64_t bits) {
631 if (!isValid()) return;
632 ShapeFilter3D filter = shapeValue(backend_->filter());
633 filter.maskBits = bits;
634 shapeValue(backend_->setFilter(filter, true));
635}
636
637uint64_t Shape3D::getMaskBits() const { return isValid() ? shapeValue(backend_->filter()).maskBits : 0; }
638
639void Shape3D::setGroupIndex(int index) {
640 if (!isValid()) return;
641 ShapeFilter3D filter = shapeValue(backend_->filter());
642 filter.groupIndex = index;
643 shapeValue(backend_->setFilter(filter, true));
644}
645
646int Shape3D::getGroupIndex() const { return isValid() ? shapeValue(backend_->filter()).groupIndex : 0; }
647
648bool Shape3D::testPoint(float x, float y, float z) const {
649 if (!isValid() || !body_ || !body_->isValid()) return false;
650 return shapeValue(backend_->testPoint(x, y, z));
651}
652
653} // namespace eve::physics
double z
double y
double x
ActionParameterOperation operation
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
Definition Assert.h:30
float rollingResistance
float friction
float density
std::vector< std::uint32_t > indices
float halfWidth
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
std::array< float, 3 > scale
std::string id
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
const std::string * tag
OceanRenderBackend backend
std::shared_ptr< const OceanSprayFrame > previous
glm::dvec3 tangentZ
glm::dvec3 tangentX
std::array< uint32_t, 16 > material
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
std::string body
std::string slot
std::string filter
std::string geometry
unsigned column
double restitution
int count
std::array< double, 2 > vertices[3]
int margin
std::uint32_t depth
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
static constexpr RuntimeHandle invalid() noexcept
Returns the canonical invalid handle.
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
bool isValid() const
True while the underlying Box3D body is still alive.
Definition Body3D.cpp:57
std::string getType() const
Returns the type.
Definition Body3D.cpp:396
void invalidate()
Internal: marks the wrapper invalid after destruction.
Definition Shape3D.cpp:70
void setTag(int tag)
User-defined integer tag preserved for the wrapper lifetime.
Definition Shape3D.cpp:120
void setBoxSize(float width, float height, float depth)
Atomically changes full box dimensions in meters.
Definition Shape3D.cpp:198
void setOneWay(float nx, float ny, float nz, float planeOffset, float margin, float minNormalDot)
Enables a one-way collision plane in shape-local space.
Definition Shape3D.cpp:134
void setTriangleMeshData(const std::vector< float > &vertices, const std::vector< int32_t > &indices, bool weldVertices=true, float weldTolerance=0.001f, bool identifyEdges=true, bool useMedianSplit=false)
Atomically replaces static triangle-mesh source data and rebuilds its BVH.
Definition Shape3D.cpp:260
std::string getKind() const
Kind name including primitives, "convexHull", "triangleMesh", or "heightField".
Definition Shape3D.cpp:186
void setHitEventsEnabled(bool enabled)
Enables significant collision hit events for this shape.
Definition Shape3D.cpp:125
int getTriangleMeshMaterialIndex(int triangleIndex) const
Material-slot index assigned to a source triangle.
Definition Shape3D.cpp:335
void setTriangleMeshMaterialIndices(const std::vector< int32_t > &materialIndices)
Atomically assigns one material-slot index per source mesh triangle.
Definition Shape3D.cpp:298
void setTriangleMeshMaterial(int slot, float friction, float restitution, float rollingResistance, float tangentX, float tangentY, float tangentZ, int materialId, const std::string &frictionMode, const std::string &restitutionMode)
Replaces one triangle-mesh material slot without rebuilding geometry.
Definition Shape3D.cpp:350
int getTriangleMeshMaterialCount() const
Number of material slots on a triangle mesh, otherwise zero.
Definition Shape3D.cpp:346
bool isSensor() const
Definition Shape3D.cpp:495
void setSphereRadius(float radius)
Atomically changes sphere radius in meters.
Definition Shape3D.cpp:217
bool isValid() const
Native shape liveness through the selected backend.
Definition Shape3D.cpp:69
void destroy()
Destroys the shape inside its world.
Definition Shape3D.cpp:77
Shape3D(World3D *world, Body3D *body, std::unique_ptr< IShapeBackend3D > backend, PhysicsShapeHandle runtimeHandle, ShapeGeometry3D geometry)
Internal owning constructor used by Body3D shape creation; backend and geometry are consumed.
Definition Shape3D.cpp:52
void setCapsuleSize(float height, float radius)
Atomically changes capsule segment height and radius in meters.
Definition Shape3D.cpp:230
void setConvexHullVertices(const std::vector< float > &vertices, int maxVertices=64)
Atomically rebuilds a convex hull from packed local XYZ vertices.
Definition Shape3D.cpp:247
void disableOneWay()
Disables one-way filtering and restores ordinary two-sided collision.
Definition Shape3D.cpp:158
void setSensor(bool sensor)
Sensor shapes report contacts but never collide.
Definition Shape3D.cpp:102
bool areHitEventsEnabled() const
Whether significant collision hit events are enabled.
Definition Shape3D.cpp:130
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
void updateShapeTag(Shape3D *shape)
Internal: refreshes the tag snapshot for a live shape handle.
Definition World3D.cpp:554
void registerShapeHandle(Shape3D *shape)
Internal: snapshots a backend handle for destruction-safe end events.
Definition World3D.cpp:527
void forgetShape(Shape3D *shape)
Definition World3D.cpp:507
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
bool enabled
Allocation-free owning three-dimensional physics value.
Definition RigidTypes3D.h:4
Collision filter; negative groups never collide, positive groups always collide.
Owning, backend-independent shape source; metres, local quaternion XYZW.
std::vector< int32_t > meshIndices
std::vector< uint8_t > meshMaterialIndices
std::vector< float > meshVertices
std::vector< float > hullVertices
Owning surface values; userMaterialId contains the engine material ID and combine policy encoding.