载入中...
搜索中...
未找到
Box3DWorldMover.cpp
浏览该文件的文档.
1// eve-hot-path
2#include <algorithm>
3#include <cfloat>
4#include <cmath>
5#include <utility>
6#include "physics/Joint3D.h"
11namespace eve::physics::box3d {
12using namespace world3d_detail;
13
14void WorldBackend::do_setMoverUp(float x, float y, float z) {
15 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
16 throw eve::Exception("World3D.setMoverUp: values must be finite");
17 const float lengthSquared = x * x + y * y + z * z;
18 if (lengthSquared <= 1e-12f) throw eve::Exception("World3D.setMoverUp: direction must be non-zero");
19 const float inverseLength = 1.f / std::sqrt(lengthSquared);
20 moverUp_ = b3Vec3{x * inverseLength, y * inverseLength, z * inverseLength};
21}
22
24 return checked("physics.world3d.setMoverUp", [&] {
25 do_setMoverUp(x, y, z);
27 });
28}
29
30bool WorldBackend::do_moveCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius, float dx,
31 float dy, float dz) {
32 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(bx) || !std::isfinite(by) ||
33 !std::isfinite(bz) || !(radius > 0.f) || !std::isfinite(radius) || !std::isfinite(dx) || !std::isfinite(dy) ||
34 !std::isfinite(dz))
35 throw eve::Exception("World3D.moveCapsule: all values must be finite; radius > 0");
36
37 owner_->moverDeltaX_ = owner_->moverDeltaY_ = owner_->moverDeltaZ_ = 0.f;
38 owner_->moverNormalX_ = owner_->moverNormalY_ = owner_->moverNormalZ_ = 0.f;
39 owner_->moverPlaneCount_ = 0;
40 owner_->moverIterations_ = 0;
41 owner_->moverGroundDot_ = -1.f;
42 owner_->moverGrounded_ = false;
43 if (!isValid()) return false;
44
45 constexpr int planeCapacity = 16;
46 struct PlaneCollector {
47 WorldBackend *world = nullptr;
48 b3CollisionPlane planes[planeCapacity]{};
49 int count = 0;
50 b3Vec3 steepNormals[planeCapacity]{};
51 int steepCount = 0;
52 b3Vec3 desired = b3Vec3_zero;
53 b3Vec3 up = b3Vec3_axisY;
54 b3Vec3 bestNormal = b3Vec3_zero;
55 float bestDot = 0.f;
56 float maxUpDot = -1.f;
57
58 static bool callback(b3ShapeId shapeId, const b3PlaneResult *results, int resultCount, void *context) {
59 auto *self = static_cast<PlaneCollector *>(context);
60 if (b3Shape_IsSensor(shapeId) || self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
61 for (int i = 0; i < resultCount && self->count < planeCapacity; ++i) {
62 const b3Plane &plane = results[i].plane;
63 self->planes[self->count++] =
64 b3CollisionPlane{.plane = plane, .pushLimit = FLT_MAX, .push = 0.f, .clipVelocity = true};
65 const float upDot = b3Dot(plane.normal, self->up);
66 // Clip uphill intent independently of penetration recovery to avoid solver slop creep.
67 if (upDot > 0.f && upDot < self->world->owner_->moverSlopeCos_ && self->steepCount < planeCapacity) {
68 const b3Vec3 horizontal = plane.normal - upDot * self->up;
69 const float length = b3Length(horizontal);
70 if (length > 1e-6f) self->steepNormals[self->steepCount++] = (1.f / length) * horizontal;
71 }
72 const float d = b3Dot(plane.normal, self->desired);
73 if (d < self->bestDot) {
74 self->bestDot = d;
75 self->bestNormal = plane.normal;
76 }
77 self->maxUpDot = std::max(self->maxUpDot, b3Dot(plane.normal, self->up));
78 }
79 return true;
80 }
81 } collector;
82 collector.world = this;
83 collector.up = moverUp_;
84
85 const b3Pos start{ax, ay, az};
86 b3Pos current = start;
87 const b3Pos target{ax + dx, ay + dy, az + dz};
88 b3Capsule mover{b3Vec3_zero, b3Vec3{bx - ax, by - ay, bz - az}, radius};
89 b3QueryFilter filter = do_makeQueryFilter();
90 constexpr float toleranceSquared = 1e-8f;
91 bool collided = false;
92
93 for (int pass = 0; pass < 5; ++pass) {
94 collector.count = 0;
95 collector.steepCount = 0;
96 collector.desired = target - current;
97 b3World_CollideMover(worldId_, current, &mover, filter, &PlaneCollector::callback, &collector);
98 owner_->moverPlaneCount_ += collector.count;
99 collided = collided || collector.count > 0;
100
101 b3Vec3 targetDelta = target - current;
102 for (int i = 0; i < collector.steepCount; ++i) {
103 const auto normal = collector.steepNormals[i];
104 const float inward = b3Dot(targetDelta, normal);
105 if (inward < 0.f) targetDelta = targetDelta - inward * normal;
106 }
107 b3PlaneSolverResult solved = b3SolvePlanes(targetDelta, collector.planes, collector.count);
108 b3Vec3 delta = solved.delta;
109 struct MoverFilter {
110 WorldBackend *world = nullptr;
111 static bool callback(b3ShapeId shapeId, void *context) {
112 auto *self = static_cast<MoverFilter *>(context);
113 return !b3Shape_IsSensor(shapeId) && !self->world->do_shouldIgnoreQueryShape(shapeId);
114 }
115 } moverFilter{this};
116 const float fraction =
117 b3World_CastMover(worldId_, current, &mover, delta, filter, &MoverFilter::callback, &moverFilter);
118 if (fraction < 1.f) collided = true;
119 delta = fraction * delta;
120 current = current + delta;
121 owner_->moverIterations_ = pass + 1;
122
123 if (b3LengthSquared(delta) <= toleranceSquared) break;
124 if (b3LengthSquared(target - current) <= toleranceSquared) break;
125 }
126
127 const b3Vec3 total = current - start;
128 // Grounding describes support at the destination, not planes left behind.
129 struct SupportCollector {
130 WorldBackend *world = nullptr;
131 b3Vec3 up = b3Vec3_axisY;
132 b3Vec3 normal = b3Vec3_zero;
133 float upDot = -1.f;
134
135 static bool callback(b3ShapeId shapeId, const b3PlaneResult *results, int count, void *context) {
136 auto *self = static_cast<SupportCollector *>(context);
137 if (b3Shape_IsSensor(shapeId) || self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
138 for (int i = 0; i < count; ++i) {
139 const float upDot = b3Dot(results[i].plane.normal, self->up);
140 if (upDot > self->upDot) {
141 self->upDot = upDot;
142 self->normal = results[i].plane.normal;
143 }
144 }
145 return true;
146 }
147 } support{this, moverUp_};
148 b3World_CollideMover(worldId_, current, &mover, filter, &SupportCollector::callback, &support);
149 if (b3LengthSquared(collector.bestNormal) <= toleranceSquared) collector.bestNormal = support.normal;
150 owner_->moverDeltaX_ = total.x;
151 owner_->moverDeltaY_ = total.y;
152 owner_->moverDeltaZ_ = total.z;
153 owner_->moverNormalX_ = collector.bestNormal.x;
154 owner_->moverNormalY_ = collector.bestNormal.y;
155 owner_->moverNormalZ_ = collector.bestNormal.z;
156 owner_->moverGroundDot_ = support.upDot;
157 owner_->moverGrounded_ = owner_->moverGroundDot_ >= owner_->moverSlopeCos_;
158 return collided;
159}
160
161eve::Result<bool> WorldBackend::moveCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius,
162 float dx, float dy, float dz) {
163 return checked("physics.world3d.moveCapsule", [&] {
164 return eve::Result<bool>::success(do_moveCapsule(ax, ay, az, bx, by, bz, radius, dx, dy, dz));
165 });
166}
167
168eve::Result<CapsuleMove3D> WorldBackend::do_moveCapsuleOwned(float ax, float ay, float az, float bx, float by, float bz,
169 float radius, float dx, float dy, float dz,
171 if (!isValid())
172 return ownedQueryFailure<CapsuleMove3D>(eve::DiagnosticCode::StaleHandle, "physics world is no longer valid",
173 "world");
174 const float upLengthSquared = policy.upX * policy.upX + policy.upY * policy.upY + policy.upZ * policy.upZ;
175 if (!std::isfinite(policy.upX) || !std::isfinite(policy.upY) || !std::isfinite(policy.upZ) ||
176 upLengthSquared <= 1e-12f || !std::isfinite(policy.maxSlopeRadians) || policy.maxSlopeRadians < 0.f ||
177 policy.maxSlopeRadians >= 1.57079633f)
178 return ownedQueryFailure<CapsuleMove3D>(eve::DiagnosticCode::InvalidArgument, "capsule mover policy is invalid",
179 "policy");
180 const b3Vec3 previousUp = moverUp_;
181 const float previousSlopeCos = owner_->moverSlopeCos_;
182 try {
183 ScopedQueryState3D queryState(*owner_, filter);
184 const float inverseUpLength = 1.f / std::sqrt(upLengthSquared);
185 moverUp_ = {policy.upX * inverseUpLength, policy.upY * inverseUpLength, policy.upZ * inverseUpLength};
186 owner_->moverSlopeCos_ = std::cos(policy.maxSlopeRadians);
188 result.world = owner_->runtimeHandle_;
189 result.constrained = do_moveCapsule(ax, ay, az, bx, by, bz, radius, dx, dy, dz);
190 result.grounded = owner_->isMoverGrounded();
191 result.deltaX = owner_->getMoverDeltaX();
192 result.deltaY = owner_->getMoverDeltaY();
193 result.deltaZ = owner_->getMoverDeltaZ();
194 result.normalX = owner_->getMoverNormalX();
195 result.normalY = owner_->getMoverNormalY();
196 result.normalZ = owner_->getMoverNormalZ();
197 result.planeCount = owner_->getMoverPlaneCount();
198 result.iterations = owner_->getMoverIterations();
199 moverUp_ = previousUp;
200 owner_->moverSlopeCos_ = previousSlopeCos;
202 } catch (const std::exception &error) {
203 moverUp_ = previousUp;
204 owner_->moverSlopeCos_ = previousSlopeCos;
205 return ownedQueryFailure<CapsuleMove3D>(eve::DiagnosticCode::InvalidArgument, error.what(), "capsuleMove");
206 }
207}
208
209eve::Result<CapsuleMove3D> WorldBackend::moveCapsuleOwned(float ax, float ay, float az, float bx, float by, float bz,
210 float radius, float dx, float dy, float dz,
212 return do_moveCapsuleOwned(ax, ay, az, bx, by, bz, radius, dx, dy, dz, filter, policy);
213}
214
215ClothProbeStatus WorldBackend::do_pointProbeFiltered(float x, float y, float z, float radius, ClothContact3D *out,
216 uint64_t categoryBits, uint64_t maskBits) const {
217 if (out) *out = ClothContact3D{};
218 if (!isValid() || radius <= 0.f || !out) return ClothProbeStatus::Miss;
219
220 const b3Vec3 target{x, y, z};
221 for (Shape3D *s : owner_->shapes_) {
222 if (!s || !s->isValid() || s->isSensor()) continue;
223 if ((maskBits & s->getCategoryBits()) == 0 || (s->getMaskBits() & categoryBits) == 0) continue;
224 // Box3D closest-point proxies are convex-only. Concave surfaces are handled by
225 // swept queries (and rigid contact generation), not b3Shape_GetClosestPoint.
226 const std::string kind = s->getKind();
227 if (kind == "triangleMesh" || kind == "heightField") continue;
228 const b3Vec3 closest = b3Shape_GetClosestPoint(box3d::Access::shapeId(*s), target);
229 const b3Vec3 delta = target - closest;
230 const float d = std::sqrt(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z);
231 const float depth = radius - d;
232 if (depth > 0.f && depth > out->depth) {
233 out->hit = true;
234 out->depth = depth;
235 if (d > 1e-6f) {
236 out->nx = delta.x / d;
237 out->ny = delta.y / d;
238 out->nz = delta.z / d;
239 } else {
240 out->nx = 0.f;
241 out->ny = 1.f;
242 out->nz = 0.f;
243 }
244 out->body = s->getBody();
245 out->friction = s->getFriction();
246 out->restitution = s->getRestitution();
247 }
248 }
250}
251
253 uint64_t categoryBits, uint64_t maskBits) const {
254 return checked("physics.world3d.pointProbeFiltered", [&] {
256 do_pointProbeFiltered(x, y, z, radius, &hit, categoryBits, maskBits);
258 });
259}
260
261} // namespace eve::physics::box3d
double z
double y
double x
LogicalId target
Duration start
const std::string & s
float planes[6][4]
HexVec3 up
float length
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
Texture * normal
glm::dvec3 dx
glm::dvec3 dz
std::string error
Definition Package.cpp:174
bool hit
float d
RenderSystem3D::GpuOpaqueCollector collector
std::string filter
ScriptStructure out
std::string kind
double current
float dy
Definition Shadow.cpp:151
int count
std::uint32_t depth
const VegetationPresetContext & context
float fraction
int shapeId
ViewPreparation callback
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
float getMoverNormalY() const
Representative blocking normal Y from the last move.
Definition World3D.h:789
float getMoverDeltaZ() const
Resolved translation Z from the last moveCapsule call.
Definition World3D.h:785
float getMoverDeltaY() const
Resolved translation Y from the last moveCapsule call.
Definition World3D.h:783
float getMoverNormalZ() const
Representative blocking normal Z from the last move.
Definition World3D.h:791
float getMoverDeltaX() const
Resolved translation X from the last moveCapsule call.
Definition World3D.h:781
float getMoverNormalX() const
Representative blocking normal X from the last move.
Definition World3D.h:787
int getMoverIterations() const
Number of outer solver passes used by the last move.
Definition World3D.h:795
int getMoverPlaneCount() const
Number of collision planes considered during the last move.
Definition World3D.h:793
bool isMoverGrounded() const
True when the last move touched a walkable plane.
Definition World3D.h:801
eve::Result< CapsuleMove3D > moveCapsuleOwned(float ax, float ay, float az, float bx, float by, float bz, float radius, float dx, float dy, float dz, QueryFilter3D filter, CapsuleMovePolicy3D policy) override
moveCapsuleOwned; uses the class ownership, thread and failure contract.
bool isValid() const noexcept override
Native world liveness.
eve::Result< void > setMoverUp(float x, float y, float z) override
setMoverUp; uses the class ownership, thread and failure contract.
eve::Result< bool > moveCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius, float dx, float dy, float dz) override
moveCapsule; uses the class ownership, thread and failure contract.
eve::Result< ClothContact3D > pointProbeFiltered(float x, float y, float z, float radius, uint64_t categoryBits, uint64_t maskBits) const override
pointProbeFiltered; uses the class ownership, thread and failure contract.
float lengthSquared(Vec3 value)
Length squared.
ClothProbeStatus
Named outcome for a filtered cloth particle probe.
Owning result of continuous capsule movement.
PhysicsWorldHandle world
Per-call capsule mover classification policy; never mutates persistent World3D settings.
Result of a 3D point probe: deepest non-sensor shape within radius. Normal points from the shape towa...
Query filter applied atomically for one owning query operation.
static b3ShapeId shapeId(const Shape3D &shape)
Borrows a Box3D shape identifier for a synchronous native operation.