载入中...
搜索中...
未找到
WorldSnapshot.cpp
浏览该文件的文档.
1#include "physics/World.h"
2
3
4#include "physics/Body.h"
5#include "physics/Body3D.h"
6#include "physics/Fixture.h"
7#include "physics/Joint3D.h"
8#include "physics/Shape3D.h"
10#include "physics/World3D.h"
11
12#include <Box2D/Box2D.h>
13#include <glm/gtc/quaternion.hpp>
14
15#include <algorithm>
16#include <charconv>
17#include <cmath>
18#include <cstdint>
19#include <exception>
20#include <initializer_list>
21#include <limits>
22#include <set>
23#include <string>
24#include <string_view>
25#include <utility>
26#include <vector>
27
30
31namespace eve::physics {
32using namespace snapshot_detail;
33
34
36 if (pendingForceStep_)
38 "Complete the submitted force step before snapshot",
39 "physics.forces.snapshot"));
40 if (!isValid() || !simulation_)
42 eve::DiagnosticCode::PreconditionViolation, "Cannot snapshot a destroyed or uninitialized physics world",
43 "physics.world.snapshot"));
44 if (raw()->IsLocked() || simulationStepActive_)
46 Diagnostic::error(DiagnosticCode::PreconditionViolation, "Cannot snapshot while stepping"));
47 auto joints = WorldSnapshotAccess::captureJoints2D(*this);
48 if (!joints) return Result<SnapshotEnvelope>::failure(joints.status());
49 auto schema = snapshotSchema(kWorld2DSchema);
50 if (!schema) return eve::Result<eve::SnapshotEnvelope>::failure(schema.status());
51 const auto observation = simulationObservation();
52 std::vector<Body*> bodies(bodies_.begin(), bodies_.end());
53 auto payload = make2DPayload(*this, bodies);
54 payload.set("joints", std::move(joints).takeValue());
56 std::string(kWorld2DType), std::move(schema).takeValue(), eve::SchemaVersion(kSnapshot2DVersion), instanceId_,
57 eve::Revision(observation.stepCount), simulationTick(), std::move(payload), hashProvider);
58}
59
61 const eve::SnapshotHashProvider& hashProvider) {
62 if (!isValid() || !simulation_)
64 eve::DiagnosticCode::PreconditionViolation, "Cannot restore a destroyed or uninitialized physics world",
65 "physics.world.restore"));
66 auto verified = eve::verifySnapshotEnvelope(snapshotValue, hashProvider);
67 if (!verified) return verified;
68 auto envelope = checkEnvelope(snapshotValue, kWorld2DType, kWorld2DSchema);
69 if (!envelope) return envelope;
70 if (raw()->IsLocked() || simulationStepActive_)
72 Diagnostic::error(DiagnosticCode::PreconditionViolation, "Cannot restore while stepping"));
73 if (snapshotValue.instanceId.isNil() || snapshotValue.instanceId != instanceId_)
75 DiagnosticCode::Conflict, "physics snapshot belongs to a different world instance", "snapshot.instanceId"));
76 eve::Value migratedPayload = snapshotValue.payload;
77 if (snapshotValue.schemaVersion.value() == 2) {
78 auto migration = migratePlanarV2(migratedPayload);
79 if (!migration) return migration;
80 }
81 const auto* object = migratedPayload.getIf<eve::Value::Object>();
82 if (!object || !hasExactFields(*object, {"bodies", "joints", "allowSleep", "gravityX", "gravityY", "meter", "tick",
83 "revision", "stepCount", "simulatedDurationNs", "lastDeltaSeconds"}))
85 eve::DiagnosticCode::ParseError, "2D physics snapshot payload has unknown or missing fields", "payload"));
86 auto observation = parseObservation(*object, snapshotValue);
87 if (!observation) return eve::Result<void>::failure(observation.status());
88 auto bodies = parseBodies2D(*object);
89 if (!bodies) return eve::Result<void>::failure(bodies.status());
90 auto gravityX = readFloat(*object, "gravityX");
91 if (!gravityX) return eve::Result<void>::failure(gravityX.status());
92 auto gravityY = readFloat(*object, "gravityY");
93 if (!gravityY) return eve::Result<void>::failure(gravityY.status());
94 auto meter = readFloat(*object, "meter");
95 if (!meter) return eve::Result<void>::failure(meter.status());
96 if (meter.value() <= 0.f)
98 eve::DiagnosticCode::InvalidArgument, "physics snapshot meter must be positive", "payload.meter"));
99
100 std::set<int> snapshotIds;
101 auto matched = matchBodyIds(bodies.value(), snapshotIds);
102 if (!matched) return matched;
103 auto handleRefresh = prepareRuntimeHandleRefresh(bodies.value().size());
104 if (!handleRefresh) return handleRefresh;
105 auto prepared = prepareWorld2D(bodies.value(), gravityX.value(), gravityY.value(), meter.value(),
106 observation.value().value, instanceId_);
107 if (!prepared) return eve::Result<void>::failure(prepared.status());
108 const auto* jointValues = field(*object, "joints")->getIf<Value::Array>();
109 if (!jointValues)
110 return Result<void>::failure(Diagnostic::error(DiagnosticCode::ParseError, "Planar joints must be an array"));
111 auto sleeping = readBool(*object, "allowSleep");
112 if (!sleeping) return Result<void>::failure(sleeping.status());
113 prepared.value()->raw()->SetAllowSleeping(sleeping.value());
114 auto jointRestore = WorldSnapshotAccess::restoreJoints2D(*prepared.value(), *jointValues, nextJointHandleIndex_);
115 if (!jointRestore) return jointRestore;
116 WorldSnapshotAccess::adopt(*this, *prepared.value());
117 refreshRuntimeHandlesAfterRestore();
120}
121
123 if (rigidBackendKind_ != RigidBackend3D::Box3D) return snapshotPortable(hashProvider);
124 if (pendingForceStep_)
126 "Complete the submitted force step before snapshot",
127 "physics.forces.snapshot"));
128 if (couplingStepActive_)
130 DiagnosticCode::PreconditionViolation, "Cannot snapshot while stepping", "physics.world3d.snapshot"));
131 if (!isValid() || !simulation_)
133 eve::DiagnosticCode::PreconditionViolation, "Cannot snapshot a destroyed or uninitialized 3D physics world",
134 "physics.world3d.snapshot"));
135 auto schema = snapshotSchema(kWorld3DSchema);
136 if (!schema) return eve::Result<eve::SnapshotEnvelope>::failure(schema.status());
137 const auto observation = simulationObservation();
138 std::vector<Body3D*> bodies(bodies_.begin(), bodies_.end());
139 auto couplings = WorldSnapshotAccess::captureCouplings3D(*this);
140 if (!couplings) return Result<SnapshotEnvelope>::failure(couplings.status());
141 auto payload = make3DPayload(*this, bodies, std::vector<Shape3D*>(shapes_.begin(), shapes_.end()),
142 std::vector<Joint3D*>(joints_.begin(), joints_.end()));
143 payload.set("couplings", std::move(couplings).takeValue());
145 std::string(kWorld3DType), std::move(schema).takeValue(), eve::SchemaVersion(kSnapshotVersion), instanceId_,
146 eve::Revision(observation.stepCount), simulationTick(), std::move(payload), hashProvider);
147}
148
150 const eve::SnapshotHashProvider& hashProvider) {
151 if (rigidBackendKind_ != RigidBackend3D::Box3D) return restorePortable(snapshotValue, hashProvider);
152 if (couplingStepActive_)
154 "Cannot restore while stepping", "physics.world3d.restore"));
155 if (!isValid() || !simulation_)
157 eve::DiagnosticCode::PreconditionViolation, "Cannot restore a destroyed or uninitialized 3D physics world",
158 "physics.world3d.restore"));
159 auto verified = eve::verifySnapshotEnvelope(snapshotValue, hashProvider);
160 if (!verified) return verified;
161 auto envelope = checkEnvelope(snapshotValue, kWorld3DType, kWorld3DSchema);
162 if (!envelope) return envelope;
163 const bool legacyV1 = snapshotValue.schemaVersion.value() == 1;
164 if (!legacyV1 && (snapshotValue.instanceId.isNil() || snapshotValue.instanceId != instanceId_))
167 "3D physics snapshot belongs to a different world instance", "snapshot.instanceId"));
168 eve::Value migratedPayload = snapshotValue.payload;
169 if (legacyV1) {
170 auto* migrated = migratedPayload.getIf<eve::Value::Object>();
171 if (!migrated)
173 "v1 3D physics payload is malformed", "payload"));
174 auto legacyShapes = shapesTopologyValue(std::vector<Shape3D*>(shapes_.begin(), shapes_.end()));
175 for (auto& shape : *legacyShapes.getIf<Value::Array>()) {
176 shape.getIf<Value::Object>()->erase("localTransform");
177 shape.getIf<Value::Object>()->erase("contact");
178 }
179 migrated->emplace("shapes", std::move(legacyShapes));
180 auto legacyJoints = jointsTopologyValue(std::vector<Joint3D*>(joints_.begin(), joints_.end()));
181 for (auto& joint : *legacyJoints.getIf<Value::Array>()) joint.getIf<Value::Object>()->erase("parameters");
182 migrated->emplace("joints", std::move(legacyJoints));
183 const eve::Value* bodyValues = field(*migrated, "bodies");
184 if (!bodyValues || bodyValues->arraySize() != bodies_.size())
187 "v1 snapshot requires topology-compatible live bodies", "payload.bodies"));
188 }
189 if (snapshotValue.schemaVersion.value() < 3) {
190 auto* legacy = migratedPayload.getIf<Value::Object>();
191 if (!legacy || legacy->contains("couplings"))
193 Diagnostic::error(DiagnosticCode::ParseError, "Legacy snapshot has unexpected transmission fields"));
194 if (legacy->contains("allowSleep"))
196 Diagnostic::error(DiagnosticCode::ParseError, "Legacy world has unexpected dynamics"));
197 legacy->emplace("allowSleep", Value(false));
198 auto* bodyValues = migratedPayload.find("bodies");
199 auto* bodyArray = bodyValues ? bodyValues->getIf<Value::Array>() : nullptr;
200 if (!bodyArray)
202 Diagnostic::error(DiagnosticCode::ParseError, "Legacy bodies must be an array"));
203 const auto defaults = b3DefaultBodyDef();
204 for (auto& body : *bodyArray) {
205 auto* bodyObject = body.getIf<Value::Object>();
206 if (!bodyObject || bodyObject->contains("dynamics"))
208 Diagnostic::error(DiagnosticCode::ParseError, "Legacy body has unexpected dynamics"));
209 bodyObject->emplace("dynamics", Value(Value::Object{{"linearDamping", Value(defaults.linearDamping)},
210 {"angularDamping", Value(defaults.angularDamping)},
211 {"gravityScale", Value(defaults.gravityScale)},
212 {"sleepThreshold", Value(defaults.sleepThreshold)},
213 {"allowSleep", Value(defaults.enableSleep)}}));
214 }
215 legacy->emplace("couplings", Value(Value::Array{}));
216 }
217 const auto* object = migratedPayload.getIf<eve::Value::Object>();
218 if (!object || !hasExactFields(
219 *object, {"bodies", "couplings", "allowSleep", "gravityX", "gravityY", "gravityZ", "joints",
220 "shapes", "tick", "revision", "stepCount", "simulatedDurationNs", "lastDeltaSeconds"}))
222 eve::DiagnosticCode::ParseError, "3D physics snapshot payload has unknown or missing fields", "payload"));
223 auto observation = parseObservation(*object, snapshotValue);
224 if (!observation) return eve::Result<void>::failure(observation.status());
225 auto bodies = parseBodies3D(*object);
226 if (!bodies) return eve::Result<void>::failure(bodies.status());
227 auto gravityX = readFloat(*object, "gravityX");
228 if (!gravityX) return eve::Result<void>::failure(gravityX.status());
229 auto gravityY = readFloat(*object, "gravityY");
230 if (!gravityY) return eve::Result<void>::failure(gravityY.status());
231 auto gravityZ = readFloat(*object, "gravityZ");
232 if (!gravityZ) return eve::Result<void>::failure(gravityZ.status());
233 const eve::Value* snapshotShapes = field(*object, "shapes");
234 const eve::Value* snapshotJoints = field(*object, "joints");
235 if (!snapshotShapes || !snapshotShapes->isArray() || !snapshotJoints || !snapshotJoints->isArray())
237 eve::DiagnosticCode::ParseError, "3D physics snapshot topology fields must be arrays", "payload.shapes"));
238 std::set<int> snapshotIds;
239 auto matched = matchBodyIds(bodies.value(), snapshotIds);
240 if (!matched) return matched;
241 auto handleRefresh =
242 prepareRuntimeHandleRefresh(bodies.value().size(), snapshotShapes->arraySize(), snapshotJoints->arraySize());
243 if (!handleRefresh) return handleRefresh;
244 auto allowSleep = readBool(*object, "allowSleep");
245 if (!allowSleep) return Result<void>::failure(allowSleep.status());
246 auto prepared = prepareWorld3D(bodies.value(), *snapshotShapes->getIf<eve::Value::Array>(),
247 *snapshotJoints->getIf<eve::Value::Array>(), gravityX.value(), gravityY.value(),
248 gravityZ.value(), observation.value().value, instanceId_,
249 snapshotValue.schemaVersion.value() < 3, allowSleep.value());
250 if (!prepared) return eve::Result<void>::failure(prepared.status());
251 auto preparedLinks = WorldSnapshotAccess::prepareRuntimeLinks(*this, *prepared.value());
252 if (!preparedLinks) return preparedLinks;
253 const auto* couplings = field(*object, "couplings")->getIf<Value::Array>();
254 if (!couplings)
255 return Result<void>::failure(Diagnostic::error(DiagnosticCode::ParseError, "Couplings must be an array"));
256 auto preparedCouplings = WorldSnapshotAccess::restoreCouplings3D(*prepared.value(), *couplings);
257 if (!preparedCouplings) return preparedCouplings;
258 auto restoredObservation = simulation_->restoreObservation(observation.value().value);
259 if (!restoredObservation) return restoredObservation;
260 WorldSnapshotAccess::adopt(*this, *prepared.value());
261 ++queryEpoch_;
264}
265
266eve::Result<void> World::prepareRuntimeHandleRefresh(std::size_t incomingBodyCount) const {
267 const auto available =
268 static_cast<std::uint64_t>(PhysicsBodyHandle::invalidIndex) - nextBodyHandleIndex_;
269 if (incomingBodyCount > available)
271 eve::DiagnosticCode::InvariantViolation, "2D physics body handle space cannot represent restored links",
272 "physics.world.restore.handles"));
274}
275
276void World::refreshRuntimeHandlesAfterRestore() {
277 for (Body* body : bodies_)
278 if (body && body->isValid()) body->runtimeHandle_ = nextBodyRuntimeHandle();
279}
280
281eve::Result<void> World3D::prepareRuntimeHandleRefresh(std::size_t bodyCount, std::size_t shapeCount,
282 std::size_t jointCount) const {
283 const auto bodyAvailable = static_cast<std::uint64_t>(PhysicsBodyHandle::invalidIndex) - nextBodyHandleIndex_;
284 const auto shapeAvailable = static_cast<std::uint64_t>(PhysicsShapeHandle::invalidIndex) - nextShapeHandleIndex_;
285 const auto jointAvailable = static_cast<std::uint64_t>(PhysicsJointHandle::invalidIndex) - nextJointHandleIndex_;
286 if (queryEpoch_ == UINT64_MAX || bodyCount > bodyAvailable || shapeCount > shapeAvailable ||
287 jointCount > jointAvailable)
289 eve::DiagnosticCode::InvariantViolation, "3D physics handle space cannot represent restored links",
290 "physics.world3d.restore.handles"));
292}
293
294void World3D::refreshRuntimeHandlesAfterRestore() {
295 ++queryEpoch_;
296 shapeRecords_.clear();
297 shapeHandles_.clear();
298 shapeRawHandles_.clear();
299 jointHandles_.clear();
300 for (Body3D* body : bodies_)
301 if (body && body->isValid()) body->runtimeHandle_ = nextBodyRuntimeHandle();
302 for (Shape3D* shape : shapes_) {
303 if (!shape || !shape->isValid()) continue;
304 shape->runtimeHandle_ = nextShapeRuntimeHandle();
305 indexShapeHandle(shape);
306 }
307 for (Joint3D* joint : joints_) {
308 if (!joint || !joint->isValid()) continue;
309 joint->runtimeHandle_ = nextJointRuntimeHandle();
310 jointHandles_[joint->runtimeHandle_] = joint;
311 }
312}
313
314} // namespace eve::physics
Value::Object payload
std::vector< Value > defaults
Definition ECS.cpp:49
ShaderImageInput shape
std::string body
Backend-neutral, observable fixed-step contract for physics domains.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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 constexpr index_type invalidIndex
Reserved index value shared by all invalid handles.
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
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
std::vector< Value > Array
Definition Value.h:33
std::size_t arraySize() const
Return the number of array elements.
Definition Value.cpp:220
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:175
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
PhysicsJointHandle nextJointRuntimeHandle()
Internal: next generation-qualified joint handle.
Definition World3D.cpp:416
SimulationObservation simulationObservation() const noexcept
Snapshot of completed backend steps and logical simulation time.
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures a versioned, integrity-checked 3D world snapshot.
eve::Result< void > restore(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified snapshot without exposing partial state.
PhysicsBodyHandle nextBodyRuntimeHandle()
Internal: next generation-qualified body handle.
Definition World3D.cpp:404
friend class Body3D
Definition World3D.h:1058
bool isValid() const
True while the underlying Box3D world is alive.
Definition World3D.cpp:239
eve::SimulationTick simulationTick() const noexcept
Current deterministic tick; save data should persist this value.
Definition World3D.h:134
friend class Joint3D
Definition World3D.h:1059
void clearContactEvents()
Clears all contact and trigger buffers before the next step.
PhysicsShapeHandle nextShapeRuntimeHandle()
Internal: next generation-qualified shape handle.
Definition World3D.cpp:410
friend class Shape3D
Definition World3D.h:1063
SimulationObservation simulationObservation() const noexcept
Snapshot of completed backend steps and logical simulation time.
Definition World.cpp:433
eve::SimulationTick simulationTick() const noexcept
Current deterministic tick; save data should persist this value.
Definition World.h:126
friend class Body
Definition World.h:457
eve::Result< void > restore(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified snapshot without exposing partial state.
b2World * raw()
Exposes the underlying Box2D world for tightly-scoped backend integration.
Definition World.h:417
PhysicsBodyHandle nextBodyRuntimeHandle()
Definition World.cpp:472
bool isValid() const
True while the underlying Box2D world is alive.
Definition World.h:332
void clearContactEvents()
Clears collected begin/end contact and impact event buffers.
Definition World.cpp:760
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures a versioned, integrity-checked world snapshot.
constexpr std::string_view kWorld2DSchema
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
eve::Result< std::unique_ptr< World3D > > prepareWorld3D(const std::vector< Body3DState > &states, const eve::Value::Array &shapes, const eve::Value::Array &joints, float gravityX, float gravityY, float gravityZ, const SimulationObservation &observation, eve::PersistentId instanceId, bool legacyParameters, bool allowSleep)
constexpr std::uint64_t kSnapshotVersion
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...
eve::Value shapesTopologyValue(const std::vector< Shape3D * > &shapes)
eve::Value make2DPayload(const World &world, const std::vector< Body * > &bodies)
constexpr std::string_view kWorld3DSchema
eve::Value jointsTopologyValue(const std::vector< Joint3D * > &joints)
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
constexpr std::string_view kWorld3DType
eve::Value make3DPayload(const World3D &world, const std::vector< Body3D * > &bodies, const std::vector< Shape3D * > &shapes, const std::vector< Joint3D * > &joints)
constexpr std::string_view kWorld2DType
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
eve::Result< void > matchBodyIds(const std::vector< BodyState > &states, std::set< int > &ids)
eve::Result< eve::LogicalId > snapshotSchema(std::string_view text)
Result< void > migratePlanarV2(Value &payload)
Migrate previous schema with explicit defaults for previously omitted state.
eve::Result< std::unique_ptr< World > > prepareWorld2D(const std::vector< Body2DState > &states, float gravityX, float gravityY, float meter, const SimulationObservation &observation, eve::PersistentId instanceId)
eve::Result< std::vector< Body2DState > > parseBodies2D(const eve::Value::Object &object)
eve::Result< void > checkEnvelope(const eve::SnapshotEnvelope &snapshot, std::string_view type, std::string_view schema)
eve::Result< std::vector< Body3DState > > parseBodies3D(const eve::Value::Object &object)
constexpr std::uint64_t kSnapshot2DVersion
eve::Result< ObservationState > parseObservation(const eve::Value::Object &object, const eve::SnapshotEnvelope &snapshot)
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
Result< void > verifySnapshotEnvelope(const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Verify an envelope's content hash without modifying it.
Definition Snapshot.cpp:63
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
SchemaVersion schemaVersion
Definition Snapshot.h:49
PersistentId instanceId
Definition Snapshot.h:50
static Result< void > restoreJoints2D(World &candidate, const Value::Array &joints, std::uint32_t firstHandleIndex)
Rebuild validated joint definitions inside a detached candidate, allocating fresh runtime handles.
static Result< void > restoreCouplings3D(World3D &world, const Value::Array &values)
Rebuild transmissions after candidate handles and native joints are ready.
static Result< void > prepareRuntimeLinks(const World3D &live, World3D &prepared)
Allocate fresh 3D links entirely in the detached candidate before publishing topology.
static Result< Value > captureCouplings3D(const World3D &world)
Capture transmissions with stable source ids and current unwrapped phase.
static Result< Value > captureJoints2D(const World &world)
Capture owning joint definitions; rejects unregistered backend joints.
static void adopt(World &live, World &prepared)