载入中...
搜索中...
未找到
VoronoiCook.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <cstdint>
6#include <limits>
7#include <map>
8#include <utility>
13namespace {
14struct Vec {
15 double x = 0, y = 0, z = 0;
16 Vec operator+(Vec b) const { return {x + b.x, y + b.y, z + b.z}; }
17 Vec operator-(Vec b) const { return {x - b.x, y - b.y, z - b.z}; }
18 Vec operator*(double s) const { return {x * s, y * s, z * s}; }
19};
20double dot(Vec a, Vec b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
21Vec cross(Vec a, Vec b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
22double length(Vec a) { return std::sqrt(dot(a, a)); }
23struct Face {
24 std::vector<Vec> points;
25 int neighbor = -1;
26};
27using Poly = std::vector<Face>;
28Diagnostic bad(const char* message) { return Diagnostic::error(DiagnosticCode::InvalidArgument, message, "voronoi"); }
29Vec point(const FractureFragment& f, std::uint32_t i) {
30 return {f.positions[3 * i], f.positions[3 * i + 1], f.positions[3 * i + 2]};
31}
32void uniquePush(std::vector<Vec>& points, Vec p, double eps) {
33 for (auto q : points)
34 if (length(p - q) <= eps) return;
35 points.push_back(p);
36}
37std::uint32_t vertex(FractureFragment& f, Vec p, double eps) {
38 for (std::uint32_t i = 0; i < f.positions.size() / 3; ++i)
39 if (length(p - point(f, i)) <= eps) return i;
40 const auto result = static_cast<std::uint32_t>(f.positions.size() / 3);
41 f.positions.insert(f.positions.end(), {static_cast<float>(p.x), static_cast<float>(p.y), static_cast<float>(p.z)});
42 return result;
43}
44// Merge coplanar source triangles before clipping. Otherwise triangle diagonals
45// create almost-collinear cap vertices and ill-conditioned sliver triangles.
46std::vector<Vec> boundary(std::vector<Vec> points, Vec n, double eps) {
47 const Vec helper = std::abs(n.x) < .8 ? Vec{1, 0, 0} : Vec{0, 1, 0};
48 Vec u = cross(helper, n);
49 u = u * (1.0 / length(u));
50 const Vec v = cross(n, u);
51 std::sort(points.begin(), points.end(), [&](Vec a, Vec b) {
52 const double ax = dot(a, u), bx = dot(b, u);
53 return ax == bx ? dot(a, v) < dot(b, v) : ax < bx;
54 });
55 auto turn = [&](Vec a, Vec b, Vec c) { return dot(cross(b - a, c - a), n); };
56 std::vector<Vec> hull;
57 for (auto p : points) {
58 while (hull.size() >= 2 && turn(hull[hull.size() - 2], hull.back(), p) <= eps * eps) hull.pop_back();
59 hull.push_back(p);
60 }
61 const auto lower = hull.size();
62 for (std::size_t i = points.size() - 1; i > 0; --i) {
63 const auto p = points[i - 1];
64 while (hull.size() > lower && turn(hull[hull.size() - 2], hull.back(), p) <= eps * eps) hull.pop_back();
65 hull.push_back(p);
66 }
67 if (!hull.empty()) hull.pop_back();
68 return hull;
69}
70Poly sourceFaces(const FractureFragment& source, double eps) {
71 struct Group {
72 Vec n;
73 double d;
74 std::vector<Vec> points;
75 };
76 std::vector<Group> groups;
77 for (std::size_t t = 0; t < source.indices.size(); t += 3) {
78 const Vec a = point(source, source.indices[t]), b = point(source, source.indices[t + 1]),
79 c = point(source, source.indices[t + 2]);
80 Vec n = cross(b - a, c - a);
81 n = n * (1.0 / length(n));
82 const double d = dot(n, a);
83 auto found = std::find_if(groups.begin(), groups.end(),
84 [&](const Group& g) { return dot(g.n, n) > 1 - 1e-10 && std::abs(g.d - d) < eps; });
85 if (found == groups.end()) {
86 groups.push_back({n, d, {}});
87 found = groups.end() - 1;
88 }
89 uniquePush(found->points, a, eps);
90 uniquePush(found->points, b, eps);
91 uniquePush(found->points, c, eps);
92 }
93 Poly faces;
94 for (auto& g : groups) faces.push_back({boundary(std::move(g.points), g.n, eps), -1});
95 return faces;
96}
97// Keep n dot x <= d. The new cap points outwards towards the removed half-space.
98Poly clip(const Poly& input, Vec n, double d, int neighbor, double eps) {
99 Poly result;
100 std::vector<Vec> cap;
101 for (const auto& face : input) {
102 Face out{{}, face.neighbor};
103 for (std::size_t i = 0; i < face.points.size(); ++i) {
104 const Vec a = face.points[i], b = face.points[(i + 1) % face.points.size()];
105 const double da = dot(n, a) - d, db = dot(n, b) - d;
106 const bool ina = da <= eps, inb = db <= eps;
107 if (ina) uniquePush(out.points, a, eps);
108 if (ina != inb) {
109 const Vec q = a + (b - a) * (da / (da - db));
110 uniquePush(out.points, q, eps);
111 uniquePush(cap, q, eps);
112 }
113 if (std::abs(da) <= eps) uniquePush(cap, a, eps);
114 }
115 if (out.points.size() >= 3) result.push_back(std::move(out));
116 }
117 if (cap.size() >= 3) {
118 cap = boundary(std::move(cap), n, eps);
119 if (cap.size() >= 3) result.push_back({std::move(cap), neighbor});
120 }
121 return result;
122}
123struct Rng {
124 std::uint64_t state;
125 std::uint64_t next() {
126 auto z = (state += 0x9e3779b97f4a7c15ULL);
127 z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
128 z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
129 return z ^ (z >> 31);
130 }
131 double unit() { return static_cast<double>(next() >> 11) / 9007199254740992.0; }
132};
133std::uint64_t seed(const FractureRecipe& r) {
134 auto h = 0xcbf29ce484222325ULL ^ r.seed;
135 for (unsigned char c : r.randomStreamName) {
136 h ^= c;
137 h *= 0x100000001b3ULL;
138 }
139 return h;
140}
141Result<FractureFragment> sourceMesh(const eve::asset::CanonicalMeshData& mesh, Vec& origin, Vec& lo, Vec& hi,
142 double& eps) {
143 if (mesh.positions.size() % 3 || mesh.positions.size() < 12 || mesh.positions.size() > 12288 ||
144 mesh.indices.empty() || mesh.indices.size() % 3 || mesh.indices.size() > 384)
145 return Result<FractureFragment>::failure(bad("source mesh exceeds convex cook budget or is incomplete"));
146 lo = {1e300, 1e300, 1e300};
147 hi = {-1e300, -1e300, -1e300};
148 for (std::size_t i = 0; i < mesh.positions.size(); i += 3) {
149 Vec p{mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]};
150 if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z))
151 return Result<FractureFragment>::failure(bad("nonfinite source mesh"));
152 lo = {std::min(lo.x, p.x), std::min(lo.y, p.y), std::min(lo.z, p.z)};
153 hi = {std::max(hi.x, p.x), std::max(hi.y, p.y), std::max(hi.z, p.z)};
154 }
155 origin = (lo + hi) * .5;
156 lo = lo - origin;
157 hi = hi - origin;
158 eps = std::max({hi.x - lo.x, hi.y - lo.y, hi.z - lo.z}) * 1e-7;
159 if (!(eps > 0) || eps > 1000) return Result<FractureFragment>::failure(bad("unsupported source scale"));
160 FractureFragment f;
161 for (auto i : mesh.indices) {
162 if (i >= mesh.positions.size() / 3) return Result<FractureFragment>::failure(bad("invalid triangle index"));
163 Vec p{mesh.positions[3 * i], mesh.positions[3 * i + 1], mesh.positions[3 * i + 2]};
164 f.indices.push_back(vertex(f, p - origin, eps));
165 }
166 f.materials.resize(f.indices.size() / 3, 0);
167 double volume = 0;
168 for (std::size_t t = 0; t < f.indices.size(); t += 3)
169 volume += dot(point(f, f.indices[t]), cross(point(f, f.indices[t + 1]), point(f, f.indices[t + 2]))) / 6;
170 if (volume < 0)
171 for (std::size_t t = 0; t < f.indices.size(); t += 3) std::swap(f.indices[t + 1], f.indices[t + 2]);
172 FractureGeometry check;
173 check.fragments.push_back(f);
174 auto valid = check.validate();
175 if (!valid) return Result<FractureFragment>::failure(valid.status());
176 return Result<FractureFragment>::success(std::move(f));
177}
178eve::asset::CanonicalMeshData box(float x, float y, float z) {
180 m.positions = {-x, -y, -z, x, -y, -z, x, y, -z, -x, y, -z, -x, -y, z, x, -y, z, x, y, z, -x, y, z};
181 m.indices = {0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4,
182 3, 7, 6, 3, 6, 2, 0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5};
183 return m;
184}
185} // namespace
187 auto rv = recipe.validate();
188 if (!rv) return Result<FracturedCollection>::failure(rv.status());
190 recipe.siteCountMax > 64 || recipe.siteCountMax > recipe.maximumBones)
192 bad("convex Voronoi cook requires 1..64 sites within maximumBones"));
193 Vec origin, lo, hi;
194 double eps = 0;
195 auto source = sourceMesh(mesh, origin, lo, hi, eps);
197 if (std::min({hi.x - lo.x, hi.y - lo.y, hi.z - lo.z}) < recipe.minimumThickness)
198 return Result<FracturedCollection>::failure(bad("source is thinner than minimumThickness"));
199 Poly original = sourceFaces(source.value(), eps);
200 Rng rng{seed(recipe)};
201 const int count =
202 recipe.siteCountMin +
203 static_cast<int>(rng.next() % static_cast<std::uint64_t>(recipe.siteCountMax - recipe.siteCountMin + 1));
204 auto inside = [&](Vec p) {
205 for (const auto& f : original) {
206 Vec n = cross(f.points[1] - f.points[0], f.points[2] - f.points[0]);
207 if (dot(n, p - f.points[0]) > eps * length(n)) return false;
208 }
209 return true;
210 };
211 auto uniform = [&]() {
212 return Vec{lo.x + (hi.x - lo.x) * rng.unit(), lo.y + (hi.y - lo.y) * rng.unit(),
213 lo.z + (hi.z - lo.z) * rng.unit()};
214 };
215 std::vector<Vec> centers, sites;
216 std::vector<int> clusters;
218 for (int c = 0; c < recipe.clusterCount; ++c) {
219 bool found = false;
220 for (int trial = 0; trial < 10000; ++trial) {
221 auto p = uniform();
222 if (inside(p)) {
223 centers.push_back(p);
224 found = true;
225 break;
226 }
227 }
228 if (!found) return Result<FracturedCollection>::failure(bad("cannot place cluster center inside source"));
229 }
230 }
231 for (int i = 0; i < count; ++i) {
232 bool found = false;
233 const int cluster = centers.empty() ? 0 : i % recipe.clusterCount;
234 for (int trial = 0; trial < 10000; ++trial) {
235 Vec p = uniform();
236 if (!centers.empty()) {
237 auto c = centers[static_cast<std::size_t>(cluster)];
238 p = c + Vec{(rng.unit() * 2 - 1) * recipe.clusterRadius, (rng.unit() * 2 - 1) * recipe.clusterRadius,
239 (rng.unit() * 2 - 1) * recipe.clusterRadius};
240 }
241 if (!inside(p)) continue;
242 bool duplicate = false;
243 for (auto q : sites)
244 if (length(q - p) < eps * 100) {
245 duplicate = true;
246 break;
247 }
248 if (duplicate) continue;
249 sites.push_back(p);
250 clusters.push_back(cluster);
251 found = true;
252 break;
253 }
254 if (!found)
255 return Result<FracturedCollection>::failure(bad("cannot place distinct Voronoi sites inside source"));
256 }
258 std::map<std::pair<int, int>, double> contacts;
259 for (int i = 0; i < count; ++i) {
260 Poly cell = original;
261 for (int j = 0; j < count; ++j)
262 if (i != j) {
263 const Vec diff = sites[static_cast<std::size_t>(j)] - sites[static_cast<std::size_t>(i)];
264 const double len = length(diff);
265 const Vec n = diff * (1.0 / len);
266 const double d = dot(n, (sites[static_cast<std::size_t>(i)] + sites[static_cast<std::size_t>(j)]) * .5);
267 cell = clip(cell, n, d, j, eps);
268 if (cell.empty()) return Result<FracturedCollection>::failure(bad("Voronoi produced empty cell"));
269 }
270 Vec center;
271 std::size_t points = 0;
272 for (const auto& f : cell)
273 for (auto p : f.points) {
274 center = center + p;
275 ++points;
276 }
277 center = center * (1.0 / static_cast<double>(points));
278 FractureFragment fragment;
279 double volume = 0;
280 Vec extents;
281 for (const auto& face : cell) {
282 Vec faceCenter;
283 for (auto p : face.points) faceCenter = faceCenter + p;
284 faceCenter = faceCenter * (1.0 / static_cast<double>(face.points.size()));
285 double area = 0;
286 for (std::size_t k = 0; k < face.points.size(); ++k) {
287 Vec a = faceCenter - center, b = face.points[k] - center,
288 c = face.points[(k + 1) % face.points.size()] - center;
289 const double triArea = length(cross(b - a, c - a)) * .5;
290 if (triArea <= eps * eps) continue;
291 const auto ia = vertex(fragment, a, eps), ib = vertex(fragment, b, eps), ic = vertex(fragment, c, eps);
292 fragment.indices.insert(fragment.indices.end(), {ia, ib, ic});
293 fragment.materials.push_back(face.neighbor < 0 ? 0U : 1U);
294 volume += dot(a, cross(b, c)) / 6;
295 area += triArea;
296 }
297 if (face.neighbor >= 0 && i < face.neighbor && area > eps * eps * 10) contacts[{i, face.neighbor}] = area;
298 }
299 for (std::uint32_t k = 0; k < fragment.positions.size() / 3; ++k) {
300 auto v = point(fragment, k);
301 extents = {std::max(extents.x, std::abs(v.x)), std::max(extents.y, std::abs(v.y)),
302 std::max(extents.z, std::abs(v.z))};
303 }
305 bone.localX = static_cast<float>(origin.x + center.x);
306 bone.localY = static_cast<float>(origin.y + center.y);
307 bone.localZ = static_cast<float>(origin.z + center.z);
308 bone.halfExtentX = static_cast<float>(extents.x);
309 bone.halfExtentY = static_cast<float>(extents.y);
310 bone.halfExtentZ = static_cast<float>(extents.z);
311 bone.mass = static_cast<float>(volume * recipe.defaultDensity);
312 bone.density = recipe.defaultDensity;
313 bone.friction = recipe.defaultFriction;
314 bone.restitution = recipe.defaultRestitution;
315 bone.clusterId = clusters[static_cast<std::size_t>(i)];
316 result.collection.bones.push_back(bone);
317 result.geometry.fragments.push_back(std::move(fragment));
318 }
319 for (const auto& [pair, area] : contacts) {
320 (void)area;
321 float threshold = recipe.defaultStrainThreshold;
323 threshold *=
324 clusters[static_cast<std::size_t>(pair.first)] == clusters[static_cast<std::size_t>(pair.second)] ? 2.f
325 : .5f;
326 result.collection.edges.push_back({pair.first, pair.second, threshold});
327 }
328 auto gv = result.geometry.validate();
329 if (!gv) return Result<FracturedCollection>::failure(gv.status());
330 auto av = result.collection.validate();
331 if (!av) return Result<FracturedCollection>::failure(av.status());
333}
341 auto validSettings = settings.validate();
342 if (!validSettings) return Result<FracturedCollection>::failure(validSettings.status());
343 const auto& recipe = settings.recipe;
344 auto av = assembly.validate();
345 if (!av) return Result<FracturedCollection>::failure(av.status());
346 auto policyFor = [&](std::size_t i) {
347 FractureComponentPolicy policy{0, recipe.defaultStrainThreshold, 1.f};
348 if (auto g = settings.groups.find(assembly.bones[i].clusterId); g != settings.groups.end()) policy = g->second;
349 if (auto c = settings.components.find(static_cast<int>(i)); c != settings.components.end()) policy = c->second;
350 return policy;
351 };
352 std::size_t maximum = 0;
353 for (std::size_t i = 0; i < assembly.bones.size(); ++i) {
354 auto p = policyFor(i);
355 maximum += static_cast<std::size_t>(p.fragments ? p.fragments : recipe.siteCountMax);
356 }
357 if (maximum > static_cast<std::size_t>(recipe.maximumBones))
358 return Result<FracturedCollection>::failure(bad("assembly exceeds fragment budget"));
359 for (const auto& [id, policy] : settings.components) {
360 (void)policy;
361 if (static_cast<std::size_t>(id) >= assembly.bones.size())
362 return Result<FracturedCollection>::failure(bad("component override is outside assembly"));
363 }
365 std::vector<std::pair<int, int>> ranges;
366 for (std::size_t parent = 0; parent < assembly.bones.size(); ++parent) {
367 const auto& original = assembly.bones[parent];
368 auto r = recipe;
369 r.seed ^= static_cast<std::uint64_t>(parent) * 0x9e3779b97f4a7c15ULL;
370 const auto policy = policyFor(parent);
371 if (policy.fragments) r.siteCountMin = r.siteCountMax = policy.fragments;
372 r.defaultStrainThreshold = policy.cohesion;
373 r.defaultDensity = original.density;
374 r.defaultFriction = original.friction;
375 r.defaultRestitution = original.restitution;
376 auto cooked = cookVoronoi(box(original.halfExtentX, original.halfExtentY, original.halfExtentZ), r);
377 if (!cooked) return Result<FracturedCollection>::failure(cooked.status());
378 auto& part = cooked.value();
379 const int base = static_cast<int>(result.collection.bones.size());
380 for (auto bone : part.collection.bones) {
381 bone.localX += original.localX;
382 bone.localY += original.localY;
383 bone.localZ += original.localZ;
384 bone.anchoredDefault = original.anchoredDefault;
385 if (r.mode == FractureMode::UniformVoronoi) bone.clusterId = original.clusterId;
386 result.collection.bones.push_back(bone);
387 }
388 for (auto edge : part.collection.edges) {
389 edge.boneA += base;
390 edge.boneB += base;
391 result.collection.edges.push_back(edge);
392 }
393 for (auto& mesh : part.geometry.fragments) result.geometry.fragments.push_back(std::move(mesh));
394 ranges.push_back({base, static_cast<int>(result.collection.bones.size())});
395 }
396 // Preserve explicit authoring supports; do not invent support between unrelated components.
397 for (const auto& parent : assembly.edges) {
398 auto [a0, a1] = ranges[static_cast<std::size_t>(parent.boneA)];
399 auto [b0, b1] = ranges[static_cast<std::size_t>(parent.boneB)];
400 for (int a = a0; a < a1; ++a)
401 for (int b = b0; b < b1; ++b) {
402 const auto& x = result.collection.bones[static_cast<std::size_t>(a)];
403 const auto& y = result.collection.bones[static_cast<std::size_t>(b)];
404 if (std::abs(x.localX - y.localX) <= x.halfExtentX + y.halfExtentX + settings.contactTolerance &&
405 std::abs(x.localY - y.localY) <= x.halfExtentY + y.halfExtentY + settings.contactTolerance &&
406 std::abs(x.localZ - y.localZ) <= x.halfExtentZ + y.halfExtentZ + settings.contactTolerance)
407 result.collection.edges.push_back(
408 {a, b,
409 parent.strainThreshold *
410 std::min(policyFor(static_cast<std::size_t>(parent.boneA)).connectionStrength,
411 policyFor(static_cast<std::size_t>(parent.boneB)).connectionStrength)});
412 }
413 }
414 auto valid = result.collection.validate();
415 if (!valid) return Result<FracturedCollection>::failure(valid.status());
417}
418} // namespace eve::physics::destruction_cook
double z
double y
double m[16]
double x
double volume
const std::string & s
std::vector< V3 > centers
Definition BushMesh.cpp:100
glm::vec4 p[6]
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
float maximum[3]
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec4 clip
float u
Definition Grass.cpp:233
float area
Definition Grass.cpp:62
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
std::vector< std::uint32_t > indices
float v
std::int32_t c
int h
float length
const ColourScope * parent
std::uint32_t bone
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
OceanMeshSettings mesh
glm::dvec3 origin
glm::dvec2 center
uint32_t groups
Definition OnnxGpgpu.cpp:39
BakeRecipe recipe
float f
std::shared_ptr< const std::vector< glm::vec2 > > points
float d
float t
bool found
ScriptStructure out
std::string_view source
int count
Cell cell
TacticalUnit * unit
CommandLogBoundary boundary
Anchor rule, see above.
TacticalUnit::TurnResources turn
uint32_t seed
Definition TreeMesh.cpp:276
std::vector< char > inside
glm::vec3 point
int neighbor
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
Vec3 operator-(Vec3 lhs, Vec3 rhs)
Operator -.
Vec3 operator*(Vec3 value, float scale)
Operator *.
eve::Diagnostic Diagnostic
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Result< FracturedCollection > cookVoronoi(const eve::asset::CanonicalMeshData &mesh, const FractureRecipe &recipe)
Intersect a closed convex source mesh with seeded Voronoi half-spaces.
Result< FracturedCollection > cookVoronoiAssembly(const GeometryCollectionAsset &assembly, const FractureRecipe &recipe)
Prefracture each box in an authored assembly and preserve declared parent supports....
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
Owning CPU mesh snapshot; UV arrays are packed ST pairs indexed by source set number....
std::vector< float > positions
Owning closed convex fragment in body-local metres; outward triangle winding. Each triangle has mater...
std::vector< std::uint32_t > indices
std::vector< std::uint32_t > materials
Versioned cook recipe for Chaos-style pre-fracture (schema v1).
Immutable cooked/authored geometry-collection asset.
std::vector< GeometryCollectionEdge > edges
std::vector< GeometryCollectionBone > bones
eve::Result< void > validate() const
Validate bone/edge topology and numeric ranges.
One pre-authored leaf bone (box collision proxy) inside a geometry collection.
Offline assembly settings; per-component policy overrides its authored cluster policy....
Independent controls for mesh granularity, internal cohesion and parent-joint strength.
Complete owning fracture asset: graph, body origins and exact convex geometry.
Definition VoronoiCook.h:16