载入中...
搜索中...
未找到
ConvexHull.cpp
浏览该文件的文档.
1#include "math/ConvexHull.h"
2
3#include <algorithm>
4#include <cmath>
5#include <map>
6#include <utility>
7
8namespace eve::math {
9namespace {
10using Point = std::array<double, 3>;
11
12Point sub(const Point& a, const Point& b) { return {a[0] - b[0], a[1] - b[1], a[2] - b[2]}; }
13Point cross(const Point& a, const Point& b) {
14 return {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]};
15}
16double dot(const Point& a, const Point& b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
17double norm(const Point& a) { return std::sqrt(dot(a, a)); }
18
19template <class P>
20bool finite(const P& p) {
21 return std::all_of(p.begin(), p.end(), [](auto x) { return std::isfinite(x); });
22}
23
24template <class P>
25std::vector<P> uniquePoints(std::span<const P> input) {
26 std::vector<P> points(input.begin(), input.end());
27 std::sort(points.begin(), points.end());
28 points.erase(std::unique(points.begin(), points.end()), points.end());
29 return points;
30}
31
32// Projected values carry an original vertex index alongside the XY coordinates.
33template <class P>
34std::vector<P> chain(const std::vector<P>& points) {
35 if (points.size() <= 1) return points;
36 auto turn = [](const P& a, const P& b, const P& c) {
37 return (double(b[0]) - a[0]) * (double(c[1]) - a[1]) - (double(b[1]) - a[1]) * (double(c[0]) - a[0]);
38 };
39 std::vector<P> hull;
40 for (const auto& p : points) {
41 while (hull.size() >= 2 && turn(hull[hull.size() - 2], hull.back(), p) <= 0) hull.pop_back();
42 hull.push_back(p);
43 }
44 const auto lower = hull.size();
45 for (auto it = points.rbegin() + 1; it != points.rend(); ++it) {
46 while (hull.size() > lower && turn(hull[hull.size() - 2], hull.back(), *it) <= 0) hull.pop_back();
47 hull.push_back(*it);
48 }
49 hull.pop_back();
50 return hull;
51}
52
53template <class T>
54Result<T> invalid(const char* message, const char* path) {
56}
57} // namespace
58
59Result<ConvexHull2D> convexHull2D(std::span<const HullPoint2> points) {
60 for (const auto& p : points)
61 if (!finite(p)) return invalid<ConvexHull2D>("Hull coordinates must be finite", "points");
62 ConvexHull2D hull;
63 hull.vertices = chain(uniquePoints(points));
64 switch (hull.vertices.size()) {
65 case 0: hull.dimension = HullDimension::Empty; break;
66 case 1: hull.dimension = HullDimension::Point; break;
67 case 2: hull.dimension = HullDimension::Segment; break;
68 default: hull.dimension = HullDimension::Plane; break;
69 }
70 return Result<ConvexHull2D>::success(std::move(hull));
71}
72
73Result<ConvexHull3D> convexHull3D(std::span<const HullPoint3> input, double tolerance) {
74 if (!std::isfinite(tolerance) || tolerance < 0 || tolerance >= 1)
75 return invalid<ConvexHull3D>("Hull tolerance must be finite and in [0, 1)", "tolerance");
76 for (const auto& p : input)
77 if (!finite(p)) return invalid<ConvexHull3D>("Hull coordinates must be finite", "points");
78 const auto original = uniquePoints(input);
79 ConvexHull3D hull;
80 if (original.size() <= 1) {
81 hull.dimension = original.empty() ? HullDimension::Empty : HullDimension::Point;
82 hull.vertices = original;
83 return Result<ConvexHull3D>::success(std::move(hull));
84 }
85 double scale = 0;
86 for (std::size_t k = 0; k < 3; ++k) {
87 auto [lo, hi] = std::minmax_element(original.begin(), original.end(),
88 [k](const auto& a, const auto& b) { return a[k] < b[k]; });
89 scale = std::max(scale, double((*hi)[k]) - (*lo)[k]);
90 }
91 std::vector<Point> pts;
92 pts.reserve(original.size());
93 for (const auto& p : original)
94 pts.push_back({(double(p[0]) - original[0][0]) / scale, (double(p[1]) - original[0][1]) / scale,
95 (double(p[2]) - original[0][2]) / scale});
96 auto farthest = [&](auto distance) {
97 std::size_t best = 0;
98 double maximum = -1;
99 for (std::size_t i = 0; i < pts.size(); ++i) {
100 const double value = distance(i);
101 if (value > maximum) {
102 maximum = value;
103 best = i;
104 }
105 }
106 return best;
107 };
108 const std::size_t a = 0;
109 const auto b = farthest([&](auto i) { return norm(sub(pts[i], pts[a])); });
110 const auto ab = sub(pts[b], pts[a]);
111 const auto c = farthest([&](auto i) { return norm(cross(ab, sub(pts[i], pts[a]))); });
112 const auto normal = cross(ab, sub(pts[c], pts[a]));
113 if (norm(normal) <= tolerance * norm(ab)) {
114 const auto lo = farthest([&](auto i) { return -dot(pts[i], ab); });
115 const auto hi = farthest([&](auto i) { return dot(pts[i], ab); });
116 hull.dimension = HullDimension::Segment;
117 hull.vertices = {original[lo], original[hi]};
118 return Result<ConvexHull3D>::success(std::move(hull));
119 }
120 const auto d = farthest([&](auto i) { return std::abs(dot(normal, sub(pts[i], pts[a]))); });
121 if (std::abs(dot(normal, sub(pts[d], pts[a]))) <= tolerance * norm(normal)) {
122 std::size_t drop = 0;
123 for (std::size_t k = 1; k < 3; ++k)
124 if (std::abs(normal[k]) > std::abs(normal[drop])) drop = k;
125 const auto x = (drop + 1) % 3, y = (drop + 2) % 3;
126 // Index travels with the projection without conversion to floating point.
127 struct Projected {
128 double x, y;
129 std::size_t index;
130 double operator[](std::size_t k) const { return k == 0 ? x : y; }
131 };
132 std::vector<Projected> projected;
133 projected.reserve(pts.size());
134 for (std::size_t i = 0; i < pts.size(); ++i) projected.push_back({pts[i][x], pts[i][y], i});
135 std::sort(projected.begin(), projected.end(), [](const auto& p, const auto& q) {
136 if (p.x != q.x) return p.x < q.x;
137 if (p.y != q.y) return p.y < q.y;
138 return p.index < q.index;
139 });
140 // Projection can collapse distinct nearly planar points.
141 projected.erase(std::unique(projected.begin(), projected.end(),
142 [](const auto& p, const auto& q) { return p.x == q.x && p.y == q.y; }),
143 projected.end());
144 hull.dimension = HullDimension::Plane;
145 for (const auto& p : chain(projected)) hull.vertices.push_back(original[p.index]);
146 for (std::size_t i = 1; i + 1 < hull.vertices.size(); ++i) hull.faces.push_back({0, i, i + 1});
147 return Result<ConvexHull3D>::success(std::move(hull));
148 }
149 Point inside{};
150 for (auto i : {a, b, c, d})
151 for (std::size_t k = 0; k < 3; ++k) inside[k] += pts[i][k] / 4;
152 auto normalOf = [&](const HullTriangle& f) { return cross(sub(pts[f[1]], pts[f[0]]), sub(pts[f[2]], pts[f[0]])); };
153 auto outward = [&](std::size_t i, std::size_t j, std::size_t k) {
154 HullTriangle f{i, j, k};
155 if (dot(normalOf(f), sub(inside, pts[i])) > 0) std::swap(f[1], f[2]);
156 return f;
157 };
158 std::vector<HullTriangle> faces{outward(a, b, c), outward(a, d, b), outward(a, c, d), outward(b, d, c)};
159 for (std::size_t p = 0; p < pts.size(); ++p) {
160 if (p == a || p == b || p == c || p == d) continue;
161 std::map<std::pair<std::size_t, std::size_t>, std::pair<std::size_t, std::size_t>> horizon;
162 std::vector<HullTriangle> retained;
163 bool visible = false;
164 for (const auto& f : faces) {
165 const auto n = normalOf(f);
166 if (dot(n, sub(pts[p], pts[f[0]])) <= tolerance * norm(n)) {
167 retained.push_back(f);
168 continue;
169 }
170 visible = true;
171 for (std::size_t e = 0; e < 3; ++e) {
172 const auto u = f[e], v = f[(e + 1) % 3];
173 const std::pair<std::size_t, std::size_t> key{std::min(u, v), std::max(u, v)};
174 if (horizon.erase(key) == 0) horizon.emplace(key, std::make_pair(u, v));
175 }
176 }
177 if (!visible) continue;
178 for (const auto& edge : horizon) retained.push_back(outward(edge.second.first, edge.second.second, p));
179 faces = std::move(retained);
180 }
181 std::vector<std::size_t> remap(pts.size(), pts.size());
182 for (const auto& f : faces)
183 for (auto i : f) remap[i] = 0;
184 for (std::size_t i = 0; i < pts.size(); ++i)
185 if (remap[i] == 0) {
186 remap[i] = hull.vertices.size();
187 hull.vertices.push_back(original[i]);
188 }
189 hull.dimension = HullDimension::Volume;
190 for (const auto& f : faces) hull.faces.push_back({remap[f[0]], remap[f[1]], remap[f[2]]});
191 return Result<ConvexHull3D>::success(std::move(hull));
192}
193} // namespace eve::math
double y
double x
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
float maximum[3]
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
std::uint32_t ab
float v
std::int32_t second
std::int32_t c
std::int32_t first
std::array< float, 3 > scale
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
bool finite
float f
std::string path
Definition PlayHost.cpp:111
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float d
std::unordered_map< std::uint32_t, std::uint32_t > remap
std::map< Cell, int > best
TacticalUnit::TurnResources turn
std::array< double, 2 > vertices[3]
bool visible
uint32_t index
std::vector< char > inside
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
eve::Diagnostic Diagnostic
Status invalid(const char *message)
Result< ConvexHull3D > convexHull3D(std::span< const HullPoint3 > input, double tolerance)
Incremental 3D hull with outward triangles and compact vertex indices.
Result< ConvexHull2D > convexHull2D(std::span< const HullPoint2 > points)
Andrew monotone-chain hull; removes exact duplicates and collinear edge interiors.
std::array< std::size_t, 3 > HullTriangle
Triangle indices into the returned vertex array.
Definition ConvexHull.h:18
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Vec3 sub(Vec3 a, Vec3 b)
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
Self-contained 2D hull; vertices are CCW, with no repeated closing point.
Definition ConvexHull.h:24
HullDimension dimension
Definition ConvexHull.h:25
std::vector< HullPoint2 > vertices
Definition ConvexHull.h:26
Self-contained 3D hull; volume triangles face outward.
Definition ConvexHull.h:30
HullDimension dimension
Definition ConvexHull.h:31
std::vector< HullPoint3 > vertices
Definition ConvexHull.h:32