载入中...
搜索中...
未找到
Coupling3D.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <limits>
4#include <numbers>
5#include "common/Assert.h"
6#include "physics/Body3D.h"
7#include "physics/Joint3D.h"
8#include "physics/World3D.h"
11
12namespace eve::physics {
13namespace {
14template <class T>
15Result<T> fail(DiagnosticCode code, const char* message) {
16 return Result<T>::failure(Diagnostic::error(code, message, "physics.coupling3d"));
17}
18bool finite(CouplingPoint3D p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
19bool valid(const CouplingLimits3D& s) {
20 return std::isfinite(s.positionCorrection) && s.positionCorrection >= 0 && s.positionCorrection <= 1 &&
21 std::isfinite(s.maxCorrectionSpeed) && s.maxCorrectionSpeed > 0 && std::isfinite(s.maxForce) &&
22 s.maxForce > 0;
23}
24b3Vec3 vec(CouplingPoint3D p) { return {p.x, p.y, p.z}; }
25b3Pos pos(CouplingPoint3D p) { return {p.x, p.y, p.z}; }
26} // namespace
28 for (int i = 0; i < count; ++i)
29 if (terms[i].body == body) {
30 terms[i].linear = b3Add(terms[i].linear, b3MulSV(scale, linear));
31 terms[i].angular = b3Add(terms[i].angular, b3MulSV(scale, angular));
32 return;
33 }
34 terms[count++] = {body, b3MulSV(scale, linear), b3MulSV(scale, angular)};
35}
37 if (!row.active) return Result<void>::success();
38 double response = 0;
39 for (int i = 0; i < row.count; ++i) {
40 const auto& t = row.terms[i];
41 auto* body = world.findBody(t.body);
42 if (!body || !body->isValid()) return fail<void>(DiagnosticCode::StaleHandle, "Coupling endpoint is stale");
43 if (b3Body_GetType(eve::physics::box3d::Access::bodyId(*body)) != b3_dynamicBody) continue;
44 response += b3Body_GetInverseMass(eve::physics::box3d::Access::bodyId(*body)) * b3Dot(t.linear, t.linear) +
45 b3Dot(t.angular,
46 b3MulMV(b3Body_GetWorldInverseRotationalInertia(eve::physics::box3d::Access::bodyId(*body)),
47 t.angular));
48 }
49 if (!std::isfinite(response) || response <= 0)
50 return fail<void>(DiagnosticCode::InvalidArgument, "Coupling has no finite movable degree of freedom");
51 return Result<void>::success();
52}
54 using R = coupling_detail::Row;
55 if (!world || !world->isValid()) return fail<R>(DiagnosticCode::StaleHandle, "Coupling world is dead");
56 R out;
57 out.active = enabled;
58 std::array<b3BodyId, 4> raw{};
59 const int count = gear ? 4 : 2;
60 for (int i = 0; i < count; ++i) {
61 auto* body = world->findBody(bodies[i]);
62 if (!body || !body->isValid()) return fail<R>(DiagnosticCode::StaleHandle, "Coupling body is dead");
64 out.active = out.active && b3Body_IsEnabled(raw[i]);
65 }
66 if (gear) {
67 for (int i = 0; i < 2; ++i) {
68 auto* joint = world->findJoint(sources[i]);
69 if (!joint || !joint->isValid()) return fail<R>(DiagnosticCode::StaleHandle, "Gear source is dead");
70 const auto a = raw[2 * i], b = raw[2 * i + 1];
71 const auto frame = b3Joint_GetLocalFrameA(eve::physics::box3d::Access::jointId(*joint));
72 const auto transform = b3Body_GetTransform(a);
73 const b3Vec3 axis =
74 b3RotateVector(transform.q, b3RotateVector(frame.q, revolute[i] ? b3Vec3_axisZ : b3Vec3_axisX));
75 const float scale = i == 0 ? 1.f : gearSettings.ratio;
76 if (revolute[i]) {
77 const float angle = b3RevoluteJoint_GetAngle(eve::physics::box3d::Access::jointId(*joint));
78 out.wrapped[i] = angle;
79 out.coordinate[i] =
80 coordinate[i] + std::remainder(static_cast<double>(angle) - previous[i], 2 * std::numbers::pi);
81 out.add(bodies[2 * i], {}, b3Neg(axis), scale);
82 out.add(bodies[2 * i + 1], {}, axis, scale);
83 } else {
84 const auto anchorA = b3Body_GetWorldPoint(a, frame.p);
85 const auto anchorB =
86 b3Body_GetWorldPoint(b, b3Joint_GetLocalFrameB(eve::physics::box3d::Access::jointId(*joint)).p);
87 const auto d = b3SubPos(anchorB, anchorA);
88 const auto rA = b3SubPos(anchorA, b3Body_GetWorldCenterOfMass(a));
89 const auto rB = b3SubPos(anchorB, b3Body_GetWorldCenterOfMass(b));
90 out.coordinate[i] = b3Dot(axis, d);
91 out.add(bodies[2 * i], b3Neg(axis), b3Neg(b3Cross(b3Add(rA, d), axis)), scale);
92 out.add(bodies[2 * i + 1], axis, b3Cross(rB, axis), scale);
93 }
94 }
95 out.error = out.coordinate[0] + gearSettings.ratio * out.coordinate[1] - reference;
96 } else {
97 const std::array<CouplingPoint3D, 2> local{pulleySettings.localAnchorA, pulleySettings.localAnchorB};
98 const std::array<CouplingPoint3D, 2> guide{pulleySettings.groundA, pulleySettings.groundB};
99 for (int i = 0; i < 2; ++i) {
100 const auto anchor = b3Body_GetWorldPoint(raw[i], vec(local[i]));
101 const auto d = b3SubPos(anchor, pos(guide[i]));
102 const float length = b3Length(d);
103 out.coordinate[i] = length;
104 if (!std::isfinite(length) || (out.active && length <= 1e-6f))
105 return fail<R>(DiagnosticCode::InvalidArgument, "Pulley segment is singular or non-finite");
106 const auto direction = length > 1e-6f ? b3MulSV(1.f / length, d) : b3Vec3{};
107 const auto offset = b3SubPos(anchor, b3Body_GetWorldCenterOfMass(raw[i]));
108 out.add(bodies[i], direction, b3Cross(offset, direction), i == 0 ? 1.f : pulleySettings.ratio);
109 }
110 out.error = out.coordinate[0] + pulleySettings.ratio * out.coordinate[1] - pulleySettings.length;
111 }
112 if (!std::isfinite(out.error)) return fail<R>(DiagnosticCode::InvalidArgument, "Coupling coordinate overflow");
113 for (int i = 0; i < out.count; ++i)
114 if (!b3IsValidVec3(out.terms[i].linear) || !b3IsValidVec3(out.terms[i].angular))
115 return fail<R>(DiagnosticCode::InvalidArgument, "Coupling Jacobian overflow");
116 return Result<R>::success(out);
117}
118Coupling3D::Coupling3D(std::unique_ptr<Data> data) : data_(std::move(data)) {}
120 EV_ASSERT((!data_->world || !data_->world->couplingStepActive_),
121 "Release coupling wrappers outside simulation callbacks");
122 release();
123}
124void Coupling3D::release() noexcept {
125 if (data_->world) data_->world->couplings3D_.erase(data_->id);
126 data_->world = nullptr;
127 lifetime_.reset();
128}
129bool Coupling3D::isValid() const noexcept {
130 if (!data_->world || !data_->world->isValid()) return false;
131 for (int i = 0; i < (data_->gear ? 4 : 2); ++i) {
132 auto* body = data_->world->findBody(data_->bodies[i]);
133 if (!body || !body->isValid()) return false;
134 }
135 if (data_->gear)
136 for (auto handle : data_->sources) {
137 auto* joint = data_->world->findJoint(handle);
138 if (!joint || !joint->isValid()) return false;
139 }
140 return true;
141}
142int Coupling3D::getId() const noexcept { return data_->id; }
144 if (data_->world && data_->world->couplingStepActive_)
145 return fail<void>(DiagnosticCode::PreconditionViolation, "World is stepping");
146 release();
147 return Result<void>::success();
148}
150 if (!isValid()) return fail<void>(DiagnosticCode::StaleHandle, "Coupling is dead");
151 if (data_->world->couplingStepActive_)
152 return fail<void>(DiagnosticCode::PreconditionViolation, "World is stepping");
153 data_->enabled = enabled;
154 return Result<void>::success();
155}
157 auto r = data_->row();
158 if (!r) return Result<Coupling3DState>::failure(r.status());
159 return Result<Coupling3DState>::success({r.value().coordinate[0], r.value().coordinate[1], r.value().error,
160 data_->lastImpulse, r.value().active, data_->saturated});
161}
164 using R = std::unique_ptr<Coupling3D>;
165 if (world.rigidBackendKind() != RigidBackend3D::Box3D)
166 return fail<R>(DiagnosticCode::Unsupported, "Transmission projection currently requires the Box3D backend");
167 if (!world.isValid() || !first.isValid() || !second.isValid() || &first == &second || first.getWorld() != &world ||
168 second.getWorld() != &world || !valid(settings.limits) || !std::isfinite(settings.ratio) || settings.ratio == 0)
169 return fail<R>(DiagnosticCode::InvalidArgument, "Live same-world sources and finite gear settings required");
170 if (world.couplingStepActive_) return fail<R>(DiagnosticCode::PreconditionViolation, "World is stepping");
171 if (world.nextCoupling3DId_ == std::numeric_limits<int>::max())
172 return fail<R>(DiagnosticCode::Failed, "Coupling id space exhausted");
173 auto d = std::make_unique<Data>();
174 d->world = &world;
175 d->gear = true;
176 d->gearSettings = settings;
177 const std::array<Joint3D*, 2> sources{&first, &second};
178 for (int i = 0; i < 2; ++i) {
179 const auto type = b3Joint_GetType(eve::physics::box3d::Access::jointId(*sources[i]));
180 if (type != b3_revoluteJoint && type != b3_prismaticJoint)
181 return fail<R>(DiagnosticCode::Unsupported, "Gear requires revolute/prismatic sources");
182 d->revolute[i] = type == b3_revoluteJoint;
183 d->sources[i] = sources[i]->runtimeHandle();
184 auto* a = world.findBodyById(sources[i]->getBodyAId());
185 auto* b = world.findBodyById(sources[i]->getBodyBId());
186 if (!a || !b) return fail<R>(DiagnosticCode::StaleHandle, "Gear body is missing");
187 d->bodies[2 * i] = a->runtimeHandle();
188 d->bodies[2 * i + 1] = b->runtimeHandle();
189 }
190 auto row = d->row();
191 if (!row) return Result<R>::failure(row.status());
192 auto movable = coupling_detail::validateResponse(world, row.value());
193 if (!movable) return Result<R>::failure(movable.status());
194 d->reference = row.value().coordinate[0] + settings.ratio * row.value().coordinate[1];
195 d->previous = row.value().wrapped;
196 d->coordinate = row.value().coordinate;
197 d->id = world.nextCoupling3DId_++;
198 R owned(new Coupling3D(std::move(d)));
199 world.couplings3D_.emplace(owned->getId(), owned.get());
200 return Result<R>::success(std::move(owned));
201}
204 using R = std::unique_ptr<Coupling3D>;
205 if (world.rigidBackendKind() != RigidBackend3D::Box3D)
206 return fail<R>(DiagnosticCode::Unsupported, "Transmission projection currently requires the Box3D backend");
207 if (!world.isValid() || !a.isValid() || !b.isValid() || &a == &b || a.getWorld() != &world ||
208 b.getWorld() != &world || !valid(settings.limits) || !finite(settings.localAnchorA) ||
209 !finite(settings.localAnchorB) || !finite(settings.groundA) || !finite(settings.groundB) ||
210 !std::isfinite(settings.ratio) || settings.ratio <= 0 || !std::isfinite(settings.length) ||
211 settings.length <= 0)
212 return fail<R>(DiagnosticCode::InvalidArgument,
213 "Live distinct same-world bodies and finite pulley settings required");
214 if (world.couplingStepActive_) return fail<R>(DiagnosticCode::PreconditionViolation, "World is stepping");
215 if (world.nextCoupling3DId_ == std::numeric_limits<int>::max())
216 return fail<R>(DiagnosticCode::Failed, "Coupling id space exhausted");
217 auto d = std::make_unique<Data>();
218 d->world = &world;
219 d->pulleySettings = settings;
220 d->bodies[0] = a.runtimeHandle();
221 d->bodies[1] = b.runtimeHandle();
222 auto row = d->row();
223 if (!row) return Result<R>::failure(row.status());
224 auto movable = coupling_detail::validateResponse(world, row.value());
225 if (!movable) return Result<R>::failure(movable.status());
226 d->id = world.nextCoupling3DId_++;
227 R owned(new Coupling3D(std::move(d)));
228 world.couplings3D_.emplace(owned->getId(), owned.get());
229 return Result<R>::success(std::move(owned));
230}
231void World3D::invalidateCouplings3D() noexcept {
232 while (!couplings3D_.empty()) couplings3D_.begin()->second->release();
233}
234void World3D::releaseCouplingsForBody(PhysicsBodyHandle body) noexcept {
235 for (auto it = couplings3D_.begin(); it != couplings3D_.end();) {
236 auto* coupling = (it++)->second;
237 const auto& d = *coupling->data_;
238 if (std::find(d.bodies.begin(), d.bodies.end(), body) != d.bodies.end()) coupling->release();
239 }
240}
241void World3D::releaseCouplingsForJoint(PhysicsJointHandle joint) noexcept {
242 for (auto it = couplings3D_.begin(); it != couplings3D_.end();) {
243 auto* coupling = (it++)->second;
244 const auto& d = *coupling->data_;
245 if (d.gear && std::find(d.sources.begin(), d.sources.end(), joint) != d.sources.end()) coupling->release();
246 }
247}
248void World3D::adoptCouplings3D(World3D& prepared) noexcept {
249 std::swap(couplings3D_, prepared.couplings3D_);
250 std::swap(restoredCouplings3D_, prepared.restoredCouplings3D_);
251 std::swap(nextCoupling3DId_, prepared.nextCoupling3DId_);
252 for (auto [id, coupling] : couplings3D_) coupling->data_->world = this;
253 for (auto [id, coupling] : prepared.couplings3D_) coupling->data_->world = &prepared;
254}
256 const auto found = couplings3D_.find(id);
257 if (found == couplings3D_.end() || !found->second->isValid())
259 DiagnosticCode::StaleHandle, "Transmission is absent or destroyed", "physics.world3d.coupling"));
260 return ResultRef<Coupling3D>::success(std::ref(*found->second));
261}
262} // namespace eve::physics
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
b3Vec3 angular
glm::vec4 p[6]
double raw
float linear
std::string message
DiagnosticCode code
double r
std::int32_t second
std::int32_t first
JointPoint2D anchorB
float length
JointPoint2D axis
JointPoint2D anchorA
std::string local
size_t offset
std::array< float, 3 > scale
std::string response
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
ssq::Object frame
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::shared_ptr< const OceanSprayFrame > previous
bool finite
PrimitiveHandle handle
std::string body
float d
float t
std::vector< Gear > gear
RoadLaneDirection direction
bool found
ScriptStructure out
int count
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
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
Owning 3D transmission constraint, stepped transactionally by its World3D. @ownership Caller/VM owns ...
Definition Coupling3D.h:50
~Coupling3D()
Releases the registration; source bodies and joints remain intact.
Result< void > destroy()
Remove the transmission; repeated destruction succeeds, a stepping world rejects mutation.
Coupling3D(const Coupling3D &)=delete
int getId() const noexcept
Stable world-local transmission id, retained after invalidation.
static Result< std::unique_ptr< Coupling3D > > createGear(World3D &world, Joint3D &first, Joint3D &second, const GearCoupling3DSettings &settings)
Couple two live same-world revolute/prismatic joints with finite nonzero signed ratio.
bool isValid() const noexcept
True while the world and all transmission sources exist.
Result< Coupling3DState > sample() const
Read current coordinates and last completed impulse without advancing phase tracking.
static Result< std::unique_ptr< Coupling3D > > createPulley(World3D &world, Body3D &a, Body3D &b, const PulleyCoupling3DSettings &settings)
Connect distinct same-world bodies to fixed guides with positive lengths and ratio.
Result< void > setEnabled(bool enabled)
Enable/disable force projection while retaining phase tracking; locked/dead objects reject changes.
Script-facing joint owned by a World3D. Legacy scalar/void methods adapt the checked backend contract...
Definition Joint3D.h:27
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
ResultRef< Coupling3D > resolveCoupling3D(int id) const
Borrow a live transmission by persistent id, or return a stale-handle diagnostic. @ownership World or...
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
Result< void > validateResponse(World3D &world, const Row &row)
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
eve::RuntimeHandle< PhysicsJointHandleTag > PhysicsJointHandle
Generation-qualified runtime identity for a physics joint.
eve::RuntimeHandle< PhysicsBodyHandleTag > PhysicsBodyHandle
Generation-qualified runtime identity for a physics body.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
bool enabled
Result< coupling_detail::Row > row() const
Gear relation q1 + ratio*q2 = constant captured at creation. Mixed joints give ratio length-dependent...
Definition Coupling3D.h:23
Weighted rope length lA + ratio*lB; ideal taut pulley by default, optional tension-only slack rope.
Definition Coupling3D.h:28
static b3BodyId bodyId(const Body3D &body)
Borrows the native identifier synchronously; facade must belong to a Box3D world.
static b3JointId jointId(const Joint3D &joint)
Internal checked Box3D joint ID; fails for another backend.
void add(PhysicsBodyHandle body, b3Vec3 linear, b3Vec3 angular, float scale)