载入中...
搜索中...
未找到
JoltWorld.cpp
浏览该文件的文档.
1// eve-hot-path
2// Jolt requires its platform header before any other native header.
3#include <Jolt/Jolt.h>
4
5// Provider implementation dependencies.
6#include <Jolt/Physics/Body/MotionProperties.h>
7#include <algorithm>
8#include <chrono>
9#include "physics/Joint3D.h"
10#include "physics/World3D.h"
15namespace eve::physics::jolt {
16namespace {
17class StepDriver final : public ISimulationBackend {
18 WorldBackend& world;
19 SimulationObservation progress;
20
21public:
22 explicit StepDriver(WorldBackend& value) : world(value) {}
23 eve::Result<void> step(const SimulationStep& step, const SimulationSettings& settings) override {
24 auto valid = detail::validateSimulationStep(step, settings, progress);
25 if (!valid) return valid;
26 if (!world.isValid()) return rejected<void>("World expired", eve::DiagnosticCode::StaleHandle);
27 auto next = detail::advanceSimulationObservation(progress, step);
28 if (!next) return eve::Result<void>::failure(next.status());
29 auto& state = *world.state;
30 if (state.faulted)
31 return rejected<void>("Solver requires world recreation after capacity failure",
33 auto policy = state.system.GetPhysicsSettings();
34 policy.mNumVelocitySteps = static_cast<JPH::uint>(settings.velocityIterations);
35 policy.mNumPositionSteps = static_cast<JPH::uint>(settings.positionIterations);
36 state.system.SetPhysicsSettings(policy);
37 if (step.delta.seconds() > 0) {
38 state.listener->solved.clear();
39 state.listener->hits.clear();
40 state.listener->normalTotals.clear();
41 state.listener->substep = 0;
42 if (policy.mContactPointPreserveLambdaMaxDistSq == 0)
43 for (const auto& [id, body] : state.bodies) body->api().InvalidateContactCache(body->id);
44 state.inverseStep = settings.subStepCount / static_cast<float>(step.delta.seconds());
45 const auto started = std::chrono::steady_clock::now();
46 auto error = state.system.Update(static_cast<float>(step.delta.seconds()), settings.subStepCount,
47 &state.allocator, &state.jobs);
48 state.stepMilliseconds =
49 std::chrono::duration<float, std::milli>(std::chrono::steady_clock::now() - started).count();
50 if (error != JPH::EPhysicsUpdateError::None) {
51 state.faulted = true;
52 return rejected<void>("Solver capacity exceeded; simulation stopped", eve::DiagnosticCode::Failed);
53 }
54 }
55 // Explicit per-body thresholds use a conservative point-speed bound and simulation time.
56 // Native automatic sleep is disabled only for these bodies, so there is one decision owner.
57 for (const auto& [id, body] : state.bodies) {
58 if (!body->customSleepThreshold) continue;
59 auto* native = state.system.GetBodyLockInterfaceNoLock().TryGetBody(body->id);
60 if (!state.sleep || !body->sleepEnabled || !native->IsDynamic() || !native->IsActive()) {
61 body->quietSeconds = 0;
62 continue;
63 }
64 const float speed =
65 native->GetLinearVelocity().Length() +
66 native->GetAngularVelocity().Length() * native->GetShape()->GetLocalBounds().GetExtent().Length();
67 body->quietSeconds = speed > body->sleepThreshold ? 0.f : body->quietSeconds + float(step.delta.seconds());
68 if (body->quietSeconds >= state.system.GetPhysicsSettings().mTimeBeforeSleep) {
69 body->api().DeactivateBody(body->id);
70 body->quietSeconds = 0;
71 }
72 }
73 progress = std::move(next).takeValue();
74 return success();
75 }
76 SimulationObservation observation() const noexcept override { return progress; }
77 SimulationBackendKind kind() const noexcept override { return SimulationBackendKind::Cpu; }
78 SimulationDeterminism determinism() const noexcept override { return SimulationDeterminism::ToleranceBounded; }
79 eve::Result<void> restoreObservation(const SimulationObservation& value) override {
80 auto valid = detail::validateSimulationObservation(value, "physics.jolt.restore");
81 if (!valid) return valid;
82 progress = value;
83 return success();
84 }
85};
86} // namespace
87WorldBackend::WorldBackend(World3D& facade, float x, float y, float z, bool sleep)
88 : owner(&facade), state((initializeRuntime(), std::make_shared<State>(x, y, z, sleep))) {}
90bool WorldBackend::isValid() const noexcept { return state && state->alive; }
91void WorldBackend::destroy() noexcept {
92 if (state) {
93 state->alive = false;
94 state->bodies.clear();
95 state.reset();
96 }
97}
100 std::make_unique<WorldBackend>(owner, x, y, z, sleep));
101}
107 auto* other = dynamic_cast<WorldBackend*>(&prepared);
108 if (!other) return rejected<void>("Cannot swap different rigid backends");
109 state.swap(other->state);
110 return success();
111}
112uint64_t WorldBackend::shapeKey(const Shape3D& shape) const { return static_cast<uint64_t>(shape.getId()); }
114 float z) {
115 if (!isValid()) return rejected<std::unique_ptr<IBodyBackend3D>>("World expired", eve::DiagnosticCode::StaleHandle);
116 if (!isFinite(x, y, z) || (type != "static" && type != "dynamic" && type != "kinematic"))
117 return rejected<std::unique_ptr<IBodyBackend3D>>("Invalid body definition",
119 auto motion = type == "static" ? JPH::EMotionType::Static
120 : type == "dynamic" ? JPH::EMotionType::Dynamic
121 : JPH::EMotionType::Kinematic;
122 JPH::RefConst<JPH::Shape> empty = new JPH::EmptyShape;
123 JPH::BodyCreationSettings settings(empty, {x, y, z}, JPH::Quat::sIdentity(), motion,
124 motion == JPH::EMotionType::Static ? 0 : 1);
125 settings.mAllowDynamicOrKinematic = true;
126 settings.mAllowSleeping = state->sleep;
127 settings.mMaxLinearVelocity = state->maximumLinearSpeed;
128 settings.mOverrideMassProperties = JPH::EOverrideMassProperties::MassAndInertiaProvided;
129 settings.mMassPropertiesOverride.SetMassAndInertiaOfSolidBox({1, 1, 1}, 1);
130 auto& api = state->system.GetBodyInterface();
131 auto* native = api.CreateBody(settings);
132 if (!native)
133 return rejected<std::unique_ptr<IBodyBackend3D>>("Body capacity exhausted", eve::DiagnosticCode::Failed);
134 auto body = std::make_shared<BodyState>();
135 body->mass = settings.mMassPropertiesOverride;
136 body->world = state;
137 body->id = native->GetID();
138 state->bodies.emplace(body->id.GetIndexAndSequenceNumber(), body);
139 api.AddBody(body->id, JPH::EActivation::Activate);
140 return eve::Result<std::unique_ptr<IBodyBackend3D>>::success(std::make_unique<BodyBackend>(body));
141}
143 if (!isValid()) return rejected<void>("World expired", eve::DiagnosticCode::StaleHandle);
144 auto append = [&](const ContactPair& pair, bool begin) {
145 World3D::EventShape a{pair.bodyA, pair.shapeA, pair.tagA}, b{pair.bodyB, pair.shapeB, pair.tagB};
146 if (pair.sensorA || pair.sensorB) {
147 auto& output = begin ? owner->beginTriggers_ : owner->endTriggers_;
148 if (pair.sensorA) output.push_back({a, b});
149 if (pair.sensorB) output.push_back({b, a});
150 } else {
151 if (a.shapeId > b.shapeId) std::swap(a, b);
152 (begin ? owner->beginContacts_ : owner->endContacts_).push_back({a, b});
153 }
154 };
155 for (const auto& pair : state->listener->begins) append(pair, true);
156 for (const auto& pair : state->listener->ends) append(pair, false);
157 const auto hitStart = owner->hits_.size();
158 for (const auto& [key, hit] : state->listener->hits) {
159 if (!owner->findShape(hit.shapeA) || !owner->findShape(hit.shapeB)) continue;
160 const auto& pair = hit.pair;
161 owner->hits_.push_back({{pair.bodyA, pair.shapeA, pair.tagA},
162 {pair.bodyB, pair.shapeB, pair.tagB},
163 hit.x,
164 hit.y,
165 hit.z,
166 hit.nx,
167 hit.ny,
168 hit.nz,
169 hit.speed,
170 hit.impulse});
171 }
172 state->listener->hits.clear();
173 std::sort(owner->hits_.begin() + hitStart, owner->hits_.end(), [](const auto& a, const auto& b) {
174 if (a.shapeA.shapeId != b.shapeA.shapeId) return a.shapeA.shapeId < b.shapeA.shapeId;
175 return a.shapeB.shapeId < b.shapeB.shapeId;
176 });
177 for (const auto& weak : state->joints)
178 if (auto joint = weak.lock(); joint && joint->alive && joint->owner) {
179 auto& facade = *joint->owner;
180 JPH::Vec3 f(facade.getConstraintForceX(), facade.getConstraintForceY(), facade.getConstraintForceZ());
181 JPH::Vec3 t(facade.getConstraintTorqueX(), facade.getConstraintTorqueY(), facade.getConstraintTorqueZ());
182 if (f.Length() > joint->forceThreshold || t.Length() > joint->torqueThreshold)
183 owner->jointStressEvents_.push_back({facade.getId(), facade.getBodyAId(), facade.getBodyBId(),
184 static_cast<int>(joint->kind), f.GetX(), f.GetY(), f.GetZ(),
185 t.GetX(), t.GetY(), t.GetZ()});
186 }
187 state->listener->begins.clear();
188 state->listener->ends.clear();
189 return success();
190}
191} // namespace eve::physics::jolt
double z
double y
double x
std::string output
SQObjectPtr key
Definition ECS.cpp:155
ShaderImageInput shape
std::string id
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
std::shared_ptr< OceanGpuSpectrum > owner
std::string error
Definition Package.cpp:174
float f
bool hit
std::string body
Object::Ptr value
float t
size_t begin
std::string kind
float step
Definition TreeMesh.cpp:451
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
Complete rigid-world execution boundary, bound once to an owning World3D facade. @ownership Owns exac...
3D shape (box/sphere/capsule) attached to a Body3D with material settings. Created via Body3D::new*Sh...
Definition Shape3D.h:34
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
Shape3D * findShape(PhysicsShapeHandle handle) const
Resolves a live shape handle; returns null when stale or foreign.
Definition World3D.cpp:447
void destroy() noexcept override
Idempotent native teardown after all facades have been invalidated.
Definition JoltWorld.cpp:91
WorldBackend(World3D &, float, float, float, bool)
Definition JoltWorld.cpp:87
std::shared_ptr< State > state
Definition JoltWorld.h:17
eve::Result< std::unique_ptr< IBodyBackend3D > > createBody(std::string_view type, float x, float y, float z) override
Creates an owning body backend without publishing an engine wrapper. @cost One native body allocation...
eve::Result< SimulationBackendSelection > selectSimulation() override
Builds the separate CPU/accelerator step driver; driver borrows this world's stable state.
bool isValid() const noexcept override
Native world liveness.
Definition JoltWorld.cpp:90
eve::Result< void > collectEvents() override
Collects solver events into the owner's queues without publishing callbacks.
eve::Result< void > swapTopology(IWorldBackend3D &prepared) override
Swaps prepared native topology while retaining stable step-driver contexts.
uint64_t shapeKey(const Shape3D &shape) const override
Opaque native lookup key scoped to this world, used only by internal event history.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
eve::Result< void > success()
void initializeRuntime()
Initializes the process-owned allocator and type factory before constructing any native members.
Definition JoltState.cpp:84
eve::Result< std::unique_ptr< IWorldBackend3D > > makeWorld(World3D &owner, float x, float y, float z, bool sleep)
Creates the native Jolt provider; world owns it and calls it only on the simulation thread....
Definition JoltWorld.cpp:98
bool isFinite(float x, float y, float z)
SimulationBackendKind
Kind of implementation that owns a simulation step.
SimulationDeterminism
Determinism guarantee made by a simulation backend.
@ ToleranceBounded
Results are equivalent within a documented numeric tolerance.
eve::SimulationStep SimulationStep
Compatibility alias for the common injected simulation step.
Stable snapshot describing one side of a 3D collision event.
Definition World3D.h:50
bool started
Definition Graphics.cpp:200