载入中...
搜索中...
未找到
Shape3DContactSnapshot.cpp
浏览该文件的文档.
1#include <cmath>
2#include <limits>
6
7namespace eve::physics {
8namespace {
9using namespace snapshot_detail;
10template <class T>
11Result<T> invalid(const char* message) {
13}
14Value surfaceValue(b3SurfaceMaterial m) {
15 return Value(Value::Object{{"values", Value(Value::Array{Value(m.friction), Value(m.restitution),
16 Value(m.rollingResistance), Value(m.tangentVelocity.x),
17 Value(m.tangentVelocity.y), Value(m.tangentVelocity.z)})},
18 {"id", Value(std::to_string(m.userMaterialId))},
19 {"color", Value(std::to_string(m.customColor))}});
20}
21Result<b3SurfaceMaterial> parseSurface(const Value& value) {
22 const auto* o = value.getIf<Value::Object>();
23 if (!o || !hasExactFields(*o, {"values", "id", "color"}))
24 return invalid<b3SurfaceMaterial>("Invalid surface fields");
25 auto values = readFloatArray(*o, "values");
27 if (values.value().size() != 6 || values.value()[0] < 0 || values.value()[1] < 0 || values.value()[2] < 0)
28 return invalid<b3SurfaceMaterial>("Invalid surface coefficients");
29 auto id = readUint64(*o, "id");
30 if (!id) return Result<b3SurfaceMaterial>::failure(id.status());
31 auto color = readUint64(*o, "color");
32 if (!color) return Result<b3SurfaceMaterial>::failure(color.status());
33 if (color.value() > std::numeric_limits<std::uint32_t>::max())
34 return invalid<b3SurfaceMaterial>("Color out of range");
35 const auto& n = values.value();
37 {n[0], n[1], n[2], {n[3], n[4], n[5]}, id.value(), static_cast<std::uint32_t>(color.value())});
38}
39bool finite(b3Matrix3 m) { return b3IsValidVec3(m.cx) && b3IsValidVec3(m.cy) && b3IsValidVec3(m.cz); }
40} // namespace
43 const auto filter = b3Shape_GetFilter(id);
45 for (int i = 0; shape.geometry_.kind == Shape3D::Kind::TriangleMesh && i < b3Shape_GetMeshMaterialCount(id); ++i)
46 mesh.push_back(surfaceValue(b3Shape_GetMeshSurfaceMaterial(id, i)));
47 return Value(Value::Object{
48 {"density", Value(b3Shape_GetDensity(id))},
49 {"surface", surfaceValue(b3Shape_GetSurfaceMaterial(id))},
50 {"sensor", Value(shape.isSensor())},
51 {"category", Value(std::to_string(filter.categoryBits))},
52 {"mask", Value(std::to_string(filter.maskBits))},
53 {"group", Value(std::to_string(filter.groupIndex))},
54 {"tag", Value(std::to_string(shape.tag_))},
55 {"explosionScale", Value(shape.explosionScale_)},
56 {"sensorEvents", Value(b3Shape_AreSensorEventsEnabled(id))},
57 {"contactEvents", Value(b3Shape_AreContactEventsEnabled(id))},
58 {"preSolveEvents", Value(b3Shape_ArePreSolveEventsEnabled(id))},
59 {"hitEvents", Value(b3Shape_AreHitEventsEnabled(id))},
60 {"contactOverride", Value(shape.contactOverrideFiltering_)},
61 {"oneWay", Value(shape.oneWayEnabled_)},
62 {"oneWayParameters", Value(Value::Array{Value(shape.oneWayLocalNormalX_), Value(shape.oneWayLocalNormalY_),
63 Value(shape.oneWayLocalNormalZ_), Value(shape.oneWayPlaneOffset_),
64 Value(shape.oneWayMargin_), Value(shape.oneWayMinNormalDot_)})},
65 {"meshMaterials", Value(std::move(mesh))}});
66}
68 using namespace snapshot_detail;
69 const auto* value = field(source, "contact");
70 const auto* o = value ? value->getIf<Value::Object>() : nullptr;
71 if (!o || !hasExactFields(*o, {"density", "surface", "sensor", "category", "mask", "group", "tag", "explosionScale",
72 "sensorEvents", "contactEvents", "preSolveEvents", "hitEvents", "contactOverride",
73 "oneWay", "oneWayParameters", "meshMaterials"}))
74 return invalid<float>("Unknown or missing contact fields");
75 auto density = readFloat(*o, "density");
76 if (!density) return Result<float>::failure(density.status());
77 auto explosion = readFloat(*o, "explosionScale");
78 if (!explosion) return Result<float>::failure(explosion.status());
79 if (density.value() < 0 || explosion.value() < 0)
80 return invalid<float>("Density and explosion scale must be nonnegative");
81 auto surface = parseSurface(*field(*o, "surface"));
82 if (!surface) return Result<float>::failure(surface.status());
83 auto category = readUint64(*o, "category");
84 if (!category) return Result<float>::failure(category.status());
85 auto mask = readUint64(*o, "mask");
86 if (!mask) return Result<float>::failure(mask.status());
87 auto group = readInt64(*o, "group");
88 if (!group) return Result<float>::failure(group.status());
89 auto tag = readInt64(*o, "tag");
90 if (!tag) return Result<float>::failure(tag.status());
91 if (group.value() < INT32_MIN || group.value() > INT32_MAX || tag.value() < INT32_MIN || tag.value() > INT32_MAX)
92 return invalid<float>("Group or tag out of range");
93 std::array<bool, 7> flags{};
94 int index = 0;
95 for (const char* name :
96 {"sensor", "sensorEvents", "contactEvents", "preSolveEvents", "hitEvents", "contactOverride", "oneWay"}) {
97 auto parsed = readBool(*o, name);
98 if (!parsed) return Result<float>::failure(parsed.status());
99 flags[index++] = parsed.value();
100 }
101 auto plane = readFloatArray(*o, "oneWayParameters");
102 if (!plane) return Result<float>::failure(plane.status());
103 const auto& p = plane.value();
104 if (p.size() != 6 || !b3IsNormalized({p[0], p[1], p[2]}) || p[4] < 0 || p[5] < -1 || p[5] > 1)
105 return invalid<float>("Invalid one-way plane");
106 const auto* mesh = field(*o, "meshMaterials")->getIf<Value::Array>();
107 if (!mesh) return invalid<float>("Mesh materials must be an array");
108 std::vector<b3SurfaceMaterial> materials;
109 for (const auto& item : *mesh) {
110 auto parsed = parseSurface(item);
111 if (!parsed) return Result<float>::failure(parsed.status());
112 materials.push_back(parsed.value());
113 }
114 const auto* indices = field(source, "meshMaterialIndices")->getIf<Value::Array>();
115 if (!indices) return invalid<float>("Mesh material indices must be an array");
116 std::vector<std::uint8_t> encoded;
117 int required = 1;
118 for (const auto& item : *indices) {
119 Value::Object wrapped{{"index", item}};
120 auto parsed = readInt64(wrapped, "index");
121 if (!parsed) return Result<float>::failure(parsed.status());
122 if (parsed.value() < 0 || parsed.value() > 254) return invalid<float>("Mesh material index out of range");
123 encoded.push_back(static_cast<std::uint8_t>(parsed.value()));
124 required = std::max(required, static_cast<int>(parsed.value()) + 1);
125 }
126 if (shape.geometry_.kind == Shape3D::Kind::TriangleMesh) {
127 if ((!encoded.empty() && encoded.size() != shape.geometry_.meshIndices.size() / 3) ||
128 materials.size() != static_cast<std::size_t>(required))
129 return invalid<float>("Mesh material topology mismatch");
130 } else if (!encoded.empty() || !materials.empty())
131 return invalid<float>("Non-mesh shape has mesh materials");
132 // Candidate geometry still uses construction density. All density assignments are deferred until every recreation
133 // is done.
134 shape.explosionScale_ = explosion.value();
135 shape.tag_ = static_cast<int>(tag.value());
136 shape.contactOverrideFiltering_ = flags[5];
137 shape.hitEventsEnabled_ = flags[4];
138 shape.oneWayEnabled_ = flags[6];
139 shape.oneWayLocalNormalX_ = p[0];
140 shape.oneWayLocalNormalY_ = p[1];
141 shape.oneWayLocalNormalZ_ = p[2];
142 shape.oneWayPlaneOffset_ = p[3];
143 shape.oneWayMargin_ = p[4];
144 shape.oneWayMinNormalDot_ = p[5];
145 if (shape.geometry_.kind == Shape3D::Kind::TriangleMesh) {
146 shape.geometry_.meshMaterialIndices = std::move(encoded);
147 shape.meshMaterials_.clear();
148 for (const auto& m : materials)
149 shape.meshMaterials_.push_back({m.friction,
150 m.restitution,
151 m.rollingResistance,
152 {m.tangentVelocity.x, m.tangentVelocity.y, m.tangentVelocity.z},
153 m.userMaterialId,
154 m.customColor});
155 shape.meshMaterialsDirty_ = true;
156 }
157 shape.recreate(flags[0]);
159 b3Shape_SetSurfaceMaterial(raw, surface.value());
160 b3Shape_SetFilter(raw, {category.value(), mask.value(), static_cast<int>(group.value())}, false);
161 b3Shape_EnableSensorEvents(raw, flags[1]);
162 b3Shape_EnableContactEvents(raw, flags[2]);
163 b3Shape_EnablePreSolveEvents(raw, flags[3]);
164 b3Shape_EnableHitEvents(raw, flags[4]);
165 shape.refreshOneWayWorldData();
166 return Result<float>::success(density.value());
167}
168Result<void> WorldSnapshotAccess::finishShapeMass(World3D& world) {
169 for (auto* body : world.bodies_) {
170 if (b3Body_GetType(eve::physics::box3d::Access::bodyId(*body)) != b3_dynamicBody) continue;
171 std::vector<b3ShapeId> shapes(
172 static_cast<std::size_t>(b3Body_GetShapeCount(eve::physics::box3d::Access::bodyId(*body))));
173 const int count = b3Body_GetShapes(eve::physics::box3d::Access::bodyId(*body), shapes.data(),
174 static_cast<int>(shapes.size()));
175 std::vector<b3MassData> masses;
176 float mass = 0;
177 b3Vec3 center{};
178 for (int i = 0; i < count; ++i) {
179 if (b3Shape_GetDensity(shapes[i]) == 0) continue;
180 const auto data = b3Shape_ComputeMassData(shapes[i]);
181 if (!std::isfinite(data.mass) || data.mass < 0 || !b3IsValidVec3(data.center) || !finite(data.inertia))
182 return invalid<void>("Shape mass or inertia exceeds finite range");
183 mass += data.mass;
184 center = b3MulAdd(center, data.mass, data.center);
185 if (!std::isfinite(mass) || !b3IsValidVec3(center)) return invalid<void>("Body mass accumulation overflow");
186 masses.push_back(data);
187 }
188 if (mass > 0) {
189 const float inverse = 1.f / mass;
190 if (!std::isfinite(inverse)) return invalid<void>("Inverse body mass overflow");
191 center = b3MulSV(inverse, center);
192 }
193 b3Matrix3 inertia = b3Mat3_zero;
194 for (const auto& data : masses) {
195 if (data.mass == 0) continue;
196 inertia = b3AddMM(inertia, b3AddMM(data.inertia, b3Steiner(data.mass, b3Sub(center, data.center))));
197 if (!finite(inertia)) return invalid<void>("Body inertia accumulation overflow");
198 }
199 const float determinant = b3Det(inertia);
200 if (!std::isfinite(determinant) || determinant < 0 || (determinant > 0 && !finite(b3InvertT(inertia))))
201 return invalid<void>("Body inertia cannot be inverted safely");
202 if (b3Body_GetShapeCount(box3d::Access::bodyId(*body)) > 0)
203 b3Body_ApplyMassFromShapes(box3d::Access::bodyId(*body));
204 }
205 return Result<void>::success();
206}
207} // namespace eve::physics
double m[16]
int mask
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
double raw
float inertia
float density
std::string message
ShaderImageInput shape
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::vector< std::uint32_t > indices
bool required
const std::string * tag
OceanMeshSettings mesh
glm::dvec2 center
bool finite
std::set< std::string > values
std::string body
Object::Ptr value
std::string filter
std::string_view source
int count
AbilityActivationGroup group
const char * category
uint32_t index
uint32_t flags
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
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
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
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::uint64_t > readUint64(const Value::Object &object, std::string_view name)
Reads a required unsigned decimal integer string.
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.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
static Value shapeContact(const Shape3D &shape)
Capture native shape contact state and wrapper-owned collision settings.
static Result< float > restoreShapeContact(Shape3D &shape, const Value::Object &source)
Restore validated candidate contact state; return density for deferred mass preparation.
static b3BodyId bodyId(const Body3D &body)
Borrows the native identifier synchronously; facade must belong to a Box3D world.
static b3ShapeId shapeId(const Shape3D &shape)
Borrows a Box3D shape identifier for a synchronous native operation.
glm::vec4 color