载入中...
搜索中...
未找到
PortableWorldSnapshot.cpp
浏览该文件的文档.
1#include "physics/World.h"
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"
9#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
28namespace eve::physics {
29using namespace snapshot_detail;
30
34 object.emplace("bodyId", eve::Value(std::to_string(shape.body_ ? shape.body_->getId() : -1)));
35 object.emplace("id", eve::Value(std::to_string(shape.id_)));
36 object.emplace("kind", eve::Value(shape.getKind()));
37 object.emplace("a", eve::Value(shape.geometry_.a));
38 object.emplace("b", eve::Value(shape.geometry_.b));
39 object.emplace("c", eve::Value(shape.geometry_.c));
40 auto floats = [](const std::vector<float>& source) {
42 values.reserve(source.size());
43 for (float value : source) values.emplace_back(value);
44 return eve::Value(std::move(values));
45 };
46 auto integers = [](const auto& source) {
48 values.reserve(source.size());
49 for (auto value : source) values.emplace_back(std::to_string(static_cast<std::int64_t>(value)));
50 return eve::Value(std::move(values));
51 };
52 object.emplace("hullVertices", floats(shape.geometry_.hullVertices));
53 object.emplace("hullMaxVertices", eve::Value(std::to_string(shape.geometry_.hullMaxVertices)));
54 object.emplace("meshVertices", floats(shape.geometry_.meshVertices));
55 object.emplace("meshIndices", integers(shape.geometry_.meshIndices));
56 object.emplace("meshWeldVertices", eve::Value(shape.geometry_.meshWeldVertices));
57 object.emplace("meshWeldTolerance", eve::Value(shape.geometry_.meshWeldTolerance));
58 object.emplace("meshIdentifyEdges", eve::Value(shape.geometry_.meshIdentifyEdges));
59 object.emplace("meshUseMedianSplit", eve::Value(shape.geometry_.meshUseMedianSplit));
60 object.emplace("meshMaterialIndices", integers(shape.geometry_.meshMaterialIndices));
61 object.emplace("heightValues", floats(shape.geometry_.heightValues));
62 object.emplace("heightCountX", eve::Value(std::to_string(shape.geometry_.heightCountX)));
63 object.emplace("heightCountZ", eve::Value(std::to_string(shape.geometry_.heightCountZ)));
64 object.emplace("heightCellSizeX", eve::Value(shape.geometry_.heightCellSizeX));
65 object.emplace("heightCellSizeZ", eve::Value(shape.geometry_.heightCellSizeZ));
66 object.emplace("heightGlobalMin", eve::Value(shape.geometry_.heightGlobalMin));
67 object.emplace("heightGlobalMax", eve::Value(shape.geometry_.heightGlobalMax));
68 object.emplace("heightClockwise", eve::Value(shape.geometry_.heightClockwise));
69 return eve::Value(std::move(object));
70 }
71
72 static void setBodyId(Body& body, int id) { body.id_ = id; }
73 static void setBodyId(Body3D& body, int id) { body.id_ = id; }
74 static void setShapeId(Shape3D& shape, int id) { shape.id_ = id; }
75 static void setJointId(Joint3D& joint, int id) { joint.id_ = id; }
76 static std::unique_ptr<World3D> makeDetachedWorld3D(float gx, float gy, float gz, eve::PersistentId instanceId,
78 return std::unique_ptr<World3D>(new World3D(gx, gy, gz, false, instanceId, false, backend));
79 }
80 static eve::Result<void> finishPrepared(World& world, int nextId, const SimulationObservation& observation) {
81 world.nextId_ = nextId;
82 auto restored = world.simulation_->restoreObservation(observation);
83 if (!restored) return restored;
84 world.simulationTick_ = observation.lastTick;
86 }
87 static eve::Result<void> finishPrepared(World3D& world, int nextBodyId, int nextShapeId, int nextJointId,
88 const SimulationObservation& observation) {
89 world.nextId_ = nextBodyId;
90 world.nextShapeId_ = nextShapeId;
91 world.nextJointId_ = nextJointId;
92 auto restored = world.simulation_->restoreObservation(observation);
93 if (!restored) return restored;
94 world.simulationTick_ = observation.lastTick;
96 }
97
98 static void adopt(World& live, World& prepared) { live.adoptPreparedTopology(prepared); }
99 static void adopt(World3D& live, World3D& prepared) { live.adoptPreparedTopology(prepared); }
100};
101namespace {
102
103constexpr std::string_view kWorld2DType = "physics.world2d";
104constexpr std::string_view kWorld2DSchema = "physics:world2d";
105constexpr std::string_view kWorld3DType = "physics.world3d";
106constexpr std::string_view kWorld3DSchema = "physics:world3d";
107constexpr std::uint64_t kSnapshotVersion = 2;
108
110 const auto parsed = eve::LogicalId::parse(text);
111 if (!parsed)
113 eve::DiagnosticCode::InvariantViolation, "physics snapshot schema constant is invalid", "schema"));
115}
116
117eve::Result<void> checkEnvelope(const eve::SnapshotEnvelope& snapshot, std::string_view type, std::string_view schema) {
118 if (snapshot.type != type || snapshot.schema.format() != schema)
121 "snapshot type or schema does not belong to this physics world", "snapshot.type"));
122 if (snapshot.schemaVersion.value() != kSnapshotVersion && snapshot.schemaVersion.value() != 1)
125 "physics world snapshot schema version is not supported", "snapshot.schemaVersion"));
127}
128
129struct ObservationState {
130 SimulationObservation value;
131};
132
134 const eve::SnapshotEnvelope& snapshot) {
135 auto tick = readUint64(object, "tick");
136 if (!tick) return eve::Result<ObservationState>::failure(tick.status());
137 auto revision = readUint64(object, "revision");
139 auto stepCount = readUint64(object, "stepCount");
140 if (!stepCount) return eve::Result<ObservationState>::failure(stepCount.status());
141 auto duration = readInt64(object, "simulatedDurationNs");
143 auto lastDelta = readFloat(object, "lastDeltaSeconds");
144 if (!lastDelta) return eve::Result<ObservationState>::failure(lastDelta.status());
145 if (duration.value() < 0 || revision.value() != stepCount.value() || tick.value() != snapshot.tick.value() ||
146 stepCount.value() != snapshot.revision.value()) {
148 eve::DiagnosticCode::Conflict, "physics snapshot payload progress disagrees with its envelope",
149 "payload.observation"));
150 }
151
152 ObservationState result;
153 result.value.stepCount = stepCount.value();
154 result.value.lastTick = eve::SimulationTick(tick.value());
155 result.value.simulatedDuration = eve::Duration::fromNanoseconds(duration.value());
156 result.value.simulatedSeconds = result.value.simulatedDuration.seconds();
157 result.value.lastDeltaSeconds = lastDelta.value();
158 auto valid = detail::validateSimulationObservation(result.value, "physics.snapshot.observation");
161}
162
163struct Body2DState {
164 int id = 0;
165 std::string type;
166 float x = 0.f, y = 0.f, angle = 0.f;
167 float vx = 0.f, vy = 0.f, angularVelocity = 0.f;
168 bool active = false, bullet = false, awake = false, fixedRotation = false;
170};
171
172struct Body3DState {
173 int id = 0;
174 std::string type;
175 float x = 0.f, y = 0.f, z = 0.f;
176 float qx = 0.f, qy = 0.f, qz = 0.f, qw = 1.f;
177 float vx = 0.f, vy = 0.f, vz = 0.f;
178 float wx = 0.f, wy = 0.f, wz = 0.f;
179 bool active = false, bullet = false, awake = false, fixedRotation = false;
180};
181
182bool validBodyType(const std::string& type) { return type == "static" || type == "kinematic" || type == "dynamic"; }
183
185 const auto* object = value.getIf<eve::Value::Object>();
186 if (!object || !hasExactFields(*object, {"active", "angle", "awake", "bullet", "fixedRotation", "fixtures", "id",
187 "type", "vx", "vy", "angularVelocity", "x", "y"}))
190 "2D physics snapshot body has unknown or missing fields", "payload.bodies"));
191 Body2DState state;
192 auto id = readUint64(*object, "id");
193 if (!id || id.value() > static_cast<std::uint64_t>(std::numeric_limits<int>::max()))
195 eve::DiagnosticCode::ParseError, "2D physics snapshot body id is invalid", "payload.bodies.id"));
196 state.id = static_cast<int>(id.value());
197 auto type = readString(*object, "type");
198 if (!type || !validBodyType(type.value()))
200 eve::DiagnosticCode::InvalidArgument, "2D physics snapshot body type is invalid", "payload.bodies.type"));
201 state.type = std::move(type).takeValue();
202 auto x = readFloat(*object, "x");
203 if (!x) return eve::Result<Body2DState>::failure(x.status());
204 state.x = x.value();
205 auto y = readFloat(*object, "y");
206 if (!y) return eve::Result<Body2DState>::failure(y.status());
207 state.y = y.value();
208 auto angle = readFloat(*object, "angle");
209 if (!angle) return eve::Result<Body2DState>::failure(angle.status());
210 state.angle = angle.value();
211 auto vx = readFloat(*object, "vx");
212 if (!vx) return eve::Result<Body2DState>::failure(vx.status());
213 state.vx = vx.value();
214 auto vy = readFloat(*object, "vy");
215 if (!vy) return eve::Result<Body2DState>::failure(vy.status());
216 state.vy = vy.value();
217 auto angular = readFloat(*object, "angularVelocity");
219 state.angularVelocity = angular.value();
220 auto active = readBool(*object, "active");
221 if (!active) return eve::Result<Body2DState>::failure(active.status());
222 state.active = active.value();
223 auto bullet = readBool(*object, "bullet");
224 if (!bullet) return eve::Result<Body2DState>::failure(bullet.status());
225 state.bullet = bullet.value();
226 auto awake = readBool(*object, "awake");
227 if (!awake) return eve::Result<Body2DState>::failure(awake.status());
228 state.awake = awake.value();
229 auto fixed = readBool(*object, "fixedRotation");
230 if (!fixed) return eve::Result<Body2DState>::failure(fixed.status());
231 state.fixedRotation = fixed.value();
232 const eve::Value* fixtures = field(*object, "fixtures");
233 if (!fixtures || !fixtures->isArray())
235 "2D physics snapshot fixtures must be an array",
236 "payload.bodies.fixtures"));
237 state.fixtures = *fixtures;
238 return eve::Result<Body2DState>::success(std::move(state));
239}
240
242 const auto* object = value.getIf<eve::Value::Object>();
243 if (!object || !hasExactFields(*object, {"active", "awake", "bullet", "fixedRotation", "id", "type", "x", "y", "z",
244 "qx", "qy", "qz", "qw", "vx", "vy", "vz", "wx", "wy", "wz"}))
247 "3D physics snapshot body has unknown or missing fields", "payload.bodies"));
248 Body3DState state;
249 auto id = readUint64(*object, "id");
250 if (!id || id.value() > static_cast<std::uint64_t>(std::numeric_limits<int>::max()))
252 eve::DiagnosticCode::ParseError, "3D physics snapshot body id is invalid", "payload.bodies.id"));
253 state.id = static_cast<int>(id.value());
254 auto type = readString(*object, "type");
255 if (!type || !validBodyType(type.value()))
257 eve::DiagnosticCode::InvalidArgument, "3D physics snapshot body type is invalid", "payload.bodies.type"));
258 state.type = std::move(type).takeValue();
259#define EV_READ_BODY3D_FLOAT(name) \
260 do { \
261 auto value = readFloat(*object, #name); \
262 if (!value) return eve::Result<Body3DState>::failure(value.status()); \
263 state.name = value.value(); \
264 } while (false)
278#undef EV_READ_BODY3D_FLOAT
279 const double quaternionLengthSquared =
280 static_cast<double>(state.qx) * state.qx + static_cast<double>(state.qy) * state.qy +
281 static_cast<double>(state.qz) * state.qz + static_cast<double>(state.qw) * state.qw;
282 if (!(quaternionLengthSquared > 1e-16))
284 "3D physics snapshot rotation must be non-zero",
285 "payload.bodies.rotation"));
286#define EV_READ_BODY3D_BOOL(name) \
287 do { \
288 auto value = readBool(*object, #name); \
289 if (!value) return eve::Result<Body3DState>::failure(value.status()); \
290 state.name = value.value(); \
291 } while (false)
296#undef EV_READ_BODY3D_BOOL
297 return eve::Result<Body3DState>::success(std::move(state));
298}
299
300eve::Value bodyValue(const Body& body) {
302 object.emplace("active", eve::Value(body.isActive()));
303 object.emplace("angle", eve::Value(body.getAngle()));
304 object.emplace("awake", eve::Value(body.isAwake()));
305 object.emplace("bullet", eve::Value(body.isBullet()));
306 object.emplace("fixedRotation", eve::Value(body.isFixedRotation()));
307 object.emplace("id", eve::Value(std::to_string(body.getId())));
308 object.emplace("type", eve::Value(body.getType()));
309 object.emplace("vx", eve::Value(body.getLinearVelocityX()));
310 object.emplace("vy", eve::Value(body.getLinearVelocityY()));
311 object.emplace("angularVelocity", eve::Value(body.getAngularVelocity()));
312 object.emplace("x", eve::Value(body.getX()));
313 object.emplace("y", eve::Value(body.getY()));
314 return eve::Value(std::move(object));
315}
316
317eve::Value bodyValue(const Body3D& body) {
319 object.emplace("active", eve::Value(body.isActive()));
320 object.emplace("awake", eve::Value(body.isAwake()));
321 object.emplace("bullet", eve::Value(body.isBullet()));
322 object.emplace("fixedRotation", eve::Value(body.isFixedRotation()));
323 object.emplace("id", eve::Value(std::to_string(body.getId())));
324 object.emplace("type", eve::Value(body.getType()));
325 object.emplace("x", eve::Value(body.getX()));
326 object.emplace("y", eve::Value(body.getY()));
327 object.emplace("z", eve::Value(body.getZ()));
328 object.emplace("qx", eve::Value(body.getRotX()));
329 object.emplace("qy", eve::Value(body.getRotY()));
330 object.emplace("qz", eve::Value(body.getRotZ()));
331 object.emplace("qw", eve::Value(body.getRotW()));
332 object.emplace("vx", eve::Value(body.getLinearVelocityX()));
333 object.emplace("vy", eve::Value(body.getLinearVelocityY()));
334 object.emplace("vz", eve::Value(body.getLinearVelocityZ()));
335 object.emplace("wx", eve::Value(body.getAngularVelocityX()));
336 object.emplace("wy", eve::Value(body.getAngularVelocityY()));
337 object.emplace("wz", eve::Value(body.getAngularVelocityZ()));
338 return eve::Value(std::move(object));
339}
340
343 const b2Body* rawBody = body.raw();
344 for (const b2Fixture* fixture = rawBody ? rawBody->GetFixtureList() : nullptr; fixture;
345 fixture = fixture->GetNext()) {
347 const b2Shape* shape = fixture->GetShape();
348 object.emplace("type", eve::Value(std::to_string(static_cast<int>(shape->GetType()))));
349 object.emplace("radius", eve::Value(shape->m_radius));
351 switch (shape->GetType()) {
352 case b2Shape::e_circle: {
353 const auto* circle = static_cast<const b2CircleShape*>(shape);
354 geometry.emplace_back(circle->m_p.x);
355 geometry.emplace_back(circle->m_p.y);
356 break;
357 }
358 case b2Shape::e_polygon: {
359 const auto* polygon = static_cast<const b2PolygonShape*>(shape);
360 for (int index = 0; index < polygon->m_count; ++index) {
361 geometry.emplace_back(polygon->m_vertices[index].x);
362 geometry.emplace_back(polygon->m_vertices[index].y);
363 }
364 break;
365 }
366 case b2Shape::e_chain: {
367 const auto* chain = static_cast<const b2ChainShape*>(shape);
368 for (int index = 0; index < chain->m_count; ++index) {
369 geometry.emplace_back(chain->m_vertices[index].x);
370 geometry.emplace_back(chain->m_vertices[index].y);
371 }
372 geometry.emplace_back(chain->m_hasPrevVertex);
373 geometry.emplace_back(chain->m_hasNextVertex);
374 break;
375 }
376 case b2Shape::e_edge: {
377 const auto* edge = static_cast<const b2EdgeShape*>(shape);
378 geometry.emplace_back(edge->m_vertex1.x);
379 geometry.emplace_back(edge->m_vertex1.y);
380 geometry.emplace_back(edge->m_vertex2.x);
381 geometry.emplace_back(edge->m_vertex2.y);
382 break;
383 }
384 default: break;
385 }
386 object.emplace("geometry", eve::Value(std::move(geometry)));
387 fixtures.emplace_back(std::move(object));
388 }
389 return eve::Value(std::move(fixtures));
390}
391
392eve::Value shapesTopologyValue(const std::vector<Shape3D*>& shapes) {
393 std::vector<Shape3D*> sorted = shapes;
394 std::sort(sorted.begin(), sorted.end(),
395 [](const Shape3D* left, const Shape3D* right) { return left->getId() < right->getId(); });
397 for (const Shape3D* shape : sorted)
398 if (shape && shape->isValid()) values.push_back(PortableWorldSnapshotAccess::shapeSource(*shape));
399 return eve::Value(std::move(values));
400}
401
402eve::Result<eve::Value> jointsTopologyValue(const std::vector<Joint3D*>& joints) {
403 std::vector<Joint3D*> sorted = joints;
404 std::sort(sorted.begin(), sorted.end(),
405 [](const Joint3D* left, const Joint3D* right) { return left->getId() < right->getId(); });
407 for (const Joint3D* joint : sorted) {
408 if (!joint || !joint->isValid()) continue;
410 object.emplace("id", eve::Value(std::to_string(joint->getId())));
411 object.emplace("kind", eve::Value(joint->getKind()));
412 object.emplace("bodyAId", eve::Value(std::to_string(joint->getBodyAId())));
413 object.emplace("bodyBId", eve::Value(std::to_string(joint->getBodyBId())));
414 auto local = joint->localFrames();
415 if (!local) return eve::Result<eve::Value>::failure(local.status());
416 eve::Value::Array frames;
417 for (float component : local.value().bodyA) frames.emplace_back(component);
418 for (float component : local.value().bodyB) frames.emplace_back(component);
419 object.emplace("localFrames", eve::Value(std::move(frames)));
420 values.emplace_back(std::move(object));
421 }
423}
424
425eve::Value::Object observationFields(const SimulationObservation& observation, eve::SimulationTick tick) {
427 object.emplace("tick", eve::Value(std::to_string(tick.value())));
428 object.emplace("revision", eve::Value(std::to_string(observation.stepCount)));
429 object.emplace("stepCount", eve::Value(std::to_string(observation.stepCount)));
430 object.emplace("simulatedDurationNs", eve::Value(std::to_string(observation.simulatedDuration.nanoseconds())));
431 object.emplace("lastDeltaSeconds", eve::Value(observation.lastDeltaSeconds));
432 return object;
433}
434
435eve::Value make2DPayload(const World& world, const std::vector<Body*>& bodies) {
436 const auto observation = world.simulationObservation();
437 eve::Value::Object object = observationFields(observation, world.simulationTick());
438 object.emplace("gravityX", eve::Value(world.getGravityX()));
439 object.emplace("gravityY", eve::Value(world.getGravityY()));
440 object.emplace("meter", eve::Value(world.getMeter()));
441 std::vector<Body*> sortedBodies = bodies;
442 std::sort(sortedBodies.begin(), sortedBodies.end(),
443 [](const Body* left, const Body* right) { return left->getId() < right->getId(); });
445 values.reserve(sortedBodies.size());
446 for (const Body* body : sortedBodies)
447 if (body && body->isValid()) {
449 value.getIf<eve::Value::Object>()->emplace("fixtures", fixtureTopologyValue(*body));
450 values.push_back(std::move(value));
451 }
452 object.emplace("bodies", eve::Value(std::move(values)));
453 return eve::Value(std::move(object));
454}
455
456eve::Result<eve::Value> make3DPayload(const World3D& world, const std::vector<Body3D*>& bodies,
457 const std::vector<Shape3D*>& shapes, const std::vector<Joint3D*>& joints) {
458 const auto observation = world.simulationObservation();
459 eve::Value::Object object = observationFields(observation, world.simulationTick());
460 object.emplace("gravityX", eve::Value(world.getGravityX()));
461 object.emplace("gravityY", eve::Value(world.getGravityY()));
462 object.emplace("gravityZ", eve::Value(world.getGravityZ()));
463 std::vector<Body3D*> sortedBodies = bodies;
464 std::sort(sortedBodies.begin(), sortedBodies.end(),
465 [](const Body3D* left, const Body3D* right) { return left->getId() < right->getId(); });
467 values.reserve(sortedBodies.size());
468 for (const Body3D* body : sortedBodies)
469 if (body && body->isValid()) values.push_back(bodyValue(*body));
470 object.emplace("bodies", eve::Value(std::move(values)));
471 object.emplace("shapes", shapesTopologyValue(shapes));
472 auto jointValues = jointsTopologyValue(joints);
473 if (!jointValues) return eve::Result<eve::Value>::failure(jointValues.status());
474 object.emplace("joints", std::move(jointValues).takeValue());
475 return eve::Result<eve::Value>::success(eve::Value(std::move(object)));
476}
477
478template <typename BodyState>
479eve::Result<void> matchBodyIds(const std::vector<BodyState>& states, std::set<int>& ids) {
480 for (const BodyState& state : states) {
481 if (!ids.insert(state.id).second)
483 eve::DiagnosticCode::Conflict, "physics snapshot contains a duplicate body id", "payload.bodies.id"));
484 }
486}
487
489 const eve::Value* value = field(object, "bodies");
490 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
491 if (!array)
493 eve::DiagnosticCode::ParseError, "physics snapshot bodies must be an array", "payload.bodies"));
494 std::vector<Body2DState> result;
495 result.reserve(array->size());
496 for (const eve::Value& entry : *array) {
497 auto body = parseBody2D(entry);
498 if (!body) return eve::Result<std::vector<Body2DState>>::failure(body.status());
499 result.push_back(std::move(body).takeValue());
500 }
501 return eve::Result<std::vector<Body2DState>>::success(std::move(result));
502}
503
505 const eve::Value* value = field(object, "bodies");
506 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
507 if (!array)
509 eve::DiagnosticCode::ParseError, "physics snapshot bodies must be an array", "payload.bodies"));
510 std::vector<Body3DState> result;
511 result.reserve(array->size());
512 for (const eve::Value& entry : *array) {
513 auto body = parseBody3D(entry);
514 if (!body) return eve::Result<std::vector<Body3DState>>::failure(body.status());
515 result.push_back(std::move(body).takeValue());
516 }
517 return eve::Result<std::vector<Body3DState>>::success(std::move(result));
518}
519
520eve::Result<std::unique_ptr<World>> prepareWorld2D(const std::vector<Body2DState>& states, float gravityX,
521 float gravityY, float meter,
522 const SimulationObservation& observation,
524 try {
525 auto prepared = std::make_unique<World>(gravityX, gravityY, false, meter, instanceId);
526 int maxId = 0;
527 for (const Body2DState& state : states) {
528 Body* body = prepared->newBody(state.type, state.x, state.y);
530 maxId = std::max(maxId, state.id);
531 const auto* fixtures = state.fixtures.getIf<eve::Value::Array>();
532 for (auto it = fixtures->rbegin(); it != fixtures->rend(); ++it) {
533 const auto* fixture = it->getIf<eve::Value::Object>();
534 if (!fixture || !hasExactFields(*fixture, {"geometry", "radius", "type"}))
535 return eve::Result<std::unique_ptr<World>>::failure(
537 "2D fixture has unknown or missing fields", "payload.bodies.fixtures"));
538 auto type = readInt64(*fixture, "type");
539 auto radius = readFloat(*fixture, "radius");
540 const eve::Value* geometryValue = field(*fixture, "geometry");
541 const auto* geometry = geometryValue ? geometryValue->getIf<eve::Value::Array>() : nullptr;
542 if (!type || !radius || !geometry)
543 return eve::Result<std::unique_ptr<World>>::failure(
544 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "2D fixture geometry is malformed",
545 "payload.bodies.fixtures.geometry"));
546 std::vector<float> values;
547 values.reserve(geometry->size());
548 for (const eve::Value& component : *geometry) {
549 if (!component.isNumeric()) {
550 if (component.isBool()) continue;
552 eve::DiagnosticCode::ParseError, "2D fixture coordinate must be numeric",
553 "payload.bodies.fixtures.geometry"));
554 }
555 values.push_back(
556 static_cast<float>(component.isDouble() ? component.asDouble() : component.asInt()) * meter);
557 }
558 Fixture* created = nullptr;
559 if (type.value() == b2Shape::e_circle && values.size() == 2)
560 created = body->newCircleFixture(radius.value() * meter);
561 else if (type.value() == b2Shape::e_polygon && values.size() >= 6)
562 created = body->newPolygonFixture(values);
563 else if (type.value() == b2Shape::e_chain && values.size() >= 4) {
564 const bool loop = geometry->size() >= 2 && (*geometry)[geometry->size() - 2].isBool() &&
565 (*geometry)[geometry->size() - 2].asBool() && geometry->back().isBool() &&
566 geometry->back().asBool();
567 created = body->newChainFixture(values, loop);
568 }
569 if (!created)
571 eve::DiagnosticCode::Unsupported, "2D fixture shape cannot be reconstructed",
572 "payload.bodies.fixtures.type"));
573 }
574 body->setFixedRotation(state.fixedRotation);
575 body->setBullet(state.bullet);
576 body->setActive(state.active);
577 body->setAngle(state.angle);
578 body->setLinearVelocity(state.vx, state.vy);
579 body->setAngularVelocity(state.angularVelocity);
580 body->setAwake(state.awake);
581 }
582 auto restored = PortableWorldSnapshotAccess::finishPrepared(*prepared, maxId + 1, observation);
583 if (!restored) return eve::Result<std::unique_ptr<World>>::failure(restored.status());
584 return eve::Result<std::unique_ptr<World>>::success(std::move(prepared));
585 } catch (const std::exception& error) {
587 eve::DiagnosticCode::Failed, std::string("2D topology preparation failed: ") + error.what(),
588 "physics.world.restore.prepare"));
589 }
590}
591
593 const eve::Value* value = field(object, name);
594 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
595 if (!array)
597 eve::DiagnosticCode::ParseError, "snapshot field must be an array", std::string(name)));
598 std::vector<float> result;
599 result.reserve(array->size());
600 for (const eve::Value& item : *array) {
601 if (!item.isNumeric())
603 eve::DiagnosticCode::ParseError, "snapshot array item must be numeric", std::string(name)));
604 result.push_back(static_cast<float>(item.isDouble() ? item.asDouble() : item.asInt()));
605 }
606 return eve::Result<std::vector<float>>::success(std::move(result));
607}
608
610 const eve::Value* value = field(object, name);
611 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
612 if (!array)
614 eve::DiagnosticCode::ParseError, "snapshot field must be an array", std::string(name)));
615 std::vector<std::int32_t> result;
616 for (const eve::Value& item : *array) {
617 if (!item.isString())
619 eve::DiagnosticCode::ParseError, "snapshot integer array item must be a string", std::string(name)));
620 std::int64_t parsed = 0;
621 const std::string& text = item.asString();
622 const auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), parsed);
623 if (ec != std::errc{} || end != text.data() + text.size() || parsed < INT32_MIN || parsed > INT32_MAX)
625 eve::DiagnosticCode::ParseError, "snapshot integer array item is invalid", std::string(name)));
626 result.push_back(static_cast<std::int32_t>(parsed));
627 }
628 return eve::Result<std::vector<std::int32_t>>::success(std::move(result));
629}
630
631eve::Result<std::unique_ptr<World3D>> prepareWorld3D(const std::vector<Body3DState>& states,
632 const eve::Value::Array& shapes, const eve::Value::Array& joints,
633 float gravityX, float gravityY, float gravityZ,
634 const SimulationObservation& observation,
636 try {
637 auto prepared =
639 std::unordered_map<int, Body3D*> bodyById;
640 int maxBodyId = 0;
641 for (const Body3DState& state : states) {
642 Body3D* body = prepared->newBody(state.type, state.x, state.y, state.z);
644 bodyById.emplace(state.id, body);
645 maxBodyId = std::max(maxBodyId, state.id);
646 body->setFixedRotation(state.fixedRotation);
647 body->setBullet(state.bullet);
648 body->setActive(state.active);
649 body->setRotation(state.qx, state.qy, state.qz, state.qw);
650 body->setLinearVelocity(state.vx, state.vy, state.vz);
651 body->setAngularVelocity(state.wx, state.wy, state.wz);
652 body->setAwake(state.awake);
653 }
654 int maxShapeId = 0;
655 std::set<int> shapeIds;
656 for (const eve::Value& value : shapes) {
657 const auto* object = value.getIf<eve::Value::Object>();
658 if (!object)
660 eve::DiagnosticCode::ParseError, "3D shape must be an object", "payload.shapes"));
661 auto bodyId = readInt64(*object, "bodyId");
662 auto id = readInt64(*object, "id");
663 auto kind = readString(*object, "kind");
664 auto a = readFloat(*object, "a");
665 auto b = readFloat(*object, "b");
666 auto c = readFloat(*object, "c");
667 if (!bodyId || !id || id.value() <= 0 || id.value() > std::numeric_limits<int>::max() ||
668 !shapeIds.insert(static_cast<int>(id.value())).second || !kind || !a || !b || !c ||
669 !bodyById.contains(static_cast<int>(bodyId.value())))
671 eve::DiagnosticCode::Conflict, "3D shape references invalid identity or source", "payload.shapes"));
672 Body3D* body = bodyById.at(static_cast<int>(bodyId.value()));
673 Shape3D* shape = nullptr;
674 if (kind.value() == "box")
675 shape = body->newBoxShape(a.value() * 2.f, b.value() * 2.f, c.value() * 2.f);
676 else if (kind.value() == "sphere")
677 shape = body->newSphereShape(a.value());
678 else if (kind.value() == "capsule")
679 shape = body->newCapsuleShape(a.value() * 2.f, b.value());
680 else if (kind.value() == "convexHull") {
681 auto vertices = readFloatArray(*object, "hullVertices");
682 auto maxVertices = readInt64(*object, "hullMaxVertices");
683 if (!vertices || !maxVertices)
685 eve::DiagnosticCode::ParseError, "convex hull source is invalid", "payload.shapes"));
686 shape = body->newConvexHullShape(vertices.value(), static_cast<int>(maxVertices.value()));
687 } else if (kind.value() == "triangleMesh") {
688 auto vertices = readFloatArray(*object, "meshVertices");
689 auto indices = readIntArray(*object, "meshIndices");
690 auto weld = readBool(*object, "meshWeldVertices");
691 auto tolerance = readFloat(*object, "meshWeldTolerance");
692 auto edges = readBool(*object, "meshIdentifyEdges");
693 auto median = readBool(*object, "meshUseMedianSplit");
694 if (!vertices || !indices || !weld || !tolerance || !edges || !median)
696 eve::DiagnosticCode::ParseError, "mesh source is invalid", "payload.shapes"));
697 shape = body->newTriangleMeshShape(vertices.value(), indices.value(), weld.value(), tolerance.value(),
698 edges.value(), median.value());
699 } else if (kind.value() == "heightField") {
700 auto heights = readFloatArray(*object, "heightValues");
701 auto cx = readInt64(*object, "heightCountX");
702 auto cz = readInt64(*object, "heightCountZ");
703 auto sx = readFloat(*object, "heightCellSizeX");
704 auto sz = readFloat(*object, "heightCellSizeZ");
705 auto mn = readFloat(*object, "heightGlobalMin");
706 auto mx = readFloat(*object, "heightGlobalMax");
707 auto clockwise = readBool(*object, "heightClockwise");
708 if (!heights || !cx || !cz || !sx || !sz || !mn || !mx || !clockwise)
710 eve::DiagnosticCode::ParseError, "height field source is invalid", "payload.shapes"));
711 shape =
712 body->newHeightFieldShape(static_cast<int>(cx.value()), static_cast<int>(cz.value()), sx.value(),
713 sz.value(), heights.value(), mn.value(), mx.value(), clockwise.value());
714 }
715 if (!shape)
717 eve::DiagnosticCode::Unsupported, "3D shape kind cannot be reconstructed", "payload.shapes.kind"));
718 PortableWorldSnapshotAccess::setShapeId(*shape, static_cast<int>(id.value()));
719 maxShapeId = std::max(maxShapeId, static_cast<int>(id.value()));
720 }
721 int maxJointId = 0;
722 std::set<int> jointIds;
723 for (const eve::Value& value : joints) {
724 const auto* object = value.getIf<eve::Value::Object>();
725 if (!object || !hasExactFields(*object, {"bodyAId", "bodyBId", "id", "kind", "localFrames"}))
727 eve::DiagnosticCode::ParseError, "3D joint has unknown or missing fields", "payload.joints"));
728 auto bodyAId = readInt64(*object, "bodyAId");
729 auto bodyBId = readInt64(*object, "bodyBId");
730 auto id = readInt64(*object, "id");
731 auto kind = readString(*object, "kind");
732 auto frames = readFloatArray(*object, "localFrames");
733 if (!bodyAId || !bodyBId || !id || id.value() <= 0 || id.value() > std::numeric_limits<int>::max() ||
734 !jointIds.insert(static_cast<int>(id.value())).second || !kind || !frames ||
735 frames.value().size() != 14 || !bodyById.contains(static_cast<int>(bodyAId.value())) ||
736 !bodyById.contains(static_cast<int>(bodyBId.value())))
738 eve::DiagnosticCode::Conflict, "3D joint references invalid bodies or frames", "payload.joints"));
739 Body3D* aBody = bodyById.at(static_cast<int>(bodyAId.value()));
740 Body3D* bBody = bodyById.at(static_cast<int>(bodyBId.value()));
741 const auto& f = frames.value();
742 auto anchorAResult = aBody->localToWorldPointOwned(f[0], f[1], f[2]);
743 if (!anchorAResult) return eve::Result<std::unique_ptr<World3D>>::failure(anchorAResult.status());
744 auto anchorBResult = bBody->localToWorldPointOwned(f[7], f[8], f[9]);
745 if (!anchorBResult) return eve::Result<std::unique_ptr<World3D>>::failure(anchorBResult.status());
746 const auto anchorA = anchorAResult.value();
747 const auto anchorB = anchorBResult.value();
748 const glm::quat qa(f[6], f[3], f[4], f[5]);
749 const glm::quat qb(f[13], f[10], f[11], f[12]);
750 const auto worldAxis = [](const Body3D& body, const glm::quat& frame, const glm::vec3& axis) {
751 const auto local = frame * axis;
752 return body.localToWorldVectorOwned(local.x, local.y, local.z);
753 };
754 Joint3D* joint = nullptr;
755 if (kind.value() == "distance") {
756 const glm::vec3 d(anchorB.x - anchorA.x, anchorB.y - anchorA.y, anchorB.z - anchorA.z);
757 const float length = glm::length(d);
758 joint = prepared->newDistanceJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, anchorB.x, anchorB.y,
759 anchorB.z, length);
760 } else if (kind.value() == "revolute") {
761 auto axisResult = worldAxis(*aBody, qa, glm::vec3(0.f, 0.f, 1.f));
762 if (!axisResult) return eve::Result<std::unique_ptr<World3D>>::failure(axisResult.status());
763 const auto axis = axisResult.value();
764 joint =
765 prepared->newRevoluteJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
766 } else if (kind.value() == "prismatic") {
767 auto axisResult = worldAxis(*aBody, qa, glm::vec3(1.f, 0.f, 0.f));
768 if (!axisResult) return eve::Result<std::unique_ptr<World3D>>::failure(axisResult.status());
769 const auto axis = axisResult.value();
770 joint =
771 prepared->newPrismaticJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
772 } else if (kind.value() == "spherical") {
773 auto axisResult = worldAxis(*aBody, qa, glm::vec3(0.f, 0.f, 1.f));
774 if (!axisResult) return eve::Result<std::unique_ptr<World3D>>::failure(axisResult.status());
775 const auto axis = axisResult.value();
776 joint =
777 prepared->newSphericalJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, axis.x, axis.y, axis.z);
778 } else if (kind.value() == "wheel") {
779 auto suspensionResult = worldAxis(*aBody, qa, glm::vec3(1.f, 0.f, 0.f));
780 if (!suspensionResult) return eve::Result<std::unique_ptr<World3D>>::failure(suspensionResult.status());
781 const auto suspension = suspensionResult.value();
782 auto wheelResult = worldAxis(*bBody, qb, glm::vec3(0.f, 0.f, 1.f));
783 if (!wheelResult) return eve::Result<std::unique_ptr<World3D>>::failure(wheelResult.status());
784 const auto wheel = wheelResult.value();
785 joint = prepared->newWheelJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z, suspension.x,
786 suspension.y, suspension.z, wheel.x, wheel.y, wheel.z);
787 } else if (kind.value() == "weld") {
788 joint = prepared->newWeldJoint(aBody, bBody, anchorA.x, anchorA.y, anchorA.z);
789 } else if (kind.value() == "motor") {
790 joint = prepared->newMotorJoint(aBody, bBody);
791 } else if (kind.value() == "parallel") {
792 auto axisResult = worldAxis(*aBody, qa, glm::vec3(0.f, 0.f, 1.f));
793 if (!axisResult) return eve::Result<std::unique_ptr<World3D>>::failure(axisResult.status());
794 const auto axis = axisResult.value();
795 joint = prepared->newParallelJoint(aBody, bBody, axis.x, axis.y, axis.z);
796 } else if (kind.value() == "filter") {
797 joint = prepared->newFilterJoint(aBody, bBody);
798 }
799 if (!joint)
801 eve::DiagnosticCode::Unsupported, "3D joint kind cannot be reconstructed", "payload.joints.kind"));
802 PortableWorldSnapshotAccess::setJointId(*joint, static_cast<int>(id.value()));
803 maxJointId = std::max(maxJointId, static_cast<int>(id.value()));
804 }
805 auto restored = PortableWorldSnapshotAccess::finishPrepared(*prepared, maxBodyId + 1, maxShapeId + 1,
806 maxJointId + 1, observation);
807 if (!restored) return eve::Result<std::unique_ptr<World3D>>::failure(restored.status());
808 return eve::Result<std::unique_ptr<World3D>>::success(std::move(prepared));
809 } catch (const std::exception& error) {
811 eve::DiagnosticCode::Failed, std::string("3D topology preparation failed: ") + error.what(),
812 "physics.world3d.restore.prepare"));
813 }
814}
815
816} // namespace
817
818eve::Result<eve::SnapshotEnvelope> World3D::snapshotPortable(const eve::SnapshotHashProvider& hashProvider) const {
819 if (!isValid() || !simulation_)
821 eve::DiagnosticCode::PreconditionViolation, "Cannot snapshot a destroyed or uninitialized 3D physics world",
822 "physics.world3d.snapshot"));
823 auto schema = snapshotSchema(kWorld3DSchema);
824 if (!schema) return eve::Result<eve::SnapshotEnvelope>::failure(schema.status());
825 const auto observation = simulationObservation();
826 std::vector<Body3D*> bodies(bodies_.begin(), bodies_.end());
827 auto payload = make3DPayload(*this, bodies, std::vector<Shape3D*>(shapes_.begin(), shapes_.end()),
828 std::vector<Joint3D*>(joints_.begin(), joints_.end()));
831 std::string(kWorld3DType), std::move(schema).takeValue(), eve::SchemaVersion(kSnapshotVersion), instanceId_,
832 eve::Revision(observation.stepCount), simulationTick(), std::move(payload).takeValue(), hashProvider);
833}
834
835eve::Result<void> World3D::restorePortable(const eve::SnapshotEnvelope& snapshotValue,
836 const eve::SnapshotHashProvider& hashProvider) {
837 if (!isValid() || !simulation_)
839 eve::DiagnosticCode::PreconditionViolation, "Cannot restore a destroyed or uninitialized 3D physics world",
840 "physics.world3d.restore"));
841 auto verified = eve::verifySnapshotEnvelope(snapshotValue, hashProvider);
842 if (!verified) return verified;
843 auto envelope = checkEnvelope(snapshotValue, kWorld3DType, kWorld3DSchema);
844 if (!envelope) return envelope;
845 const bool legacyV1 = snapshotValue.schemaVersion.value() == 1;
846 if (!legacyV1 && (snapshotValue.instanceId.isNil() || snapshotValue.instanceId != instanceId_))
849 "3D physics snapshot belongs to a different world instance", "snapshot.instanceId"));
850 eve::Value migratedPayload = snapshotValue.payload;
851 if (legacyV1) {
852 auto* migrated = migratedPayload.getIf<eve::Value::Object>();
853 if (!migrated)
855 "v1 3D physics payload is malformed", "payload"));
856 migrated->emplace("shapes", shapesTopologyValue(std::vector<Shape3D*>(shapes_.begin(), shapes_.end())));
857 auto joints = jointsTopologyValue(std::vector<Joint3D*>(joints_.begin(), joints_.end()));
858 if (!joints) return eve::Result<void>::failure(joints.status());
859 migrated->emplace("joints", std::move(joints).takeValue());
860 const eve::Value* bodyValues = field(*migrated, "bodies");
861 if (!bodyValues || bodyValues->arraySize() != bodies_.size())
864 "v1 snapshot requires topology-compatible live bodies", "payload.bodies"));
865 }
866 const auto* object = migratedPayload.getIf<eve::Value::Object>();
867 if (!object || !hasExactFields(*object, {"bodies", "gravityX", "gravityY", "gravityZ", "joints", "shapes", "tick",
868 "revision", "stepCount", "simulatedDurationNs", "lastDeltaSeconds"}))
870 eve::DiagnosticCode::ParseError, "3D physics snapshot payload has unknown or missing fields", "payload"));
871 auto observation = parseObservation(*object, snapshotValue);
872 if (!observation) return eve::Result<void>::failure(observation.status());
873 auto bodies = parseBodies3D(*object);
874 if (!bodies) return eve::Result<void>::failure(bodies.status());
875 auto gravityX = readFloat(*object, "gravityX");
876 if (!gravityX) return eve::Result<void>::failure(gravityX.status());
877 auto gravityY = readFloat(*object, "gravityY");
878 if (!gravityY) return eve::Result<void>::failure(gravityY.status());
879 auto gravityZ = readFloat(*object, "gravityZ");
880 if (!gravityZ) return eve::Result<void>::failure(gravityZ.status());
881 const eve::Value* snapshotShapes = field(*object, "shapes");
882 const eve::Value* snapshotJoints = field(*object, "joints");
883 if (!snapshotShapes || !snapshotShapes->isArray() || !snapshotJoints || !snapshotJoints->isArray())
885 eve::DiagnosticCode::ParseError, "3D physics snapshot topology fields must be arrays", "payload.shapes"));
886 std::set<int> snapshotIds;
887 auto matched = matchBodyIds(bodies.value(), snapshotIds);
888 if (!matched) return matched;
889 auto handleRefresh =
890 prepareRuntimeHandleRefresh(bodies.value().size(), snapshotShapes->getIf<Value::Array>()->size(),
891 snapshotJoints->getIf<Value::Array>()->size());
892 if (!handleRefresh) return handleRefresh;
893 auto prepared = prepareWorld3D(bodies.value(), *snapshotShapes->getIf<eve::Value::Array>(),
894 *snapshotJoints->getIf<eve::Value::Array>(), gravityX.value(), gravityY.value(),
895 gravityZ.value(), observation.value().value, instanceId_, rigidBackendKind_);
896 if (!prepared) return eve::Result<void>::failure(prepared.status());
897 auto restoredObservation = simulation_->restoreObservation(observation.value().value);
898 if (!restoredObservation) return restoredObservation;
899 PortableWorldSnapshotAccess::adopt(*this, *prepared.value());
900 refreshRuntimeHandlesAfterRestore();
903}
904
905
906} // namespace eve::physics
double z
double y
double x
Value::Object payload
bool & active
float duration
std::uint64_t revision
float cx
Definition CardTypes.cpp:36
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
bool awake
b3Vec3 angular
std::string name
Definition ECS.cpp:154
int instanceId
float angularVelocity
ShaderImageInput shape
std::vector< std::uint32_t > indices
HexVec3 left
HexVec3 right
std::int32_t c
JointPoint2D anchorB
float length
JointPoint2D axis
JointPoint2D anchorA
std::string local
std::vector< Edge > edges
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
OceanRenderBackend backend
ssq::Object frame
std::string error
Definition Package.cpp:174
float f
#define EV_READ_BODY3D_BOOL(name)
eve::Value fixtures
#define EV_READ_BODY3D_FLOAT(name)
bool fixedRotation
std::set< std::string > values
std::string body
Object::Ptr value
float d
int created
std::string geometry
std::string text
std::string_view source
size_t end
std::string kind
Backend-neutral, observable fixed-step contract for physics domains.
SimulationTick tick
std::array< double, 2 > vertices[3]
Json object
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
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 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
Id128 public API.
Definition Identity.h:111
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.
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
2D rigid body (Box2D) in pixel-space coordinates. Owned by a World; create shapes with newRectangleFi...
Definition Body.h:21
Script-facing joint owned by a World3D. Legacy scalar/void methods adapt the checked backend contract...
Definition Joint3D.h:27
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
SimulationObservation simulationObservation() const noexcept
Snapshot of completed backend steps and logical simulation time.
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
void clearContactEvents()
Clears all contact and trigger buffers before the next step.
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
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)
eve::Value::Object observationFields(const SimulationObservation &observation, eve::SimulationTick tick)
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
eve::Value fixtureTopologyValue(const Body &body)
constexpr std::string_view kWorld3DType
Result< std::uint64_t > readUint64(const Value::Object &object, std::string_view name)
Reads a required unsigned decimal integer string.
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< std::int64_t > readInt64(const Value::Object &object, std::string_view name)
Reads a required signed decimal integer string.
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
eve::Result< std::vector< float > > readFloatArray(const eve::Value::Object &object, std::string_view name)
Read a finite float array, rejecting missing or malformed elements.
eve::Result< std::vector< std::int32_t > > readIntArray(const eve::Value::Object &object, std::string_view name)
eve::Result< Body2DState > parseBody2D(const eve::Value &value)
eve::Result< void > matchBodyIds(const std::vector< BodyState > &states, std::set< int > &ids)
eve::Result< eve::LogicalId > snapshotSchema(std::string_view text)
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)
eve::Result< Body3DState > parseBody3D(const eve::Value &value)
eve::Value bodyValue(const Body &body)
bool validBodyType(const std::string &type)
Result< std::string > readString(const Value::Object &object, std::string_view name)
Reads a required owning string.
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
RigidBackend3D
Solver identity fixed for the lifetime of one world; independent of CPU/GPU execution.
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
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 void adopt(World3D &live, World3D &prepared)
static void adopt(World &live, World &prepared)
static std::unique_ptr< World3D > makeDetachedWorld3D(float gx, float gy, float gz, eve::PersistentId instanceId, RigidBackend3D backend)
static eve::Result< void > finishPrepared(World &world, int nextId, const SimulationObservation &observation)
static void setBodyId(Body3D &body, int id)
static eve::Result< void > finishPrepared(World3D &world, int nextBodyId, int nextShapeId, int nextJointId, const SimulationObservation &observation)
static void setJointId(Joint3D &joint, int id)
static void setShapeId(Shape3D &shape, int id)
static eve::Value shapeSource(const Shape3D &shape)
Observable backend progress shared by CPU and accelerator providers.
eve::SimulationTick lastTick
Tick of the most recently completed step.