载入中...
搜索中...
未找到
DistanceField3D.cpp
浏览该文件的文档.
1// eve-hot-path
3
4#include "common/Exception.h"
5
6#include <algorithm>
7#include <cmath>
8#include <limits>
9
10namespace eve::physics {
11
12namespace {
13constexpr double maxQueryIntervals = 1000000.0;
14
15int queryIntervals(double length, double interval, const char *operation) {
16 const double count = std::ceil(length / interval);
17 if (!std::isfinite(count) || count > maxQueryIntervals)
18 throw eve::Exception("%s: sweep or capsule is too long", operation);
19 return std::max(1, static_cast<int>(count));
20}
21} // namespace
22
23DistanceField3D::DistanceField3D(int width, int height, int depth, float cellSize,
24 float originX, float originY, float originZ,
25 float outsideDistance)
26 : width_(width), height_(height), depth_(depth), cellSize_(cellSize), originX_(originX),
27 originY_(originY), originZ_(originZ), outsideDistance_(outsideDistance) {
28 if (width < 2 || height < 2 || depth < 2 || !(cellSize > 0.f) || !std::isfinite(cellSize) ||
29 !std::isfinite(originX) || !std::isfinite(originY) || !std::isfinite(originZ) ||
30 !std::isfinite(outsideDistance))
31 throw eve::Exception("DistanceField3D: dimensions must be >= 2 and cellSize finite > 0");
32 constexpr size_t maxSamples = 64u * 1024u * 1024u;
33 const size_t wh = static_cast<size_t>(width) * static_cast<size_t>(height);
34 if (static_cast<size_t>(width) > maxSamples / static_cast<size_t>(height) ||
35 wh > maxSamples / static_cast<size_t>(depth))
36 throw eve::Exception("DistanceField3D: grid is too large");
37 const size_t count = wh * static_cast<size_t>(depth);
38 distances_.assign(count, outsideDistance);
39 moverSkinWidth_ = std::max(1e-4f, cellSize_ * 1e-3f);
40}
41
42bool DistanceField3D::validIndex(int x, int y, int z) const {
43 return x >= 0 && y >= 0 && z >= 0 && x < width_ && y < height_ && z < depth_;
44}
45
46bool DistanceField3D::validRegion(int x, int y, int z, int width, int height, int depth) const {
47 return x >= 0 && y >= 0 && z >= 0 && width > 0 && height > 0 && depth > 0 &&
48 width <= width_ - x && height <= height_ - y && depth <= depth_ - z;
49}
50
51size_t DistanceField3D::index(int x, int y, int z) const {
52 return (static_cast<size_t>(z) * static_cast<size_t>(height_) + static_cast<size_t>(y)) *
53 static_cast<size_t>(width_) +
54 static_cast<size_t>(x);
55}
56
57void DistanceField3D::setDistances(const std::vector<float> &distances) {
58 if (distances.size() != distances_.size())
59 throw eve::Exception("DistanceField3D.setDistances: sample count does not match grid");
60 if (!std::all_of(distances.begin(), distances.end(),
61 [](float distance) { return std::isfinite(distance); }))
62 throw eve::Exception("DistanceField3D.setDistances: all distances must be finite");
63 distances_ = distances;
64 ++revision_;
65}
66
68 if (!std::isfinite(distance))
69 throw eve::Exception("DistanceField3D.fill: distance must be finite");
70 std::fill(distances_.begin(), distances_.end(), distance);
71 ++revision_;
72}
73
74void DistanceField3D::setDistanceRegion(int x, int y, int z, int width, int height, int depth,
75 const std::vector<float> &distances) {
76 if (!validRegion(x, y, z, width, height, depth))
77 throw eve::Exception("DistanceField3D.setDistanceRegion: region is out of range");
78 const size_t count = static_cast<size_t>(width) * static_cast<size_t>(height) *
79 static_cast<size_t>(depth);
80 if (distances.size() != count)
81 throw eve::Exception(
82 "DistanceField3D.setDistanceRegion: sample count does not match region");
83 if (!std::all_of(distances.begin(), distances.end(),
84 [](float distance) { return std::isfinite(distance); }))
85 throw eve::Exception(
86 "DistanceField3D.setDistanceRegion: all distances must be finite");
87 size_t source = 0;
88 for (int localZ = 0; localZ < depth; ++localZ) {
89 for (int localY = 0; localY < height; ++localY) {
90 const size_t destination = index(x, y + localY, z + localZ);
91 std::copy_n(distances.begin() + static_cast<std::ptrdiff_t>(source), width,
92 distances_.begin() + static_cast<std::ptrdiff_t>(destination));
93 source += static_cast<size_t>(width);
94 }
95 }
96 ++revision_;
97}
98
99void DistanceField3D::fillRegion(int x, int y, int z, int width, int height, int depth,
100 float distance) {
101 if (!validRegion(x, y, z, width, height, depth))
102 throw eve::Exception("DistanceField3D.fillRegion: region is out of range");
103 if (!std::isfinite(distance))
104 throw eve::Exception("DistanceField3D.fillRegion: distance must be finite");
105 for (int localZ = 0; localZ < depth; ++localZ) {
106 for (int localY = 0; localY < height; ++localY) {
107 const size_t destination = index(x, y + localY, z + localZ);
108 std::fill_n(distances_.begin() + static_cast<std::ptrdiff_t>(destination), width,
109 distance);
110 }
111 }
112 ++revision_;
113}
114
115void DistanceField3D::setDistance(int x, int y, int z, float distance) {
116 if (!validIndex(x, y, z)) throw eve::Exception("DistanceField3D.setDistance: index out of range");
117 if (!std::isfinite(distance))
118 throw eve::Exception("DistanceField3D.setDistance: distance must be finite");
119 distances_[index(x, y, z)] = distance;
120 ++revision_;
121}
122
123float DistanceField3D::getDistance(int x, int y, int z) const {
124 return validIndex(x, y, z) ? distances_[index(x, y, z)] : outsideDistance_;
125}
126
127float DistanceField3D::sample(float x, float y, float z) const {
128 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
129 throw eve::Exception("DistanceField3D.sample: coordinates must be finite");
130 const float gx = (x - originX_) / cellSize_;
131 const float gy = (y - originY_) / cellSize_;
132 const float gz = (z - originZ_) / cellSize_;
133 if (gx < 0.f || gy < 0.f || gz < 0.f || gx > width_ - 1.f || gy > height_ - 1.f ||
134 gz > depth_ - 1.f)
135 return outsideDistance_;
136
137 const int x0 = std::min(static_cast<int>(std::floor(gx)), width_ - 2);
138 const int y0 = std::min(static_cast<int>(std::floor(gy)), height_ - 2);
139 const int z0 = std::min(static_cast<int>(std::floor(gz)), depth_ - 2);
140 const float tx = std::clamp(gx - x0, 0.f, 1.f);
141 const float ty = std::clamp(gy - y0, 0.f, 1.f);
142 const float tz = std::clamp(gz - z0, 0.f, 1.f);
143 auto mix = [](float a, float b, float t) { return a + (b - a) * t; };
144 const float c00 = mix(getDistance(x0, y0, z0), getDistance(x0 + 1, y0, z0), tx);
145 const float c10 = mix(getDistance(x0, y0 + 1, z0), getDistance(x0 + 1, y0 + 1, z0), tx);
146 const float c01 = mix(getDistance(x0, y0, z0 + 1), getDistance(x0 + 1, y0, z0 + 1), tx);
147 const float c11 = mix(getDistance(x0, y0 + 1, z0 + 1),
148 getDistance(x0 + 1, y0 + 1, z0 + 1), tx);
149 return mix(mix(c00, c10, ty), mix(c01, c11, ty), tz);
150}
151
152void DistanceField3D::sampleNormal(float x, float y, float z) {
153 const float h = cellSize_ * 0.5f;
154 const float maxX = originX_ + cellSize_ * static_cast<float>(width_ - 1);
155 const float maxY = originY_ + cellSize_ * static_cast<float>(height_ - 1);
156 const float maxZ = originZ_ + cellSize_ * static_cast<float>(depth_ - 1);
157 if (x < originX_ || y < originY_ || z < originZ_ || x > maxX || y > maxY || z > maxZ) {
158 normalX_ = 0.f;
159 normalY_ = 1.f;
160 normalZ_ = 0.f;
161 return;
162 }
163 const float center = sample(x, y, z);
164 const float nx = x - h < originX_ ? sample(x + h, y, z) - center
165 : x + h > maxX ? center - sample(x - h, y, z)
166 : sample(x + h, y, z) - sample(x - h, y, z);
167 const float ny = y - h < originY_ ? sample(x, y + h, z) - center
168 : y + h > maxY ? center - sample(x, y - h, z)
169 : sample(x, y + h, z) - sample(x, y - h, z);
170 const float nz = z - h < originZ_ ? sample(x, y, z + h) - center
171 : z + h > maxZ ? center - sample(x, y, z - h)
172 : sample(x, y, z + h) - sample(x, y, z - h);
173 const float length = std::sqrt(nx * nx + ny * ny + nz * nz);
174 if (length > 1e-6f) {
175 normalX_ = nx / length;
176 normalY_ = ny / length;
177 normalZ_ = nz / length;
178 } else {
179 normalX_ = 0.f;
180 normalY_ = 1.f;
181 normalZ_ = 0.f;
182 }
183}
184
185void DistanceField3D::setCollisionResult(float x, float y, float z, float radius) {
186 collisionX_ = x;
187 collisionY_ = y;
188 collisionZ_ = z;
189 collisionDistance_ = sample(x, y, z) - radius;
190 sampleNormal(x, y, z);
191 updateContactPoints(x, y, z, radius);
192}
193
194void DistanceField3D::updateContactPoints(float x, float y, float z, float radius) {
195 const float fieldDistance = collisionDistance_ + radius;
196 surfaceX_ = x - normalX_ * fieldDistance;
197 surfaceY_ = y - normalY_ * fieldDistance;
198 surfaceZ_ = z - normalZ_ * fieldDistance;
199 shapeContactX_ = x - normalX_ * radius;
200 shapeContactY_ = y - normalY_ * radius;
201 shapeContactZ_ = z - normalZ_ * radius;
202}
203
204bool DistanceField3D::checkSphere(float x, float y, float z, float radius) {
205 if (!(radius >= 0.f) || !std::isfinite(radius))
206 throw eve::Exception("DistanceField3D.checkSphere: radius must be finite and >= 0");
207 setCollisionResult(x, y, z, radius);
208 return collisionDistance_ <= 0.f;
209}
210
211bool DistanceField3D::checkCapsule(float ax, float ay, float az, float bx, float by, float bz,
212 float radius) {
213 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(bx) ||
214 !std::isfinite(by) || !std::isfinite(bz) || !(radius >= 0.f) || !std::isfinite(radius))
215 throw eve::Exception(
216 "DistanceField3D.checkCapsule: coordinates and radius must be finite; radius >= 0");
217 float bestX, bestY, bestZ;
218 const float best = capsuleClearance(ax, ay, az, bx, by, bz, radius, bestX, bestY, bestZ);
219 collisionX_ = bestX;
220 collisionY_ = bestY;
221 collisionZ_ = bestZ;
222 collisionDistance_ = best;
223 sampleNormal(bestX, bestY, bestZ);
224 updateContactPoints(bestX, bestY, bestZ, radius);
225 return best <= 0.f;
226}
227
228float DistanceField3D::capsuleClearance(float ax, float ay, float az, float bx, float by,
229 float bz, float radius, float &closestX, float &closestY,
230 float &closestZ) const {
231 const float dx = bx - ax, dy = by - ay, dz = bz - az;
232 const float length = std::hypot(dx, dy, dz);
233 // A half-cell maximum interval is a conservative practical resolution for a sampled SDF.
234 const int steps = queryIntervals(length, cellSize_ * 0.5, "DistanceField3D.checkCapsule");
235 float best = std::numeric_limits<float>::infinity();
236 closestX = ax;
237 closestY = ay;
238 closestZ = az;
239 for (int i = 0; i <= steps; ++i) {
240 const float t = static_cast<float>(i) / static_cast<float>(steps);
241 const float x = ax + dx * t, y = ay + dy * t, z = az + dz * t;
242 const float clearance = sample(x, y, z) - radius;
243 if (clearance < best) {
244 best = clearance;
245 closestX = x;
246 closestY = y;
247 closestZ = z;
248 }
249 }
250 return best;
251}
252
253void DistanceField3D::setCastResult(float fraction, float travelLength, float x, float y, float z,
254 float clearance, float radius, bool startedInside) {
255 castFraction_ = fraction;
256 castDistance_ = fraction * travelLength;
257 castStartedInside_ = startedInside;
258 collisionX_ = x;
259 collisionY_ = y;
260 collisionZ_ = z;
261 collisionDistance_ = clearance;
262 sampleNormal(x, y, z);
263 updateContactPoints(x, y, z, radius);
264}
265
266bool DistanceField3D::castSphere(float x, float y, float z, float radius, float deltaX,
267 float deltaY, float deltaZ) {
268 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) ||
269 !(radius >= 0.f) || !std::isfinite(radius) || !std::isfinite(deltaX) ||
270 !std::isfinite(deltaY) || !std::isfinite(deltaZ))
271 throw eve::Exception(
272 "DistanceField3D.castSphere: coordinates, radius, and delta must be finite; radius >= 0");
273 const float travel = std::hypot(deltaX, deltaY, deltaZ);
274 const float initial = sample(x, y, z) - radius;
275 if (initial <= 0.f) {
276 setCastResult(0.f, travel, x, y, z, initial, radius, true);
277 return true;
278 }
279 castFraction_ = 1.f;
280 castDistance_ = travel;
281 castStartedInside_ = false;
282 if (travel <= 1e-7f) return false;
283
284 const int steps = queryIntervals(travel, cellSize_ * 0.25, "DistanceField3D.castSphere");
285 float previous = 0.f;
286 for (int i = 1; i <= steps; ++i) {
287 const float fraction = static_cast<float>(i) / static_cast<float>(steps);
288 const float px = x + deltaX * fraction;
289 const float py = y + deltaY * fraction;
290 const float pz = z + deltaZ * fraction;
291 if (sample(px, py, pz) - radius > 0.f) {
293 continue;
294 }
295 float low = previous, high = fraction;
296 for (int iteration = 0; iteration < 14; ++iteration) {
297 const float middle = 0.5f * (low + high);
298 if (sample(x + deltaX * middle, y + deltaY * middle, z + deltaZ * middle) -
299 radius <=
300 0.f)
301 high = middle;
302 else
303 low = middle;
304 }
305 const float hx = x + deltaX * high;
306 const float hy = y + deltaY * high;
307 const float hz = z + deltaZ * high;
308 setCastResult(high, travel, hx, hy, hz, sample(hx, hy, hz) - radius, radius, false);
309 return true;
310 }
311 return false;
312}
313
314bool DistanceField3D::castCapsule(float ax, float ay, float az, float bx, float by, float bz,
315 float radius, float deltaX, float deltaY, float deltaZ) {
316 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) ||
317 !std::isfinite(bx) || !std::isfinite(by) || !std::isfinite(bz) ||
318 !(radius >= 0.f) || !std::isfinite(radius) || !std::isfinite(deltaX) ||
319 !std::isfinite(deltaY) || !std::isfinite(deltaZ))
320 throw eve::Exception(
321 "DistanceField3D.castCapsule: coordinates, radius, and delta must be finite; radius >= 0");
322 const float travel = std::hypot(deltaX, deltaY, deltaZ);
323 float hitX, hitY, hitZ;
324 const float initial =
325 capsuleClearance(ax, ay, az, bx, by, bz, radius, hitX, hitY, hitZ);
326 if (initial <= 0.f) {
327 setCastResult(0.f, travel, hitX, hitY, hitZ, initial, radius, true);
328 return true;
329 }
330 castFraction_ = 1.f;
331 castDistance_ = travel;
332 castStartedInside_ = false;
333 if (travel <= 1e-7f) return false;
334
335 const int steps = queryIntervals(travel, cellSize_ * 0.25, "DistanceField3D.castCapsule");
336 float previous = 0.f;
337 for (int i = 1; i <= steps; ++i) {
338 const float fraction = static_cast<float>(i) / static_cast<float>(steps);
339 float closestX, closestY, closestZ;
340 const float clearance = capsuleClearance(
341 ax + deltaX * fraction, ay + deltaY * fraction, az + deltaZ * fraction,
342 bx + deltaX * fraction, by + deltaY * fraction, bz + deltaZ * fraction, radius,
343 closestX, closestY, closestZ);
344 if (clearance > 0.f) {
346 continue;
347 }
348 float low = previous, high = fraction;
349 for (int iteration = 0; iteration < 14; ++iteration) {
350 const float middle = 0.5f * (low + high);
351 float ignoredX, ignoredY, ignoredZ;
352 if (capsuleClearance(
353 ax + deltaX * middle, ay + deltaY * middle, az + deltaZ * middle,
354 bx + deltaX * middle, by + deltaY * middle, bz + deltaZ * middle, radius,
355 ignoredX, ignoredY, ignoredZ) <= 0.f)
356 high = middle;
357 else
358 low = middle;
359 }
360 const float finalClearance = capsuleClearance(
361 ax + deltaX * high, ay + deltaY * high, az + deltaZ * high,
362 bx + deltaX * high, by + deltaY * high, bz + deltaZ * high, radius, hitX, hitY,
363 hitZ);
364 setCastResult(high, travel, hitX, hitY, hitZ, finalClearance, radius, false);
365 return true;
366 }
367 return false;
368}
369
370void DistanceField3D::setMoverUp(float x, float y, float z) {
371 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
372 throw eve::Exception("DistanceField3D.setMoverUp: direction must be finite");
373 const float magnitude = std::hypot(x, y, z);
374 if (!(magnitude > 1e-6f))
375 throw eve::Exception("DistanceField3D.setMoverUp: direction must be non-zero");
376 moverUpX_ = x / magnitude;
377 moverUpY_ = y / magnitude;
378 moverUpZ_ = z / magnitude;
379}
380
382 if (!std::isfinite(degrees))
383 throw eve::Exception("DistanceField3D.setMoverSlopeLimit: degrees must be finite");
384 constexpr float radiansPerDegree = 0.01745329251994329577f;
385 moverSlopeCos_ = std::cos(std::clamp(degrees, 0.f, 89.9f) * radiansPerDegree);
386}
387
389 if (!(width >= 0.f) || !std::isfinite(width))
390 throw eve::Exception("DistanceField3D.setMoverSkinWidth: width must be finite and >= 0");
391 moverSkinWidth_ = width;
392}
393
395 if (!(distance >= 0.f) || !std::isfinite(distance))
396 throw eve::Exception(
397 "DistanceField3D.setMoverGroundSnap: distance must be finite and >= 0");
398 moverGroundSnap_ = distance;
399}
400
402 if (!(height >= 0.f) || !std::isfinite(height))
403 throw eve::Exception(
404 "DistanceField3D.setMoverStepHeight: height must be finite and >= 0");
405 moverStepHeight_ = height;
406}
407
408bool DistanceField3D::moveCapsule(float ax, float ay, float az, float bx, float by, float bz,
409 float radius, float deltaX, float deltaY, float deltaZ) {
410 // Validation and pathological capsule-length protection are shared with the overlap query.
411 checkCapsule(ax, ay, az, bx, by, bz, radius);
412 if (!std::isfinite(deltaX) || !std::isfinite(deltaY) || !std::isfinite(deltaZ))
413 throw eve::Exception("DistanceField3D.moveCapsule: delta must be finite");
414
415 struct Vec3 {
416 float x, y, z;
417 };
418 auto dot = [](Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; };
419 auto length = [&](Vec3 value) { return std::sqrt(dot(value, value)); };
420
421 constexpr int maxIterations = 6;
422 constexpr int maxPlanes = 4;
423 // Retain a numerical epsilon even when the caller requests zero visible skin, otherwise an
424 // exact distance==radius contact would be classified as penetration on every solver pass.
425 const float skin = std::max(moverSkinWidth_, cellSize_ * 1e-6f);
426 Vec3 position{0.f, 0.f, 0.f};
427 Vec3 remaining{deltaX, deltaY, deltaZ};
428 Vec3 planes[maxPlanes]{};
429 int planeCount = 0;
430 bool constrained = false;
431 moverIterations_ = 0;
432 moverNormalX_ = 0.f;
433 moverNormalY_ = 1.f;
434 moverNormalZ_ = 0.f;
435 moverGroundDot_ = -1.f;
436 moverGrounded_ = false;
437 moverHitWall_ = false;
438 auto recordNormal = [&](Vec3 normal) {
439 moverNormalX_ = normal.x;
440 moverNormalY_ = normal.y;
441 moverNormalZ_ = normal.z;
442 const float upDot =
443 normal.x * moverUpX_ + normal.y * moverUpY_ + normal.z * moverUpZ_;
444 moverGroundDot_ = std::max(moverGroundDot_, upDot);
445 if (upDot < moverSlopeCos_) moverHitWall_ = true;
446 };
447 // Several points on a capsule axis can be equally close to a floor/wall
448 // corner. The first point's blended gradient is not a contact manifold:
449 // it can turn a horizontal wall hit into artificial upward motion. Among
450 // equally close samples use the normal most opposed to the requested move.
451 auto contactNormal = [&](Vec3 offset, Vec3 travel) {
452 const Vec3 previous{normalX_, normalY_, normalZ_};
453 Vec3 selected = previous;
454 float opposed = dot(selected, travel);
455 const float closest = collisionDistance_;
456 const float axisLength = std::hypot(bx - ax, by - ay, bz - az);
457 const int intervals = queryIntervals(axisLength, cellSize_ * 0.5, "DistanceField3D.moveCapsule");
458 for (int i = 0; i <= intervals; ++i) {
459 const float t = static_cast<float>(i) / static_cast<float>(intervals);
460 const Vec3 point{ax + offset.x + (bx - ax) * t, ay + offset.y + (by - ay) * t,
461 az + offset.z + (bz - az) * t};
462 if (sample(point.x, point.y, point.z) - radius > closest + 1e-5f) continue;
463 sampleNormal(point.x, point.y, point.z);
464 const Vec3 candidate{normalX_, normalY_, normalZ_};
465 const float candidateDot = dot(candidate, travel);
466 if (candidateDot < opposed) {
467 opposed = candidateDot;
468 selected = candidate;
469 }
470 }
471 normalX_ = previous.x;
472 normalY_ = previous.y;
473 normalZ_ = previous.z;
474 return selected;
475 };
476
477 for (int iteration = 0; iteration < maxIterations; ++iteration) {
478 moverIterations_ = iteration + 1;
479 const float currentAx = ax + position.x, currentAy = ay + position.y,
480 currentAz = az + position.z;
481 const float currentBx = bx + position.x, currentBy = by + position.y,
482 currentBz = bz + position.z;
483
484 if (checkCapsule(currentAx, currentAy, currentAz, currentBx, currentBy, currentBz,
485 radius)) {
486 const float recovery = -collisionDistance_ + skin;
487 const Vec3 normal = contactNormal(position, remaining);
488 position.x += normal.x * recovery;
489 position.y += normal.y * recovery;
490 position.z += normal.z * recovery;
491 recordNormal(normal);
492 constrained = true;
493 if (planeCount < maxPlanes) planes[planeCount++] = normal;
494 continue;
495 }
496
497 const float travel = length(remaining);
498 if (travel <= 1e-6f) break;
499 if (!castCapsule(currentAx, currentAy, currentAz, currentBx, currentBy, currentBz, radius,
500 remaining.x, remaining.y, remaining.z)) {
501 position.x += remaining.x;
502 position.y += remaining.y;
503 position.z += remaining.z;
504 remaining = {};
505 break;
506 }
507
508 constrained = true;
509 const Vec3 impactOffset{position.x + remaining.x * castFraction_, position.y + remaining.y * castFraction_,
510 position.z + remaining.z * castFraction_};
511 const Vec3 normal = contactNormal(impactOffset, remaining);
512 recordNormal(normal);
513 if (planeCount < maxPlanes) planes[planeCount++] = normal;
514
515 const float safeFraction = std::max(0.f, castFraction_ - skin / travel);
516 position.x += remaining.x * safeFraction;
517 position.y += remaining.y * safeFraction;
518 position.z += remaining.z * safeFraction;
519 remaining.x *= 1.f - safeFraction;
520 remaining.y *= 1.f - safeFraction;
521 remaining.z *= 1.f - safeFraction;
522
523 // Project against every accumulated contact plane. Repeating handles corners where
524 // projecting against one plane can reintroduce motion into another.
525 for (int pass = 0; pass < planeCount; ++pass) {
526 for (int plane = 0; plane < planeCount; ++plane) {
527 const float into = dot(remaining, planes[plane]);
528 if (into < 0.f) {
529 remaining.x -= planes[plane].x * into;
530 remaining.y -= planes[plane].y * into;
531 remaining.z -= planes[plane].z * into;
532 }
533 }
534 }
535 }
536
537 moverGrounded_ = moverGroundDot_ >= moverSlopeCos_;
538 if (!moverGrounded_ && moverGroundSnap_ > 0.f) {
539 const Vec3 snap{-moverUpX_ * moverGroundSnap_, -moverUpY_ * moverGroundSnap_,
540 -moverUpZ_ * moverGroundSnap_};
541 if (castCapsule(ax + position.x, ay + position.y, az + position.z, bx + position.x,
542 by + position.y, bz + position.z, radius, snap.x, snap.y, snap.z) &&
543 !castStartedInside_) {
544 const Vec3 snapNormal{normalX_, normalY_, normalZ_};
545 const float groundDot = snapNormal.x * moverUpX_ + snapNormal.y * moverUpY_ +
546 snapNormal.z * moverUpZ_;
547 if (groundDot >= moverSlopeCos_) {
548 const float safeFraction =
549 std::max(0.f, castFraction_ - skin / moverGroundSnap_);
550 position.x += snap.x * safeFraction;
551 position.y += snap.y * safeFraction;
552 position.z += snap.z * safeFraction;
553 recordNormal(snapNormal);
554 moverGrounded_ = true;
555 constrained = true;
556 ++moverIterations_;
557 }
558 }
559 }
560 moverDeltaX_ = position.x;
561 moverDeltaY_ = position.y;
562 moverDeltaZ_ = position.z;
563
564 const Vec3 requested{deltaX, deltaY, deltaZ};
565 const float requestedUp =
566 requested.x * moverUpX_ + requested.y * moverUpY_ + requested.z * moverUpZ_;
567 const Vec3 lateral{requested.x - moverUpX_ * requestedUp,
568 requested.y - moverUpY_ * requestedUp,
569 requested.z - moverUpZ_ * requestedUp};
570 const float lateralLength = length(lateral);
571 if (!moverStepping_ && moverStepHeight_ > 0.f && moverHitWall_ && lateralLength > 1e-6f) {
572 struct MoverState {
573 float dx, dy, dz, nx, ny, nz, groundDot;
574 int iterations;
575 bool grounded, hitWall;
576 };
577 const MoverState direct{moverDeltaX_, moverDeltaY_, moverDeltaZ_,
578 moverNormalX_, moverNormalY_, moverNormalZ_,
579 moverGroundDot_, moverIterations_, moverGrounded_,
580 moverHitWall_};
581 auto restore = [&](const MoverState &state) {
582 moverDeltaX_ = state.dx;
583 moverDeltaY_ = state.dy;
584 moverDeltaZ_ = state.dz;
585 moverNormalX_ = state.nx;
586 moverNormalY_ = state.ny;
587 moverNormalZ_ = state.nz;
588 moverGroundDot_ = state.groundDot;
589 moverIterations_ = state.iterations;
590 moverGrounded_ = state.grounded;
591 moverHitWall_ = state.hitWall;
592 };
593 const Vec3 up{moverUpX_ * moverStepHeight_, moverUpY_ * moverStepHeight_,
594 moverUpZ_ * moverStepHeight_};
595
596 // The entire raised capsule must have ceiling clearance before trying the forward phase.
597 if (!castCapsule(ax, ay, az, bx, by, bz, radius, up.x, up.y, up.z)) {
598 moverStepping_ = true;
599 try {
600 moveCapsule(ax + up.x, ay + up.y, az + up.z, bx + up.x, by + up.y,
601 bz + up.z, radius, deltaX, deltaY, deltaZ);
602 } catch (...) {
603 moverStepping_ = false;
604 throw;
605 }
606 moverStepping_ = false;
607
608 Vec3 candidate{up.x + moverDeltaX_, up.y + moverDeltaY_, up.z + moverDeltaZ_};
609 const int candidateIterations = moverIterations_;
610 const bool candidateHitWall = moverHitWall_;
611 const float downDistance = moverStepHeight_ + moverGroundSnap_ + skin;
612 const Vec3 down{-moverUpX_ * downDistance, -moverUpY_ * downDistance,
613 -moverUpZ_ * downDistance};
614 if (castCapsule(ax + candidate.x, ay + candidate.y, az + candidate.z,
615 bx + candidate.x, by + candidate.y, bz + candidate.z, radius, down.x,
616 down.y, down.z) &&
617 !castStartedInside_) {
618 const Vec3 landingNormal{normalX_, normalY_, normalZ_};
619 const float landingDot = landingNormal.x * moverUpX_ +
620 landingNormal.y * moverUpY_ +
621 landingNormal.z * moverUpZ_;
622 if (landingDot >= moverSlopeCos_) {
623 const float safeFraction =
624 std::max(0.f, castFraction_ - skin / downDistance);
625 candidate.x += down.x * safeFraction;
626 candidate.y += down.y * safeFraction;
627 candidate.z += down.z * safeFraction;
628 const float directProgress =
629 (direct.dx * lateral.x + direct.dy * lateral.y + direct.dz * lateral.z) /
630 lateralLength;
631 const float candidateProgress =
632 (candidate.x * lateral.x + candidate.y * lateral.y +
633 candidate.z * lateral.z) /
634 lateralLength;
635 if (candidateProgress > directProgress + std::max(1e-4f, skin)) {
636 moverDeltaX_ = candidate.x;
637 moverDeltaY_ = candidate.y;
638 moverDeltaZ_ = candidate.z;
639 moverNormalX_ = landingNormal.x;
640 moverNormalY_ = landingNormal.y;
641 moverNormalZ_ = landingNormal.z;
642 moverGroundDot_ = landingDot;
643 moverGrounded_ = true;
644 moverHitWall_ = candidateHitWall;
645 moverIterations_ = candidateIterations + 2;
646 return true;
647 }
648 }
649 }
650 }
651 restore(direct);
652 }
653 return constrained;
654}
655
656} // namespace eve::physics
double z
double y
double x
ActionParameterOperation operation
std::string selected
double lateral
float degrees
Definition CardTypes.cpp:38
float planes[6][4]
HexVec3 up
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
float length
size_t offset
std::array< float, 3 > position
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
std::shared_ptr< const OceanSprayFrame > previous
Object::Ptr value
int steps
float t
std::string_view source
float dy
Definition Shadow.cpp:151
int count
std::map< Cell, int > best
int iterations
Definition TreeMesh.cpp:448
std::uint32_t depth
uint32_t index
float fraction
glm::vec3 point
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
void setMoverGroundSnap(float distance)
Set the non-negative distance used to snap onto walkable ground after movement.
void fill(float distance)
Set every grid sample to the same finite distance.
bool moveCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius, float deltaX, float deltaY, float deltaZ)
Resolve a capsule displacement against the field with sliding and depenetration. The capsule coordina...
void setMoverUp(float x, float y, float z)
Set the normalized reference-up direction used for ground classification.
void fillRegion(int x, int y, int z, int width, int height, int depth, float distance)
Fill an in-bounds grid subregion with one finite signed distance.
void sampleNormal(float x, float y, float z)
Estimate the normalized outward field gradient at a world position.
void setDistances(const std::vector< float > &distances)
Replace every sample in x-fastest, then y, then z order.
bool checkCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius)
Test a capsule defined by two sphere centers against the solid.
void setMoverSlopeLimit(float degrees)
Set the maximum walkable slope angle in degrees, clamped to [0, 89.9].
bool castCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius, float deltaX, float deltaY, float deltaZ)
Sweep a capsule through the field and cache the earliest contact.
bool castSphere(float x, float y, float z, float radius, float deltaX, float deltaY, float deltaZ)
Sweep a sphere through the field and cache the earliest contact.
DistanceField3D(int width, int height, int depth, float cellSize, float originX, float originY, float originZ, float outsideDistance)
Distance field 3 d.
void setDistanceRegion(int x, int y, int z, int width, int height, int depth, const std::vector< float > &distances)
Atomically replace a grid subregion in x-fastest, then y, then z order.
void setMoverSkinWidth(float width)
Set the non-negative separation retained from surfaces by moveCapsule.
void setDistance(int x, int y, int z, float distance)
Set a signed-distance sample at a grid vertex.
bool checkSphere(float x, float y, float z, float radius)
Test a sphere against the solid (distance <= radius).
void setMoverStepHeight(float height)
Set the maximum non-negative ledge height automatically climbed by moveCapsule.
float sample(float x, float y, float z) const
Trilinearly sample the field in world coordinates.
float getDistance(int x, int y, int z) const
Read a grid vertex; out-of-range vertices return the outside distance.
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36