载入中...
搜索中...
未找到
Box3DShape.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3#include <cmath>
4#include "common/Exception.h"
5#include "physics/Shape3D.h"
8namespace eve::physics::box3d {
9namespace {
10b3SurfaceMaterial nativeMaterial(SurfaceMaterial3D value) {
11 auto material = b3DefaultSurfaceMaterial();
12 material.friction = value.friction;
13 material.restitution = value.restitution;
14 material.rollingResistance = value.rollingResistance;
15 material.tangentVelocity = {value.tangentVelocity.x, value.tangentVelocity.y, value.tangentVelocity.z};
16 material.userMaterialId = value.userMaterialId;
17 material.customColor = value.customColor;
18 return material;
19}
20SurfaceMaterial3D materialValue(b3SurfaceMaterial value) {
21 return {value.friction, value.restitution,
22 value.rollingResistance, {value.tangentVelocity.x, value.tangentVelocity.y, value.tangentVelocity.z},
23 value.userMaterialId, value.customColor};
24}
25class Box3DShape final : public IShapeBackend3D {
26 template <class F>
27 auto checked(const char* name, F&& operation) const -> decltype(operation()) {
28 using R = decltype(operation());
29 if (!isValid())
30 return R::failure(
32 try {
33 return operation();
34 } catch (const eve::Exception& error) {
36 }
37 }
38
39public:
40 Box3DShape(b3BodyId body, float density, float friction, float restitution)
41 : body_(body), initialDensity_(density) {
42 initialMaterial_.friction = friction;
43 initialMaterial_.restitution = restitution;
44 }
45 ~Box3DShape() override { destroy(); }
46 bool isValid() const noexcept override { return b3Shape_IsValid(shape_); }
47 void destroy() noexcept override {
48 if (isValid()) {
49 b3Shape_SetUserData(shape_, nullptr);
50 b3DestroyShape(shape_, true);
51 }
52 shape_ = {};
53 mesh_.reset();
54 height_.reset();
55 owner_ = nullptr;
56 }
57 void invalidate() noexcept override {
58 if (isValid()) b3Shape_SetUserData(shape_, nullptr);
59 shape_ = {};
60 owner_ = nullptr;
61 }
62 void bindOwner(Shape3D& owner) noexcept override {
63 owner_ = &owner;
64 if (isValid()) b3Shape_SetUserData(shape_, owner_);
65 }
66 eve::Result<ShapePlane3D> oneWayPlane(const ShapeGeometry3D& g, PhysicsVector3D normal,
67 float offset) const override {
68 return checked("physics.shape3d.oneWayPlane", [&] {
69 const auto bodyTransform = b3Body_GetTransform(body_);
70 const b3Quat localRotation{{g.localQx, g.localQy, g.localQz}, g.localQw};
71 const auto worldRotation = b3MulQuat(bodyTransform.q, localRotation);
72 const auto n = b3RotateVector(worldRotation, b3Vec3{normal.x, normal.y, normal.z});
73 const auto bodyOffset = b3RotateVector(bodyTransform.q, b3Vec3{g.localX, g.localY, g.localZ});
74 const auto point = b3OffsetPos(b3OffsetPos(bodyTransform.p, bodyOffset), offset * n);
75 return eve::Result<ShapePlane3D>::success({point.x, point.y, point.z, n.x, n.y, n.z});
76 });
77 }
78 b3ShapeId nativeId() const { return shape_; }
79 eve::Result<void> rebuild(const ShapeGeometry3D& g, ShapeBehavior3D behavior,
80 std::span<const SurfaceMaterial3D> materials) override {
81 if (!b3Body_IsValid(body_))
83 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "Shape body is no longer valid"));
84 try {
85 b3ShapeDef def = b3DefaultShapeDef();
86 def.density = isValid() ? b3Shape_GetDensity(shape_) : initialDensity_;
87 def.baseMaterial = isValid() ? b3Shape_GetSurfaceMaterial(shape_) : nativeMaterial(initialMaterial_);
88 if (isValid()) def.filter = b3Shape_GetFilter(shape_);
89 def.isSensor = behavior.sensor;
90 def.enableContactEvents = !behavior.sensor;
91 def.enableSensorEvents = true;
92 def.enableHitEvents = behavior.hitEvents && !behavior.sensor;
93 def.enablePreSolveEvents = behavior.preSolveEvents && !behavior.sensor;
94 def.enableCustomFiltering = behavior.customFiltering;
95 def.explosionScale = behavior.explosionScale;
96 std::vector<b3SurfaceMaterial> nativeMaterials;
97 for (auto value : materials) nativeMaterials.push_back(nativeMaterial(value));
98 if (!nativeMaterials.empty()) {
99 def.materials = nativeMaterials.data();
100 def.materialCount = static_cast<int>(nativeMaterials.size());
101 }
102 const b3Transform transform{{g.localX, g.localY, g.localZ}, {{g.localQx, g.localQy, g.localQz}, g.localQw}};
103 decltype(mesh_) nextMesh{nullptr, b3DestroyMesh};
104 decltype(height_) nextHeight{nullptr, b3DestroyHeightField};
105 b3ShapeId next{};
106 switch (g.kind) {
107 case ShapeKind3D::Box: {
108 if (!(g.a > 0.f && g.b > 0.f && g.c > 0.f) || !std::isfinite(g.a + g.b + g.c))
109 throw eve::Exception("Box dimensions must be finite and positive");
110 auto box = b3MakeBoxHull(g.a, g.b, g.c);
111 next = b3CreateTransformedHullShape(body_, &def, &box.base, transform, b3Vec3_one);
112 break;
113 }
114 case ShapeKind3D::Sphere: {
115 if (!(g.a > 0.f) || !std::isfinite(g.a))
116 throw eve::Exception("Sphere radius must be finite and positive");
117 const b3Sphere sphere{transform.p, g.a};
118 next = b3CreateSphereShape(body_, &def, &sphere);
119 break;
120 }
122 if (!(g.a >= 0.f && g.b > 0.f) || !std::isfinite(g.a + g.b))
123 throw eve::Exception("Capsule dimensions must be finite and valid");
124 auto axis = b3RotateVector(transform.q, b3Vec3{0.f, g.a, 0.f});
125 const b3Capsule capsule{transform.p - axis, transform.p + axis, g.b};
126 next = b3CreateCapsuleShape(body_, &def, &capsule);
127 break;
128 }
130 std::unique_ptr<b3HullData, decltype(&b3DestroyHull)> hull(
131 createCheckedHull(g.hullVertices, g.hullMaxVertices, "shape.rebuild"), b3DestroyHull);
132 next = b3CreateTransformedHullShape(body_, &def, hull.get(), transform, b3Vec3_one);
133 break;
134 }
136 if (b3Body_GetType(body_) != b3_staticBody)
137 throw eve::Exception("Triangle meshes require a static body");
138 nextMesh.reset(createCheckedMesh(g.meshVertices, g.meshIndices, g.meshWeldVertices,
139 g.meshWeldTolerance, g.meshIdentifyEdges, g.meshUseMedianSplit,
140 transform, &g.meshMaterialIndices, "shape.rebuild"));
141 next = b3CreateMeshShape(body_, &def, nextMesh.get(), b3Vec3_one);
142 break;
143 }
145 if (b3Body_GetType(body_) != b3_staticBody)
146 throw eve::Exception("Height fields require a static body");
147 nextHeight.reset(createCheckedHeightField(g.heightCountX, g.heightCountZ, g.heightCellSizeX,
148 g.heightCellSizeZ, g.heightValues, g.heightGlobalMin,
149 g.heightGlobalMax, g.heightClockwise, "shape.rebuild"));
150 next = b3CreateHeightFieldShape(body_, &def, nextHeight.get());
151 break;
152 }
153 }
154 if (!b3Shape_IsValid(next))
156 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "Box3D rejected shape creation"));
157 if (isValid()) {
158 b3Shape_SetUserData(shape_, nullptr);
159 b3DestroyShape(shape_, true);
160 }
161 shape_ = next;
162 mesh_ = std::move(nextMesh);
163 height_ = std::move(nextHeight);
164 kind_ = g.kind;
165 b3Shape_SetUserData(shape_, owner_);
167 } catch (const eve::Exception& error) {
169 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, error.what(), "physics.shape3d.rebuild"));
170 }
171 }
172 eve::Result<float> density() const override {
173 return checked("physics.shape3d.density",
174 [&] { return eve::Result<float>::success(b3Shape_GetDensity(shape_)); });
175 }
176 eve::Result<void> setDensity(float value, bool updateMass) override {
177 return checked("physics.shape3d.setDensity", [&] {
178 b3Shape_SetDensity(shape_, value, updateMass);
180 });
181 }
182 eve::Result<float> friction() const override {
183 return checked("physics.shape3d.friction",
184 [&] { return eve::Result<float>::success(b3Shape_GetFriction(shape_)); });
185 }
186 eve::Result<void> setFriction(float value) override {
187 return checked("physics.shape3d.setFriction", [&] {
188 b3Shape_SetFriction(shape_, value);
190 });
191 }
192 eve::Result<float> restitution() const override {
193 return checked("physics.shape3d.restitution",
194 [&] { return eve::Result<float>::success(b3Shape_GetRestitution(shape_)); });
195 }
196 eve::Result<void> setRestitution(float value) override {
197 return checked("physics.shape3d.setRestitution", [&] {
198 b3Shape_SetRestitution(shape_, value);
200 });
201 }
203 return checked("physics.shape3d.material", [&] {
204 return eve::Result<SurfaceMaterial3D>::success(materialValue(b3Shape_GetSurfaceMaterial(shape_)));
205 });
206 }
207 eve::Result<void> setMaterial(SurfaceMaterial3D value) override {
208 return checked("physics.shape3d.setMaterial", [&] {
209 b3Shape_SetSurfaceMaterial(shape_, nativeMaterial(value));
211 });
212 }
213 eve::Result<ShapeFilter3D> filter() const override {
214 return checked("physics.shape3d.filter", [&] {
215 return eve::Result<ShapeFilter3D>::success(ShapeFilter3D{b3Shape_GetFilter(shape_).categoryBits,
216 b3Shape_GetFilter(shape_).maskBits,
217 b3Shape_GetFilter(shape_).groupIndex});
218 });
219 }
220 eve::Result<void> setFilter(ShapeFilter3D value, bool updatePairs) override {
221 return checked("physics.shape3d.setFilter", [&] {
222 b3Shape_SetFilter(shape_, b3Filter{value.categoryBits, value.maskBits, value.groupIndex}, updatePairs);
224 });
225 }
226 eve::Result<bool> isSensor() const override {
227 return checked("physics.shape3d.isSensor",
228 [&] { return eve::Result<bool>::success(b3Shape_IsSensor(shape_)); });
229 }
230 eve::Result<void> enableHitEvents(bool enabled) override {
231 return checked("physics.shape3d.enableHitEvents", [&] {
232 b3Shape_EnableHitEvents(shape_, enabled);
234 });
235 }
236 eve::Result<void> enablePreSolveEvents(bool enabled) override {
237 return checked("physics.shape3d.enablePreSolveEvents", [&] {
238 b3Shape_EnablePreSolveEvents(shape_, enabled);
240 });
241 }
242 eve::Result<int> meshMaterialCount() const override {
243 return checked("physics.shape3d.meshMaterialCount",
244 [&] { return eve::Result<int>::success(b3Shape_GetMeshMaterialCount(shape_)); });
245 }
246 eve::Result<SurfaceMaterial3D> meshMaterial(int slot) const override {
247 return checked("physics.shape3d.meshMaterial", [&] {
248 if (kind_ != ShapeKind3D::TriangleMesh || slot < 0 || slot >= b3Shape_GetMeshMaterialCount(shape_))
249 throw eve::Exception("Mesh material slot is out of range");
250 return eve::Result<SurfaceMaterial3D>::success(materialValue(b3Shape_GetMeshSurfaceMaterial(shape_, slot)));
251 });
252 }
253 eve::Result<void> setMeshMaterial(SurfaceMaterial3D value, int slot) override {
254 return checked("physics.shape3d.setMeshMaterial", [&] {
255 if (kind_ != ShapeKind3D::TriangleMesh || slot < 0 || slot >= b3Shape_GetMeshMaterialCount(shape_))
256 throw eve::Exception("Mesh material slot is out of range");
257 b3Shape_SetMeshMaterial(shape_, nativeMaterial(value), slot);
259 });
260 }
261 eve::Result<bool> testPoint(float x, float y, float z) const override {
262 return checked("physics.shape3d.testPoint", [&] {
263 const auto overlap = [&]() -> bool {
264 b3Vec3 point{x, y, z};
265 b3ShapeProxy proxy;
266 proxy.points = &point;
267 proxy.count = 1;
268 proxy.radius = 0.f;
269
270 b3WorldTransform wt = b3Body_GetTransform(body_);
271 b3Transform xf;
272 xf.p = b3Vec3{static_cast<float>(wt.p.x), static_cast<float>(wt.p.y), static_cast<float>(wt.p.z)};
273 xf.q = wt.q;
274
275 switch (kind_) {
276 case ShapeKind3D::Box:
278 const b3HullData* hull = b3Shape_GetHull(shape_);
279 if (!hull) return false;
280 return b3OverlapHull(hull, xf, &proxy);
281 }
282 case ShapeKind3D::Sphere: {
283 b3Sphere sphere = b3Shape_GetSphere(shape_);
284 return b3OverlapSphere(&sphere, xf, &proxy);
285 }
287 b3Capsule capsule = b3Shape_GetCapsule(shape_);
288 return b3OverlapCapsule(&capsule, xf, &proxy);
289 }
291 const b3Mesh mesh = b3Shape_GetMesh(shape_);
292 return mesh.data ? b3OverlapMesh(&mesh, xf, &proxy) : false;
293 }
295 const b3HeightFieldData* heightField = b3Shape_GetHeightField(shape_);
296 return heightField ? b3OverlapHeightField(heightField, xf, &proxy) : false;
297 }
298 }
299 return false;
300 };
301 return eve::Result<bool>::success(overlap());
302 });
303 }
304
305private:
306 b3BodyId body_{};
307 b3ShapeId shape_{};
309 Shape3D* owner_ = nullptr;
310 float initialDensity_;
311 SurfaceMaterial3D initialMaterial_;
312 std::unique_ptr<b3MeshData, decltype(&b3DestroyMesh)> mesh_{nullptr, b3DestroyMesh};
313 std::unique_ptr<b3HeightFieldData, decltype(&b3DestroyHeightField)> height_{nullptr, b3DestroyHeightField};
314};
315} // namespace
316
318 float friction, float restitution) {
319 if (!std::isfinite(density) || density < 0.f || !std::isfinite(friction) || friction < 0.f ||
320 !std::isfinite(restitution) || restitution < 0.f)
322 eve::DiagnosticCode::InvalidArgument, "Shape material values must be finite and non-negative"));
323 auto shape = std::make_unique<Box3DShape>(body, density, friction, restitution);
324 auto result = shape->rebuild(geometry, {}, {});
325 if (!result.ok()) return eve::Result<std::unique_ptr<IShapeBackend3D>>::failure(result.status());
326 return eve::Result<std::unique_ptr<IShapeBackend3D>>::success(std::move(shape));
327}
328b3ShapeId Access::shapeId(const Shape3D& shape) {
329 const auto* backend = dynamic_cast<const Box3DShape*>(shape.backend_.get());
330 EV_ASSERT(backend != nullptr, "Box3D composition requires a Box3D shape");
331 return backend->nativeId();
332}
333} // namespace eve::physics::box3d
double z
double y
double x
ActionParameterOperation operation
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
std::string name
Definition ECS.cpp:154
float friction
float density
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
void(* destroy)(void *)
JointPoint2D axis
size_t offset
Poco::JSON::Object::Ptr result
Texture * normal
std::shared_ptr< OceanGpuSpectrum > owner
OceanMeshSettings mesh
OceanRenderBackend backend
std::string error
Definition Package.cpp:174
std::array< uint32_t, 16 > material
std::string body
Object::Ptr value
std::string slot
std::string filter
std::string geometry
double restitution
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
3D shape (box/sphere/capsule) attached to a Body3D with material settings. Created via Body3D::new*Sh...
Definition Shape3D.h:34
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
eve::Result< std::unique_ptr< IShapeBackend3D > > makeShape(b3BodyId body, const ShapeGeometry3D &geometry, float density, float friction, float restitution)
Internal native shape factory; transfers native/cooked ownership on success. @cost Cooks the supplied...
b3MeshData * createCheckedMesh(const std::vector< float > &vertices, const std::vector< int32_t > &indices, bool weldVertices, float weldTolerance, bool identifyEdges, bool useMedianSplit, b3Transform transform, const std::vector< uint8_t > *materialIndices, const char *operation)
Validates and cooks native geometry; throws on invalid input. @ownership Transfers native allocation ...
b3HeightFieldData * createCheckedHeightField(int countX, int countZ, float cellSizeX, float cellSizeZ, const std::vector< float > &heights, float globalMin, float globalMax, bool clockwiseWinding, const char *operation)
Validates and cooks native geometry; throws on invalid input. @ownership Transfers native allocation ...
b3HullData * createCheckedHull(const std::vector< float > &vertices, int maxVertices, const char *operation)
Validates and cooks native geometry; throws on invalid input. @ownership Transfers native allocation ...
Result< ForceVector > checked(ForceVector value)
Definition ForceMath.h:21
ShapeKind3D
Geometry kinds supported by the rigid shape contract.
bool enabled
Owning, backend-independent shape source; metres, local quaternion XYZW.
static b3ShapeId shapeId(const Shape3D &shape)
Borrows a Box3D shape identifier for a synchronous native operation.