载入中...
搜索中...
未找到
JointSnapshotCodec.cpp
浏览该文件的文档.
4
5#include <array>
6#include <map>
7
8namespace eve::physics {
9namespace {
10using namespace snapshot_detail;
11using Object = Value::Object;
12template <class T>
13Result<T> malformed(const char* message) {
15}
16void anchors(Object& o, b2Vec2 a, b2Vec2 b) {
17 o.emplace("ax", Value(a.x));
18 o.emplace("ay", Value(a.y));
19 o.emplace("bx", Value(b.x));
20 o.emplace("by", Value(b.y));
21}
22void spring(Object& o, float frequency, float damping) {
23 o.emplace("frequency", Value(frequency));
24 o.emplace("damping", Value(damping));
25}
26void motor(Object& o, bool enabled, float speed, float maximum) {
27 o.emplace("motorEnabled", Value(enabled));
28 o.emplace("speed", Value(speed));
29 o.emplace("maximum", Value(maximum));
30}
31template <class J>
32void limits(Object& o, const J& j) {
33 o.emplace("limitEnabled", Value(j.IsLimitEnabled()));
34 o.emplace("lower", Value(j.GetLowerLimit()));
35 o.emplace("upper", Value(j.GetUpperLimit()));
36}
37Result<std::vector<float>> parameters(const Object& data, std::initializer_list<std::string_view> names) {
38 if (!hasExactFields(data, names))
39 return malformed<std::vector<float>>("Joint parameters have unknown or missing fields");
40 std::vector<float> result;
41 for (auto name : names) {
42 if (name == "motorEnabled" || name == "limitEnabled") {
43 auto value = readBool(data, name);
44 if (!value) return Result<std::vector<float>>::failure(value.status());
45 result.push_back(value.value() ? 1.f : 0.f);
46 } else {
47 auto value = readFloat(data, name);
48 if (!value) return Result<std::vector<float>>::failure(value.status());
49 result.push_back(value.value());
50 }
51 }
52 return Result<std::vector<float>>::success(std::move(result));
53}
54Result<int> positiveId(const Object& o, std::string_view name) {
55 auto id = readInt64(o, name);
56 if (!id) return Result<int>::failure(id.status());
57 if (id.value() <= 0 || id.value() >= std::numeric_limits<int>::max())
58 return malformed<int>("Joint topology id is out of range");
59 return Result<int>::success(static_cast<int>(id.value()));
60}
61int bodyId(b2Body& body) {
62 const auto* wrapper = static_cast<const Body*>(body.GetUserData());
63 return wrapper ? wrapper->getId() : -1;
64}
65} // namespace
66
68 if (static_cast<std::size_t>(world.raw()->GetJointCount()) != world.joints_.size())
70 DiagnosticCode::Unsupported, "Snapshot cannot capture unmanaged backend joints", "physics.world.snapshot"));
71 std::vector<Joint2D*> sorted(world.joints_.begin(), world.joints_.end());
72 std::sort(sorted.begin(), sorted.end(), [](auto* a, auto* b) { return a->getId() < b->getId(); });
74 for (const auto* wrapper : sorted) {
75 auto& raw = *wrapper->joint_;
76 Object data;
77 switch (wrapper->kind_) {
79 const auto& j = static_cast<const b2RevoluteJoint&>(raw);
80 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
81 data.emplace("referenceAngle", Value(j.GetReferenceAngle()));
82 limits(data, j);
83 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorTorque());
84 break;
85 }
87 const auto& j = static_cast<const b2PrismaticJoint&>(raw);
88 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
89 data.emplace("referenceAngle", Value(j.GetReferenceAngle()));
90 data.emplace("axisX", Value(j.GetLocalAxisA().x));
91 data.emplace("axisY", Value(j.GetLocalAxisA().y));
92 limits(data, j);
93 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorForce());
94 break;
95 }
97 const auto& j = static_cast<const b2DistanceJoint&>(raw);
98 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
99 data.emplace("length", Value(j.GetLength()));
100 spring(data, j.GetFrequency(), j.GetDampingRatio());
101 break;
102 }
103 case Joint2DKind::Wheel: {
104 const auto& j = static_cast<const b2WheelJoint&>(raw);
105 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
106 data.emplace("axisX", Value(j.GetLocalAxisA().x));
107 data.emplace("axisY", Value(j.GetLocalAxisA().y));
108 spring(data, j.GetSpringFrequencyHz(), j.GetSpringDampingRatio());
109 motor(data, j.IsMotorEnabled(), j.GetMotorSpeed(), j.GetMaxMotorTorque());
110 break;
111 }
112 case Joint2DKind::Weld: {
113 const auto& j = static_cast<const b2WeldJoint&>(raw);
114 anchors(data, j.GetLocalAnchorA(), j.GetLocalAnchorB());
115 data.emplace("referenceAngle", Value(j.GetReferenceAngle()));
116 spring(data, j.GetFrequency(), j.GetDampingRatio());
117 break;
118 }
119 case Joint2DKind::Pulley: {
120 const auto& j = static_cast<const b2PulleyJoint&>(raw);
121 anchors(data, {wrapper->pulleyLocalA_.x, wrapper->pulleyLocalA_.y},
122 {wrapper->pulleyLocalB_.x, wrapper->pulleyLocalB_.y});
123 data.emplace("groundAx", Value(j.GetGroundAnchorA().x));
124 data.emplace("groundAy", Value(j.GetGroundAnchorA().y));
125 data.emplace("groundBx", Value(j.GetGroundAnchorB().x));
126 data.emplace("groundBy", Value(j.GetGroundAnchorB().y));
127 data.emplace("lengthA", Value(j.GetLengthA()));
128 data.emplace("lengthB", Value(j.GetLengthB()));
129 data.emplace("ratio", Value(j.GetRatio()));
130 break;
131 }
132 case Joint2DKind::Motor: {
133 const auto& j = static_cast<const b2MotorJoint&>(raw);
134 data.emplace("offsetX", Value(j.GetLinearOffset().x));
135 data.emplace("offsetY", Value(j.GetLinearOffset().y));
136 data.emplace("angle", Value(j.GetAngularOffset()));
137 data.emplace("force", Value(j.GetMaxForce()));
138 data.emplace("torque", Value(j.GetMaxTorque()));
139 data.emplace("correction", Value(j.GetCorrectionFactor()));
140 break;
141 }
142 case Joint2DKind::Gear: {
143 const auto& j = static_cast<const b2GearJoint&>(raw);
144 int first = -1, second = -1;
145 for (const auto* source : sorted) {
146 if (source->handle_ == wrapper->firstSource_) first = source->getId();
147 if (source->handle_ == wrapper->secondSource_) second = source->getId();
148 }
149 if (first < 0 || second < 0) return malformed<Value>("Gear source is missing");
150 data.emplace("first", Value(std::to_string(first)));
151 data.emplace("second", Value(std::to_string(second)));
152 data.emplace("ratio", Value(j.GetRatio()));
153 Value::Array poses;
154 for (float value : wrapper->gearReferencePoses_) poses.emplace_back(value);
155 data.emplace("referencePoses", Value(std::move(poses)));
156 break;
157 }
158 }
159 output.emplace_back(Object{{"id", Value(std::to_string(wrapper->getId()))},
160 {"kind", Value(std::to_string(static_cast<int>(wrapper->kind_)))},
161 {"bodyA", Value(std::to_string(bodyId(*raw.GetBodyA())))},
162 {"bodyB", Value(std::to_string(bodyId(*raw.GetBodyB())))},
163 {"collideConnected", Value(raw.GetCollideConnected())},
164 {"data", Value(std::move(data))}});
165 }
166 return Result<Value>::success(Value(std::move(output)));
167}
168
170 std::uint32_t firstHandleIndex) try {
171 if (values.size() > static_cast<std::uint64_t>(PhysicsJointHandle::invalidIndex) - firstHandleIndex)
172 return malformed<void>("Restored joint handles exceed available identity space");
173 w.nextJointHandleIndex_ = firstHandleIndex;
174 struct Record {
175 int id, a, b;
177 bool collide;
178 const Object* data;
179 };
180 std::vector<Record> records;
181 std::set<int> ids;
182 std::map<int, Body*> bodies;
183 std::map<int, Joint2D*> joints;
184 for (auto* body : w.bodies_) bodies.emplace(body->getId(), body);
185 for (const auto& value : values) {
186 const auto* o = value.getIf<Object>();
187 if (!o || !hasExactFields(*o, {"id", "kind", "bodyA", "bodyB", "collideConnected", "data"}))
188 return malformed<void>("Joint record has unknown or missing fields");
189 auto id = positiveId(*o, "id");
190 if (!id) return Result<void>::failure(id.status());
191 auto a = positiveId(*o, "bodyA");
192 if (!a) return Result<void>::failure(a.status());
193 auto b = positiveId(*o, "bodyB");
194 if (!b) return Result<void>::failure(b.status());
195 auto kind = readInt64(*o, "kind");
196 if (!kind) return Result<void>::failure(kind.status());
197 auto collide = readBool(*o, "collideConnected");
198 if (!collide) return Result<void>::failure(collide.status());
199 const auto* data = field(*o, "data")->getIf<Object>();
200 if (!data || !ids.insert(id.value()).second || !bodies.contains(a.value()) || !bodies.contains(b.value()) ||
201 a.value() == b.value() || kind.value() < 0 || kind.value() > static_cast<int>(Joint2DKind::Motor))
202 return malformed<void>("Invalid joint kind, duplicated id or missing/distinct endpoint");
203 if (bodies.at(a.value())->raw()->GetType() != b2_dynamicBody &&
204 bodies.at(b.value())->raw()->GetType() != b2_dynamicBody)
205 return malformed<void>("Joint requires at least one dynamic endpoint");
206 records.push_back(
207 {id.value(), a.value(), b.value(), static_cast<Joint2DKind>(kind.value()), collide.value(), data});
208 }
209 // Gear dependencies are restricted to revolute/prismatic; normals always precede gears regardless of input order.
210 std::sort(records.begin(), records.end(), [](const Record& a, const Record& b) {
211 if ((a.kind == Joint2DKind::Gear) != (b.kind == Joint2DKind::Gear)) return a.kind != Joint2DKind::Gear;
212 return a.id < b.id;
213 });
214 auto adopt = [&](const Record& record, b2JointDef& def) -> Joint2D& {
215 def.bodyA = bodies.at(record.a)->raw();
216 def.bodyB = bodies.at(record.b)->raw();
217 def.collideConnected = record.collide;
218 auto* raw = w.raw()->CreateJoint(&def);
219 auto owned = std::unique_ptr<Joint2D>(
220 new Joint2D(w, *raw, record.kind, PhysicsJointHandle(w.nextJointHandleIndex_++, 1u)));
221 owned->id_ = record.id;
222 auto& result = *owned;
223 w.joints_.insert(owned.get());
224 w.restoredJoints2D_.push_back(std::move(owned));
225 joints.emplace(record.id, &result);
226 return result;
227 };
228 for (const auto& r : records) {
229 const auto& o = *r.data;
230 switch (r.kind) {
231 case Joint2DKind::Motor: {
232 auto parsed = parameters(o, {"offsetX", "offsetY", "angle", "force", "torque", "correction"});
233 if (!parsed) return Result<void>::failure(parsed.status());
234 const auto& p = parsed.value();
235 if (p[3] < 0 || p[4] < 0 || p[5] < 0 || p[5] > 1) return malformed<void>("Invalid motor parameters");
236 b2MotorJointDef d;
237 d.linearOffset.Set(p[0], p[1]);
238 d.angularOffset = p[2];
239 d.maxForce = p[3];
240 d.maxTorque = p[4];
241 d.correctionFactor = p[5];
242 adopt(r, d);
243 break;
244 }
246 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "referenceAngle", "limitEnabled", "lower", "upper",
247 "motorEnabled", "speed", "maximum"});
248 if (!parsed) return Result<void>::failure(parsed.status());
249 const auto& p = parsed.value();
250 if (p[6] > p[7] || p[10] < 0) return malformed<void>("Invalid revolute limit/motor parameters");
251 b2RevoluteJointDef d;
252 d.localAnchorA.Set(p[0], p[1]);
253 d.localAnchorB.Set(p[2], p[3]);
254 d.referenceAngle = p[4];
255 d.enableLimit = p[5] != 0;
256 d.lowerAngle = p[6];
257 d.upperAngle = p[7];
258 d.enableMotor = p[8] != 0;
259 d.motorSpeed = p[9];
260 d.maxMotorTorque = p[10];
261 adopt(r, d);
262 break;
263 }
265 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "referenceAngle", "axisX", "axisY", "limitEnabled",
266 "lower", "upper", "motorEnabled", "speed", "maximum"});
267 if (!parsed) return Result<void>::failure(parsed.status());
268 const auto& p = parsed.value();
269 if (p[8] > p[9] || p[12] < 0 || std::abs(std::hypot(p[5], p[6]) - 1.f) > 1e-5f)
270 return malformed<void>("Invalid prismatic axis/limit/motor parameters");
271 b2PrismaticJointDef d;
272 d.localAnchorA.Set(p[0], p[1]);
273 d.localAnchorB.Set(p[2], p[3]);
274 d.referenceAngle = p[4];
275 d.localAxisA.Set(p[5], p[6]);
276 d.enableLimit = p[7] != 0;
277 d.lowerTranslation = p[8];
278 d.upperTranslation = p[9];
279 d.enableMotor = p[10] != 0;
280 d.motorSpeed = p[11];
281 d.maxMotorForce = p[12];
282 adopt(r, d);
283 break;
284 }
286 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "length", "frequency", "damping"});
287 if (!parsed) return Result<void>::failure(parsed.status());
288 const auto& p = parsed.value();
289 if (p[4] <= 0 || p[5] < 0 || p[6] < 0) return malformed<void>("Invalid distance spring parameters");
290 b2DistanceJointDef d;
291 d.localAnchorA.Set(p[0], p[1]);
292 d.localAnchorB.Set(p[2], p[3]);
293 d.length = p[4];
294 d.frequencyHz = p[5];
295 d.dampingRatio = p[6];
296 adopt(r, d);
297 break;
298 }
299 case Joint2DKind::Wheel: {
300 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "axisX", "axisY", "frequency", "damping",
301 "motorEnabled", "speed", "maximum"});
302 if (!parsed) return Result<void>::failure(parsed.status());
303 const auto& p = parsed.value();
304 if (p[6] < 0 || p[7] < 0 || p[10] < 0 || std::abs(std::hypot(p[4], p[5]) - 1.f) > 1e-5f)
305 return malformed<void>("Invalid wheel axis/spring/motor parameters");
306 b2WheelJointDef d;
307 d.localAnchorA.Set(p[0], p[1]);
308 d.localAnchorB.Set(p[2], p[3]);
309 d.localAxisA.Set(p[4], p[5]);
310 d.frequencyHz = p[6];
311 d.dampingRatio = p[7];
312 d.enableMotor = p[8] != 0;
313 d.motorSpeed = p[9];
314 d.maxMotorTorque = p[10];
315 adopt(r, d);
316 break;
317 }
318 case Joint2DKind::Weld: {
319 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "referenceAngle", "frequency", "damping"});
320 if (!parsed) return Result<void>::failure(parsed.status());
321 const auto& p = parsed.value();
322 if (p[5] < 0 || p[6] < 0) return malformed<void>("Invalid weld spring parameters");
323 b2WeldJointDef d;
324 d.localAnchorA.Set(p[0], p[1]);
325 d.localAnchorB.Set(p[2], p[3]);
326 d.referenceAngle = p[4];
327 d.frequencyHz = p[5];
328 d.dampingRatio = p[6];
329 adopt(r, d);
330 break;
331 }
332 case Joint2DKind::Pulley: {
333 auto parsed = parameters(o, {"ax", "ay", "bx", "by", "groundAx", "groundAy", "groundBx", "groundBy",
334 "lengthA", "lengthB", "ratio"});
335 if (!parsed) return Result<void>::failure(parsed.status());
336 const auto& p = parsed.value();
337 if (p[8] <= b2_linearSlop || p[9] <= b2_linearSlop || p[10] <= b2_epsilon ||
338 !std::isfinite(p[8] + p[10] * p[9]))
339 return malformed<void>("Invalid pulley reference length or ratio");
340 b2PulleyJointDef d;
341 d.localAnchorA.Set(p[0], p[1]);
342 d.localAnchorB.Set(p[2], p[3]);
343 d.groundAnchorA.Set(p[4], p[5]);
344 d.groundAnchorB.Set(p[6], p[7]);
345 d.lengthA = p[8];
346 d.lengthB = p[9];
347 d.ratio = p[10];
348 auto& j = adopt(r, d);
349 j.pulleyLocalA_ = {p[0], p[1]};
350 j.pulleyLocalB_ = {p[2], p[3]};
351 break;
352 }
353 case Joint2DKind::Gear: {
354 if (!hasExactFields(o, {"first", "second", "ratio", "referencePoses"}))
355 return malformed<void>("Invalid gear fields");
356 auto first = positiveId(o, "first");
357 if (!first) return Result<void>::failure(first.status());
358 auto second = positiveId(o, "second");
359 if (!second) return Result<void>::failure(second.status());
360 auto ratio = readFloat(o, "ratio");
361 if (!ratio) return Result<void>::failure(ratio.status());
362 if (!joints.contains(first.value()) || !joints.contains(second.value()) ||
363 first.value() == second.value() || ratio.value() == 0 || r.collide)
364 return malformed<void>("Missing gear sources or invalid gear ratio/collision policy");
365 auto* a = joints.at(first.value());
366 auto* b = joints.at(second.value());
367 auto sourceKind = [](Joint2DKind kind) {
369 };
370 if (!sourceKind(a->kind_) || !sourceKind(b->kind_) || bodyId(*a->joint_->GetBodyB()) != r.a ||
371 bodyId(*b->joint_->GetBodyB()) != r.b || a->joint_->GetBodyB()->GetType() != b2_dynamicBody ||
372 b->joint_->GetBodyB()->GetType() != b2_dynamicBody)
373 return malformed<void>("Invalid gear source kinds or endpoints");
374 const auto* poses = field(o, "referencePoses")->getIf<Value::Array>();
375 if (!poses || poses->size() != 12)
376 return malformed<void>("Gear reference poses must contain four XY-angle triples");
377 std::array<float, 12> reference{}, original{};
378 for (std::size_t i = 0; i < reference.size(); ++i) {
379 auto value = readFloat(Object{{"value", (*poses)[i]}}, "value");
380 if (!value) return Result<void>::failure(value.status());
381 reference[i] = value.value();
382 }
383 const std::array<b2Body*, 4> endpoints{a->joint_->GetBodyA(), a->joint_->GetBodyB(),
384 b->joint_->GetBodyA(), b->joint_->GetBodyB()};
385 for (std::size_t i = 0; i < endpoints.size(); ++i) {
386 original[3 * i] = endpoints[i]->GetPosition().x;
387 original[3 * i + 1] = endpoints[i]->GetPosition().y;
388 original[3 * i + 2] = endpoints[i]->GetAngle();
389 for (std::size_t j = 0; j < i; ++j)
390 if (endpoints[i] == endpoints[j] &&
391 (reference[3 * i] != reference[3 * j] || reference[3 * i + 1] != reference[3 * j + 1] ||
392 reference[3 * i + 2] != reference[3 * j + 2]))
393 return malformed<void>("Shared gear endpoint has inconsistent reference poses");
394 }
395 for (std::size_t i = 0; i < endpoints.size(); ++i)
396 endpoints[i]->SetTransform({reference[3 * i], reference[3 * i + 1]}, reference[3 * i + 2]);
397 auto coordinate = [](Joint2D& j) {
398 return j.kind_ == Joint2DKind::Revolute
399 ? static_cast<b2RevoluteJoint*>(j.joint_)->GetJointAngle()
400 : static_cast<b2PrismaticJoint*>(j.joint_)->GetJointTranslation();
401 };
402 if (!std::isfinite(coordinate(*a) + ratio.value() * coordinate(*b)))
403 return malformed<void>("Gear reference constant overflows");
404 b2GearJointDef d;
405 d.joint1 = a->joint_;
406 d.joint2 = b->joint_;
407 d.ratio = ratio.value();
408 auto& j = adopt(r, d);
409 j.firstSource_ = a->handle_;
410 j.secondSource_ = b->handle_;
411 j.gearReferencePoses_ = reference;
412 for (std::size_t i = 0; i < endpoints.size(); ++i)
413 endpoints[i]->SetTransform({original[3 * i], original[3 * i + 1]}, original[3 * i + 2]);
414 break;
415 }
416 }
417 }
418 w.nextJointId_ = ids.empty() ? 1 : *ids.rbegin() + 1;
419 return Result<void>::success();
420} catch (const std::exception& error) {
422 std::string("Planar joint preparation failed: ") + error.what(),
423 "physics.world.restore.prepare"));
424}
425} // namespace eve::physics
float w
Definition AnimClip.cpp:738
std::string output
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
glm::vec4 p[6]
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
double raw
std::string message
float maximum[3]
wgpu::PopErrorScopeStatus status
double r
std::int32_t second
std::int32_t first
float ratio
std::string id
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::string error
Definition Package.cpp:174
std::array< uint32_t, 9 > parameters
std::set< std::string > values
std::string body
Object::Ptr value
float d
std::string_view source
std::string kind
const AssetImportLimits & limits
double spring
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.
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
Definition Joint2D.h:58
b2Joint * raw() const
Internal borrowed solver joint; valid only while this wrapper is valid.
Definition Joint2D.h:160
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
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
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...
bool hasExactFields(const Value::Object &object, std::initializer_list< std::string_view > expected)
Internal exact-field schema predicate.
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.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
Joint2DKind
Closed set of planar mechanical constraints. Gear couples two existing joints.
Definition Joint2D.h:16
bool enabled
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< Value > captureJoints2D(const World &world)
Capture owning joint definitions; rejects unregistered backend joints.
static void adopt(World &live, World &prepared)