载入中...
搜索中...
未找到
JoltShape.cpp
浏览该文件的文档.
1// Jolt requires its platform header before any other native header.
2#include <Jolt/Jolt.h>
3
4// Provider implementation dependencies.
5#include <Jolt/Geometry/ConvexHullBuilder.h>
6#include <Jolt/Physics/Body/MotionProperties.h>
7#include <Jolt/Physics/Collision/Shape/BoxShape.h>
8#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
9#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
10#include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
11#include <Jolt/Physics/Collision/Shape/SphereShape.h>
12#include <algorithm>
15namespace eve::physics::jolt {
18 if (!std::isfinite(density) || density < 0 || !isFinite(g.localX, g.localY, g.localZ) ||
19 !isFinite(g.localQx, g.localQy, g.localQz) || !std::isfinite(g.localQw))
20 return rejected<JPH::RefConst<JPH::Shape>>("Invalid shape parameters", eve::DiagnosticCode::InvalidArgument);
21 std::unique_ptr<JPH::ConvexShapeSettings> settings;
22 if (g.kind == ShapeKind3D::Box && isFinite(g.a, g.b, g.c) && g.a > 0 && g.b > 0 && g.c > 0)
23 settings = std::make_unique<JPH::BoxShapeSettings>(JPH::Vec3(g.a, g.b, g.c), std::min({0.05f, g.a, g.b, g.c}));
24 else if (g.kind == ShapeKind3D::Sphere && std::isfinite(g.a) && g.a > 0)
25 settings = std::make_unique<JPH::SphereShapeSettings>(g.a);
26 else if (g.kind == ShapeKind3D::Capsule && isFinite(g.a, g.b, 0) && g.a >= 0 && g.b > 0)
27 settings = std::make_unique<JPH::CapsuleShapeSettings>(g.a, g.b);
28 else if (g.kind == ShapeKind3D::ConvexHull) {
29 if (g.hullVertices.size() < 12 || g.hullVertices.size() % 3 || g.hullVertices.size() / 3 > 100000 ||
30 g.hullMaxVertices < 4 || g.hullMaxVertices > 254)
31 return rejected<JPH::RefConst<JPH::Shape>>("Invalid hull", eve::DiagnosticCode::InvalidArgument);
32 auto hull = std::make_unique<JPH::ConvexHullShapeSettings>();
33 for (size_t i = 0; i < g.hullVertices.size(); i += 3) {
34 if (!isFinite(g.hullVertices[i], g.hullVertices[i + 1], g.hullVertices[i + 2]))
35 return rejected<JPH::RefConst<JPH::Shape>>("Invalid hull", eve::DiagnosticCode::InvalidArgument);
36 hull->mPoints.emplace_back(g.hullVertices[i], g.hullVertices[i + 1], g.hullVertices[i + 2]);
37 }
38 JPH::ConvexHullBuilder builder(hull->mPoints);
39 const char* error = nullptr;
40 const auto built = builder.Initialize(g.hullMaxVertices, hull->mHullTolerance, error);
41 if (built != JPH::ConvexHullBuilder::EResult::Success &&
42 built != JPH::ConvexHullBuilder::EResult::MaxVerticesReached)
43 return rejected<JPH::RefConst<JPH::Shape>>(error ? error : "Invalid hull",
45 JPH::Vec3 center;
46 float volume = 0;
47 builder.GetCenterOfMassAndVolume(center, volume);
48 if (!std::isfinite(volume) || volume <= 0)
49 return rejected<JPH::RefConst<JPH::Shape>>("Hull must have positive volume",
51 // Keep source order for deterministic cooking; faces borrow indices from the original points.
52 std::vector<bool> used(hull->mPoints.size(), false);
53 for (const auto* face : builder.GetFaces()) {
54 const auto* edge = face->mFirstEdge;
55 do {
56 used[static_cast<size_t>(edge->mStartIdx)] = true;
57 edge = edge->mNextEdge;
58 } while (edge != face->mFirstEdge);
59 }
60 JPH::Array<JPH::Vec3> reduced;
61 for (size_t i = 0; i < used.size(); ++i)
62 if (used[i]) reduced.push_back(hull->mPoints[i]);
63 hull->mPoints = std::move(reduced);
64 settings = std::move(hull);
65 } else if (g.kind == ShapeKind3D::TriangleMesh || g.kind == ShapeKind3D::HeightField)
66 return cookMesh(g, userData);
67 else
68 return rejected<JPH::RefConst<JPH::Shape>>("Invalid primitive dimensions",
70 settings->mDensity = density;
71 settings->mUserData = userData;
72 auto result = settings->Create();
73 if (result.HasError())
74 return rejected<JPH::RefConst<JPH::Shape>>(result.GetError().c_str(), eve::DiagnosticCode::InvalidArgument);
75 return R::success(result.Get());
76}
77eve::Result<void> replaceShapes(BodyState& body, const std::vector<std::shared_ptr<ShapeState>>& shapes) {
78 if (!body.valid()) return rejected<void>("Body expired", eve::DiagnosticCode::StaleHandle);
79 for (const auto& shape : shapes)
80 if (shape->native->MustBeStatic() && body.api().GetMotionType(body.id) != JPH::EMotionType::Static)
81 return rejected<void>("Concave shapes require a static body", eve::DiagnosticCode::InvalidArgument);
82 JPH::RefConst<JPH::Shape> native;
83 if (shapes.empty())
84 native = new JPH::EmptyShape;
85 else {
86 JPH::StaticCompoundShapeSettings settings;
87 for (const auto& s : shapes) {
88 const auto& g = s->geometry;
89 JPH::Quat q(g.localQx, g.localQy, g.localQz, g.localQw);
90 if (!std::isfinite(q.LengthSq()) || q.LengthSq() < 1.e-12f)
91 return rejected<void>("Invalid local rotation", eve::DiagnosticCode::InvalidArgument);
92 settings.AddShape({g.localX, g.localY, g.localZ}, q.Normalized(), s->native);
93 }
94 auto result = settings.Create();
95 if (result.HasError()) return rejected<void>(result.GetError().c_str(), eve::DiagnosticCode::InvalidArgument);
96 native = result.Get();
97 }
98 auto mass = body.mass;
99 if (!native->MustBeStatic()) {
100 mass = native->GetMassProperties();
101 if (!(mass.mMass > 0)) mass.SetMassAndInertiaOfSolidBox({1, 1, 1}, 1);
102 }
103 const auto previous = body.api().GetShape(body.id)->GetCenterOfMass();
104 std::erase_if(body.world.lock()->listener->solved, [&](const auto& entry) {
105 return entry.first.GetBody1ID() == body.id || entry.first.GetBody2ID() == body.id;
106 });
107 body.api().SetShape(body.id, native, false, JPH::EActivation::Activate);
108 if (!native->MustBeStatic()) {
109 auto* nativeBody = body.world.lock()->system.GetBodyLockInterfaceNoLock().TryGetBody(body.id);
110 nativeBody->GetMotionPropertiesUnchecked()->SetMassProperties(body.dofs, mass);
111 body.mass = mass;
112 }
113 notifyJointShapeChanged(*body.world.lock(), body.id, native->GetCenterOfMass() - previous);
114 return success();
115}
117bool ShapeBackend::isValid() const noexcept { return shape && shape->valid(); }
118void ShapeBackend::bindOwner(Shape3D& owner) noexcept { shape->owner = &owner; }
120 shape->alive = false;
121 shape->owner = nullptr;
122}
123void ShapeBackend::destroy() noexcept {
124 if (isValid()) {
125 auto b = shape->body.lock();
126 auto list = b->shapes;
127 std::erase(list, shape);
128 auto result = replaceShapes(*b, list);
129 if (result)
130 b->shapes = std::move(list);
131 else
132 result.ignore("Destructor cannot report shape removal failure; parent retains native resources");
133 }
134 invalidate();
135}
137 std::span<const SurfaceMaterial3D> materials) {
138 if (!isValid()) return rejected<void>("Shape expired", eve::DiagnosticCode::StaleHandle);
139 for (const auto& material : materials) {
141 if (!checked) return checked;
142 }
143 if (!geometry.meshMaterialIndices.empty() &&
144 *std::max_element(geometry.meshMaterialIndices.begin(), geometry.meshMaterialIndices.end()) >= materials.size())
145 return rejected<void>("Missing mesh material", eve::DiagnosticCode::InvalidArgument);
146 auto cooked = cook(geometry, shape->density, reinterpret_cast<JPH::uint64>(shape.get()));
147 if (!cooked) return eve::Result<void>::failure(cooked.status());
148 auto old = shape->native;
149 auto oldGeometry = shape->geometry;
150 shape->native = std::move(cooked).takeValue();
151 shape->geometry = geometry;
152 auto b = shape->body.lock();
153 auto result = replaceShapes(*b, b->shapes);
154 if (!result) {
155 shape->native = old;
156 shape->geometry = std::move(oldGeometry);
157 return result;
158 }
159 shape->meshMaterials.assign(materials.begin(), materials.end());
160 shape->sensor = behavior.sensor;
161 return success();
162}
163} // namespace eve::physics::jolt
double volume
const std::string & s
float density
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
std::array< double, 10 > q
Poco::JSON::Object::Ptr result
uint64_t used
MeleePoint3 b
Definition MeleeHit.cpp:41
OceanWakeSettings settings
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec2 center
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
std::string body
std::string geometry
Move-only operation result carrying either a value or Status.
Definition Result.h:176
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
void invalidate() noexcept override
Detaches native identity before parent teardown; retains cooked data until destruction.
std::shared_ptr< ShapeState > shape
Definition JoltShape.h:10
eve::Result< SurfaceMaterial3D > material() const override
material; synchronous owning-value operation under the class lifetime contract.
void bindOwner(Shape3D &owner) noexcept override
Binds the owning facade for internal collision attribution; no callbacks. @ownership Borrows its excl...
bool isValid() const noexcept override
Native shape liveness.
void destroy() noexcept override
Idempotent native resource release after dependent records have been detached.
eve::Result< void > rebuild(const ShapeGeometry3D &geometry, ShapeBehavior3D behavior, std::span< const SurfaceMaterial3D > materials) override
Atomically replaces cooked geometry, preserving material, density and filter. @cost One geometry cook...
Result< ForceVector > checked(ForceVector value)
Definition ForceMath.h:21
eve::Result< T > rejected(const char *operation, eve::DiagnosticCode code=eve::DiagnosticCode::Unsupported)
void notifyJointShapeChanged(State &state, JPH::BodyID id, JPH::Vec3Arg delta)
Recomputes constraint COM offsets after a successful native shape replacement.
eve::Result< void > success()
eve::Result< void > replaceShapes(BodyState &, const std::vector< std::shared_ptr< ShapeState > > &)
Definition JoltShape.cpp:77
eve::Result< JPH::RefConst< JPH::Shape > > cookMesh(const ShapeGeometry3D &, JPH::uint64 userData)
Definition JoltMesh.cpp:10
eve::Result< JPH::RefConst< JPH::Shape > > cook(const ShapeGeometry3D &, float density, JPH::uint64 userData)
Definition JoltShape.cpp:16
bool isFinite(float x, float y, float z)
eve::Result< void > validateMaterial(SurfaceMaterial3D)
Shape behavior reapplied atomically when geometry changes.
Owning, backend-independent shape source; metres, local quaternion XYZW.