载入中...
搜索中...
未找到
PhysicsColliderAsset.cpp
浏览该文件的文档.
2#include <type_traits>
3#include <utility>
4#include "physics/Body.h"
5#include "physics/Body3D.h"
6#include "physics/Fixture.h"
7#include "physics/Shape3D.h"
10
11// PhysicsColliderAsset.cpp
12namespace eve::physics_editing {
13
14static_assert(std::is_polymorphic_v<IPhysicsColliderAssetResolver>);
15
16} // namespace eve::physics_editing
17
18// PhysicsEditingProvider.cpp
19namespace eve::physics_editing {
20namespace {
21class PhysicsEditingFactory final : public IPhysicsEditingFactory {
22public:
23 std::unique_ptr<PhysicsColliderPublishingTarget> createCollider(std::string id, int dimensions,
24 IPhysicsColliderRuntimeSink* sink) const override {
25 return std::make_unique<PhysicsColliderPublishingTarget>(std::move(id), dimensions, sink);
26 }
27};
28} // namespace
29
32 descriptor.id = "physics.editing";
33 descriptor.schemaVersion = 1;
34 descriptor.requiredModules = {"physics"};
36 std::make_shared<PhysicsEditingFactory>());
37}
38
39} // namespace eve::physics_editing
40
41// PhysicsPublishingTarget.cpp
42namespace eve::physics_editing {
43namespace {} // namespace
44
47 : document_(std::move(id), dimensions), sink_(sink) {}
48
50 if (staging_) return document_.applyDomainOperation(operation);
51 auto candidate = cloneDomainState();
52 auto applied = candidate->applyDomainOperation(operation);
53 if (!applied.ok()) return applied;
54 return commitDomainState(std::move(candidate));
55}
56
57std::unique_ptr<IDomainOperationTarget> PhysicsColliderPublishingTarget::cloneDomainState() const {
58 auto candidate = std::make_unique<PhysicsColliderPublishingTarget>(*this);
59 candidate->staging_ = true;
60 return candidate;
61}
62
63Result<void> PhysicsColliderPublishingTarget::commitDomainState(std::unique_ptr<IDomainOperationTarget> candidate) {
64 auto* typed = dynamic_cast<PhysicsColliderPublishingTarget*>(candidate.get());
65 if (!typed || typed->targetId() != targetId() || typed->sink_ != sink_ || !typed->staging_ ||
66 typed->document_.describe().type != document_.describe().type)
67 return eve::editing::failed<void>(EditorStatus::Conflict,
68 RuleId("editor.physics.publishing-candidate-mismatch"),
69 "Collider candidate belongs to another live target");
70 if (!sink_)
71 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.physics.publishing-sink-missing"),
72 "Collider publishing target requires a live runtime sink");
73 Result<void> published = sink_->publish(typed->document_);
74 if (!published.ok()) return published;
75 document_ = typed->document_;
76 return eve::editing::applied<void>();
77}
78
79} // namespace eve::physics_editing
80
81// PhysicsRuntime.cpp
82namespace eve::physics_editing {
83namespace {
84
85template <class T>
86const T* propertyValue(const EditorValue::Object& values, const char* path) {
87 const auto found = values.find(path);
88 return found == values.end() ? nullptr : found->second.getIf<T>();
89}
90
91} // namespace
92
93Result<physics::Fixture*> PhysicsColliderRuntimeBuilder::build2D(const PhysicsColliderTarget& target,
94 physics::Body* body) const {
95 if (!body || target.describe().type != "physics-collider-2d")
96 return eve::editing::failed<physics::Fixture*>(EditorStatus::Rejected,
97 RuleId("editor.physics.runtime-2d-input"),
98 "A 2D collider target and body are required");
99 const EditorValue snapshot = target.snapshotValue();
100 const auto* root = snapshot.getIf<EditorValue::Object>();
101 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
102 if (!values)
103 return eve::editing::failed<physics::Fixture*>(
104 EditorStatus::Failed, RuleId("editor.physics.runtime-properties"), "Collider properties are unavailable");
105 const std::string kind = *propertyValue<std::string>(*values, "shape.kind");
106 const auto* size = propertyValue<EditorValue::Array>(*values, "shape.size");
107 const auto* offset = propertyValue<EditorValue::Array>(*values, "shape.offset");
108 const float radius = static_cast<float>(*propertyValue<double>(*values, "shape.radius"));
109 const float density = static_cast<float>(*propertyValue<double>(*values, "material.density"));
110 const float friction = static_cast<float>(*propertyValue<double>(*values, "material.friction"));
111 const float restitution = static_cast<float>(*propertyValue<double>(*values, "material.restitution"));
112 physics::Fixture* fixture = nullptr;
113 if (kind == "box")
114 fixture = body->newRectangleFixtureAt(
115 static_cast<float>(*(*size)[0].getIf<double>()), static_cast<float>(*(*size)[1].getIf<double>()),
116 static_cast<float>(*(*offset)[0].getIf<double>()), static_cast<float>(*(*offset)[1].getIf<double>()),
118 else if (kind == "circle")
119 fixture = body->newCircleFixture(radius, density, friction, restitution);
120 else
121 return eve::editing::failed<physics::Fixture*>(EditorStatus::Unsupported,
122 RuleId("editor.physics.runtime-2d-asset-shape"),
123 "Polygon and chain colliders require an asset resolver");
124 if (!fixture)
125 return eve::editing::failed<physics::Fixture*>(EditorStatus::Failed, RuleId("editor.physics.runtime-create"),
126 "Physics backend failed to create the fixture");
127 fixture->setSensor(*propertyValue<bool>(*values, "shape.sensor"));
128 fixture->setCategoryBits(static_cast<int>(*propertyValue<int64_t>(*values, "collision.category")));
129 fixture->setMaskBits(static_cast<int>(*propertyValue<int64_t>(*values, "collision.mask")));
130 return eve::editing::applied<physics::Fixture*>(fixture);
131}
132
133Result<physics::Fixture*> PhysicsColliderRuntimeBuilder::build2D(const PhysicsColliderTarget& target,
134 physics::Body* body,
135 const IPhysicsColliderAssetResolver& assets) const {
136 if (!body || target.describe().type != "physics-collider-2d")
137 return eve::editing::failed<physics::Fixture*>(EditorStatus::Rejected,
138 RuleId("editor.physics.runtime-2d-input"),
139 "A 2D collider target and body are required");
140 const EditorValue snapshot = target.snapshotValue();
141 const auto* root = snapshot.getIf<EditorValue::Object>();
142 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
143 if (!values)
144 return eve::editing::failed<physics::Fixture*>(
145 EditorStatus::Failed, RuleId("editor.physics.runtime-properties"), "Collider properties are unavailable");
146 const std::string kind = *propertyValue<std::string>(*values, "shape.kind");
147 if (kind == "box" || kind == "circle") return build2D(target, body);
148 const std::string asset = *propertyValue<std::string>(*values, "shape.asset");
149 auto geometry = assets.resolve(asset, kind);
150 if (!geometry.ok()) return Result<physics::Fixture*>::failure(geometry.status());
151 std::vector<float> vertices = geometry.value().vertices;
152 const auto* offset = propertyValue<EditorValue::Array>(*values, "shape.offset");
153 const float offsetX = static_cast<float>(*(*offset)[0].getIf<double>());
154 const float offsetY = static_cast<float>(*(*offset)[1].getIf<double>());
155 for (size_t index = 0; index < vertices.size(); index += 2) {
157 vertices[index + 1] += offsetY;
158 }
159 physics::Fixture* fixture = nullptr;
160 try {
161 const float density = static_cast<float>(*propertyValue<double>(*values, "material.density"));
162 const float friction = static_cast<float>(*propertyValue<double>(*values, "material.friction"));
163 const float restitution = static_cast<float>(*propertyValue<double>(*values, "material.restitution"));
164 if (kind == "polygon")
165 fixture = body->newPolygonFixture(vertices, density, friction, restitution);
166 else if (kind == "chain")
167 fixture = body->newChainFixture(vertices, geometry.value().loop, friction, restitution);
168 } catch (const std::exception& exception) {
169 return eve::editing::failed<physics::Fixture*>(
170 EditorStatus::Rejected, RuleId("editor.physics.runtime-2d-asset-shape"), exception.what());
171 }
172 if (!fixture)
173 return eve::editing::failed<physics::Fixture*>(EditorStatus::Failed, RuleId("editor.physics.runtime-create"),
174 "Physics backend failed to create the 2D asset fixture");
175 fixture->setSensor(*propertyValue<bool>(*values, "shape.sensor"));
176 fixture->setCategoryBits(static_cast<int>(*propertyValue<int64_t>(*values, "collision.category")));
177 fixture->setMaskBits(static_cast<int>(*propertyValue<int64_t>(*values, "collision.mask")));
178 return eve::editing::applied<physics::Fixture*>(fixture);
179}
180
181Result<physics::Shape3D*> PhysicsColliderRuntimeBuilder::build3D(const PhysicsColliderTarget& target,
182 physics::Body3D* body) const {
183 if (!body || target.describe().type != "physics-collider-3d")
184 return eve::editing::failed<physics::Shape3D*>(EditorStatus::Rejected,
185 RuleId("editor.physics.runtime-3d-input"),
186 "A 3D collider target and body are required");
187 const EditorValue snapshot = target.snapshotValue();
188 const auto* root = snapshot.getIf<EditorValue::Object>();
189 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
190 if (!values)
191 return eve::editing::failed<physics::Shape3D*>(
192 EditorStatus::Failed, RuleId("editor.physics.runtime-properties"), "Collider properties are unavailable");
193 const std::string kind = *propertyValue<std::string>(*values, "shape.kind");
194 const auto* size = propertyValue<EditorValue::Array>(*values, "shape.size");
195 const auto* offset = propertyValue<EditorValue::Array>(*values, "shape.offset");
196 const float radius = static_cast<float>(*propertyValue<double>(*values, "shape.radius"));
197 const float capsuleHeight = static_cast<float>(*propertyValue<double>(*values, "shape.capsule-height"));
198 const float density = static_cast<float>(*propertyValue<double>(*values, "material.density"));
199 const float friction = static_cast<float>(*propertyValue<double>(*values, "material.friction"));
200 const float restitution = static_cast<float>(*propertyValue<double>(*values, "material.restitution"));
201 physics::Shape3D* shape = nullptr;
202 if (kind == "box")
203 shape = body->newBoxShape(static_cast<float>(*(*size)[0].getIf<double>()),
204 static_cast<float>(*(*size)[1].getIf<double>()),
205 static_cast<float>(*(*size)[2].getIf<double>()), density, friction, restitution);
206 else if (kind == "sphere")
207 shape = body->newSphereShape(radius, density, friction, restitution);
208 else if (kind == "capsule")
209 shape = body->newCapsuleShape(capsuleHeight, radius, density, friction, restitution);
210 else
211 return eve::editing::failed<physics::Shape3D*>(
212 EditorStatus::Unsupported, RuleId("editor.physics.runtime-3d-asset-shape"),
213 "Mesh, hull and height-field colliders require an asset resolver");
214 if (!shape)
215 return eve::editing::failed<physics::Shape3D*>(EditorStatus::Failed, RuleId("editor.physics.runtime-create"),
216 "Physics backend failed to create the shape");
217 shape->setLocalPosition(static_cast<float>(*(*offset)[0].getIf<double>()),
218 static_cast<float>(*(*offset)[1].getIf<double>()),
219 static_cast<float>(*(*offset)[2].getIf<double>()));
220 shape->setSensor(*propertyValue<bool>(*values, "shape.sensor"));
221 shape->setFilterBits(static_cast<uint64_t>(*propertyValue<int64_t>(*values, "collision.category")),
222 static_cast<uint64_t>(*propertyValue<int64_t>(*values, "collision.mask")));
223 return eve::editing::applied<physics::Shape3D*>(shape);
224}
225
226Result<physics::Shape3D*> PhysicsColliderRuntimeBuilder::build3D(const PhysicsColliderTarget& target,
227 physics::Body3D* body,
228 const IPhysicsColliderAssetResolver& assets) const {
229 if (!body || target.describe().type != "physics-collider-3d")
230 return eve::editing::failed<physics::Shape3D*>(EditorStatus::Rejected,
231 RuleId("editor.physics.runtime-3d-input"),
232 "A 3D collider target and body are required");
233 const EditorValue snapshot = target.snapshotValue();
234 const auto* root = snapshot.getIf<EditorValue::Object>();
235 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
236 if (!values)
237 return eve::editing::failed<physics::Shape3D*>(
238 EditorStatus::Failed, RuleId("editor.physics.runtime-properties"), "Collider properties are unavailable");
239 const std::string kind = *propertyValue<std::string>(*values, "shape.kind");
240 if (kind == "box" || kind == "sphere" || kind == "capsule") return build3D(target, body);
241 const std::string asset = *propertyValue<std::string>(*values, "shape.asset");
242 auto geometry = assets.resolve(asset, kind);
243 if (!geometry.ok()) return Result<physics::Shape3D*>::failure(geometry.status());
244 physics::Shape3D* shape = nullptr;
245 try {
246 const float density = static_cast<float>(*propertyValue<double>(*values, "material.density"));
247 const float friction = static_cast<float>(*propertyValue<double>(*values, "material.friction"));
248 const float restitution = static_cast<float>(*propertyValue<double>(*values, "material.restitution"));
249 if (kind == "convex-hull")
250 shape = body->newConvexHullShape(geometry.value().vertices, 64, density, friction, restitution);
251 else if (kind == "triangle-mesh")
252 shape = body->newTriangleMeshShape(geometry.value().vertices, geometry.value().indices);
253 else if (kind == "height-field")
254 shape =
255 body->newHeightFieldShape(geometry.value().countX, geometry.value().countZ, geometry.value().cellSizeX,
256 geometry.value().cellSizeZ, geometry.value().heights,
257 geometry.value().minimumHeight, geometry.value().maximumHeight);
258 } catch (const std::exception& exception) {
259 return eve::editing::failed<physics::Shape3D*>(
260 EditorStatus::Rejected, RuleId("editor.physics.runtime-complex-shape"), exception.what());
261 }
262 if (!shape)
263 return eve::editing::failed<physics::Shape3D*>(EditorStatus::Failed, RuleId("editor.physics.runtime-create"),
264 "Physics backend failed to create the resolved shape");
265 shape->setDensity(static_cast<float>(*propertyValue<double>(*values, "material.density")));
266 shape->setFriction(static_cast<float>(*propertyValue<double>(*values, "material.friction")));
267 shape->setRestitution(static_cast<float>(*propertyValue<double>(*values, "material.restitution")));
268 const auto* offset = propertyValue<EditorValue::Array>(*values, "shape.offset");
269 shape->setLocalPosition(static_cast<float>(*(*offset)[0].getIf<double>()),
270 static_cast<float>(*(*offset)[1].getIf<double>()),
271 static_cast<float>(*(*offset)[2].getIf<double>()));
272 shape->setSensor(*propertyValue<bool>(*values, "shape.sensor"));
273 shape->setFilterBits(static_cast<uint64_t>(*propertyValue<int64_t>(*values, "collision.category")),
274 static_cast<uint64_t>(*propertyValue<int64_t>(*values, "collision.mask")));
275 return eve::editing::applied<physics::Shape3D*>(shape);
276}
277
278Result<void> PhysicsCollider3DRuntimeSink::publish(const PhysicsColliderTarget& candidate) {
279 if (!body_ || !body_->isValid() || candidate.describe().type != "physics-collider-3d")
280 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.physics.live-3d-input"),
281 "A live Body3D and 3D collider candidate are required");
282 if (current_ && current_->isValid() && current_->getBody() != body_)
283 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.physics.live-shape-owner"),
284 "Current collider shape belongs to another body");
285 const auto diagnostics = candidate.validate();
286 for (const EditorDiagnostic& diagnostic : diagnostics) {
287 if (diagnostic.severity() == DiagnosticSeverity::Error)
288 return Result<void>::failure(eve::Status(EditorStatus::Rejected, diagnostics));
289 }
290 const EditorValue snapshot = candidate.snapshotValue();
291 const auto* root = snapshot.getIf<EditorValue::Object>();
292 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
293 if (!values)
294 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.physics.live-properties"),
295 "Collider properties are unavailable");
296 const std::string kind = *propertyValue<std::string>(*values, "shape.kind");
297 const std::string desiredBodyType = *propertyValue<std::string>(*values, "body.type");
298 const std::string previousBodyType = body_->getType();
299 const bool currentRequiresStatic = current_ && current_->isValid() &&
300 (current_->getKind() == "triangleMesh" || current_->getKind() == "heightField");
301 if (currentRequiresStatic && desiredBodyType != "static" && desiredBodyType != previousBodyType)
302 return eve::editing::failed<void>(EditorStatus::Unsupported,
303 RuleId("editor.physics.live-complex-type-transition"),
304 "Swap the complex collider to a primitive before changing its body type");
305 try {
306 if (previousBodyType != desiredBodyType) body_->setType(desiredBodyType);
307 } catch (const std::exception& exception) {
308 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.physics.live-body-type"),
309 exception.what());
310 }
311
312 Result<physics::Shape3D*> built = assets_ ? PhysicsColliderRuntimeBuilder().build3D(candidate, body_, *assets_)
313 : PhysicsColliderRuntimeBuilder().build3D(candidate, body_);
314 if (!built.ok()) {
315 if (previousBodyType != desiredBodyType) {
316 try {
317 body_->setType(previousBodyType);
318 } catch (...) {
319 auto diagnostics = built.diagnostics();
320 diagnostics.push_back(eve::editing::ruleDiagnostic(
321 eve::DiagnosticCode::Failed, RuleId("editor.physics.live-rollback-body-type"),
322 DiagnosticSeverity::Error,
323 "Collider build failed and the previous body type could not be restored"));
324 return Result<void>::failure(eve::Status(EditorStatus::Failed, std::move(diagnostics)));
325 }
326 }
327 return Result<void>::failure(built.status());
328 }
329
330 physics::Shape3D* replacement = built.value();
331 if (current_ && current_->isValid()) current_->destroy();
332 current_ = replacement;
333 return eve::editing::applied<void>();
334}
335
336Result<void> PhysicsCollider2DRuntimeSink::publish(const PhysicsColliderTarget& candidate) {
337 if (!body_ || !body_->raw() || candidate.describe().type != "physics-collider-2d")
338 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.physics.live-2d-input"),
339 "A live Body and 2D collider candidate are required");
340 if (current_ && current_->raw() && current_->getBody() != body_)
341 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.physics.live-fixture-owner"),
342 "Current fixture belongs to another body");
343 const auto diagnostics = candidate.validate();
344 for (const EditorDiagnostic& diagnostic : diagnostics) {
345 if (diagnostic.severity() == DiagnosticSeverity::Error)
346 return Result<void>::failure(eve::Status(EditorStatus::Rejected, diagnostics));
347 }
348 const EditorValue snapshot = candidate.snapshotValue();
349 const auto* root = snapshot.getIf<EditorValue::Object>();
350 const auto* values = root ? root->at("properties").getIf<EditorValue::Object>() : nullptr;
351 if (!values)
352 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.physics.live-properties"),
353 "Collider properties are unavailable");
354 const std::string desiredType = *propertyValue<std::string>(*values, "body.type");
355 const std::string previousType = body_->getType();
356 try {
357 if (desiredType != previousType) body_->setType(desiredType);
358 } catch (const std::exception& exception) {
359 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.physics.live-body-type"),
360 exception.what());
361 }
362 Result<physics::Fixture*> built = assets_ ? PhysicsColliderRuntimeBuilder().build2D(candidate, body_, *assets_)
363 : PhysicsColliderRuntimeBuilder().build2D(candidate, body_);
364 if (!built.ok()) {
365 if (desiredType != previousType) body_->setType(previousType);
366 return Result<void>::failure(built.status());
367 }
368 if (current_ && current_->raw()) current_->destroy();
369 current_ = built.value();
370 return eve::editing::applied<void>();
371}
372
373} // namespace eve::physics_editing
LogicalId target
ActionParameterOperation operation
int root
Definition AnimSmr.cpp:119
std::string descriptor
bool applied
float friction
float density
ShaderImageInput shape
size_t offset
std::string id
Snapshot snapshot
double radius
Definition MeleeHit.cpp:42
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
const eve::script::BindingContractRegistry & registry
std::string body
bool found
std::string geometry
std::string kind
double restitution
std::array< double, 2 > vertices[3]
float offsetX
float offsetY
float size
Definition TreeMesh.cpp:158
uint32_t index
Move-only operation result carrying either a value or Status.
Definition Result.h:176
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
Thread-safe generation-qualified registry for editing extension providers. @ownership Registrations a...
std::map< std::string, Value > Object
Atomic runtime publication boundary for a complete collider candidate.
virtual Result< void > publish(const PhysicsColliderTarget &candidate)=0
Publish a candidate; failure must preserve the previous live collider.
static editing::CapabilityId capabilityId()
Return the stable capability id used with ProviderLease::query().
Candidate-first collider target whose commit/undo publishes to a live sink.
Result< void > commitDomainState(std::unique_ptr< IDomainOperationTarget > candidate) override
Commits domain state.
Result< void > applyDomainOperation(const DomainOperation &operation) override
Applies domain operation.
TargetId targetId() const override
Target id.
PhysicsColliderPublishingTarget(std::string id, int dimensions, IPhysicsColliderRuntimeSink *sink)
Create an owned collider document bound to a non-owning runtime sink.
std::unique_ptr< IDomainOperationTarget > cloneDomainState() const override
Clones domain state.
TargetDescriptor describe() const override
Describe.
Result< void > applyDomainOperation(const DomainOperation &operation) override
Applies domain operation.
Diagnostic ruleDiagnostic(eve::DiagnosticCode code, RuleId rule, DiagnosticSeverity severity, std::string message)
Build an owning common diagnostic carrying an open editing rule identity.
Result< ProviderHandle > registerStaticProvider(ExtensionProviderRegistry &registry, ExtensionDescriptor descriptor, CapabilityId capability, std::shared_ptr< void > implementation)
Register one owned capability behind the standard provider lifecycle.
eve::physics_editing::PhysicsColliderRuntimeBuilder PhysicsColliderRuntimeBuilder
editing::Result< editing::ProviderHandle > registerEditingProvider(editing::ExtensionProviderRegistry &registry)
Publish the physics editing factory into a host-owned extension registry.
editing::Diagnostic EditorDiagnostic
editing::Value EditorValue
DomainOperation public API.
ExtensionDescriptor public API.