载入中...
搜索中...
未找到
ArrowGenerator.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6#include <map>
7#include <numbers>
8#include <string>
9#include <vector>
10
11namespace eve::procgen {
12namespace {
13using V = std::array<double, 3>;
14V add(V a, V b) { return {a[0] + b[0], a[1] + b[1], a[2] + b[2]}; }
15V sub(V a, V b) { return {a[0] - b[0], a[1] - b[1], a[2] - b[2]}; }
16V mul(V a, double s) { return {a[0] * s, a[1] * s, a[2] * s}; }
17double dot(V a, V b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
18V cross(V a, V b) { 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]}; }
19double length(V a) { return std::sqrt(dot(a, a)); }
20V unit(V a) { return mul(a, 1. / length(a)); }
21bool valid(V a) {
22 return std::all_of(a.begin(), a.end(), [](double v) { return std::isfinite(v) && std::abs(v) <= 1e6; });
23}
24Diagnostic invalid(std::string message = "Invalid arrow parameters or degenerate path") {
25 return Diagnostic::error(DiagnosticCode::InvalidArgument, std::move(message), "arrow", {}, "procgen.arrow");
26}
27void triangle(MeshBuild& mesh, V a, V b, V c, double u0, double u1, double u2) {
28 const V n = unit(cross(sub(b, a), sub(c, a)));
29 const auto base = static_cast<uint32_t>(mesh.getVertexCount());
30 const V points[]{a, b, c};
31 const double us[]{u0, u1, u2};
32 for (int i = 0; i < 3; ++i)
33 mesh.addVertex(static_cast<float>(points[i][0]), static_cast<float>(points[i][1]),
34 static_cast<float>(points[i][2]), static_cast<float>(n[0]), static_cast<float>(n[1]),
35 static_cast<float>(n[2]), static_cast<float>(us[i]), i == 0 ? 0.f : 1.f);
36 mesh.addTriangle(base, base + 1, base + 2);
37}
38void quad(MeshBuild& m, V a, V b, V c, V d, double u, double v) {
39 triangle(m, a, b, c, u, u, v);
40 triangle(m, a, c, d, u, v, v);
41}
42double flowingRatio(double t) { return 0.08 + 0.92 * std::sin(t * std::numbers::pi * 0.5); }
43struct PathSample {
44 double progress, lateral;
45};
46PathSample samplePath(V p, const std::vector<V>& path, const std::vector<double>& arc) {
47 double best = std::numeric_limits<double>::max(), result = 1.;
48 for (std::size_t i = 0; i + 1 < path.size(); ++i) {
49 const V delta = sub(path[i + 1], path[i]);
50 const double t = std::clamp(dot(sub(p, path[i]), delta) / dot(delta, delta), 0., 1.);
51 const V difference = sub(p, add(path[i], mul(delta, t)));
52 const double squared = dot(difference, difference);
53 if (squared < best) {
54 best = squared;
55 result = (arc[i] + (arc[i + 1] - arc[i]) * t) / arc.back();
56 }
57 }
58 const double z = p[2] - path.front()[2];
59 return {result, std::sqrt(std::max(0., best - z * z))};
60}
61// Closed thin extrusion with rounded outline corners and quarter-round rim bevels.
62double turn(V a, V b, V c) { return cross(sub(b, a), sub(c, a))[2]; }
63Result<MeshBuild> flatArrow(const std::vector<V>& path, const std::vector<V>& normals, V tip, double shaft, double head,
64 double thickness, double radius, int steps, bool flowing) {
65 if (radius >= shaft * 0.25) return Result<MeshBuild>::failure(invalid());
66 std::vector<double> arc;
67 arc.reserve(path.size());
68 arc.push_back(0.);
69 for (std::size_t i = 1; i < path.size(); ++i) arc.push_back(arc.back() + length(sub(path[i], path[i - 1])));
70 const auto taper = [&](double t) { return flowing ? flowingRatio(t) : 1.; };
71 const auto progress = [&](V p) { return samplePath(p, path, arc).progress; };
72 std::vector<V> outline;
73 outline.reserve(2 * path.size() + 3);
74 for (std::size_t i = 0; i < path.size(); ++i)
75 outline.push_back(sub(path[i], mul(normals[i], shaft * taper(arc[i] / arc.back()) * 0.5)));
76 outline.push_back(sub(path.back(), mul(normals.back(), head * 0.5)));
77 outline.push_back(tip);
78 outline.push_back(add(path.back(), mul(normals.back(), head * 0.5)));
79 for (std::size_t i = path.size(); i-- > 0;)
80 outline.push_back(add(path[i], mul(normals[i], shaft * taper(arc[i] / arc.back()) * 0.5)));
81 // Remove collinear samples before rounding so straight shafts remain inexpensive.
82 for (std::size_t i = 0; outline.size() > 3 && i < outline.size();) {
83 const std::size_t n = outline.size();
84 if (std::abs(turn(outline[(i + n - 1) % n], outline[i], outline[(i + 1) % n])) < 1e-12) {
85 outline.erase(outline.begin() + static_cast<std::ptrdiff_t>(i));
86 if (i > 0) --i;
87 } else
88 ++i;
89 }
90 if (flowing) {
91 // Reserve a visible fillet span at both shoulders instead of letting
92 // dense curve samples force the corner radius down to one tiny edge.
93 const V necks[]{sub(path.back(), mul(normals.back(), shaft * 0.5)),
94 add(path.back(), mul(normals.back(), shaft * 0.5))};
95 const double span = std::min(shaft * 0.7, radius * 10.);
96 for (V neck : necks) {
97 bool shortened = true;
98 while (shortened && outline.size() > 7) {
99 shortened = false;
100 const auto found = std::find(outline.begin(), outline.end(), neck);
101 const std::size_t i = static_cast<std::size_t>(found - outline.begin());
102 for (std::size_t j : {(i + outline.size() - 1) % outline.size(), (i + 1) % outline.size()}) {
103 if (length(sub(outline[j], neck)) < span && outline[j] != necks[0] && outline[j] != necks[1] &&
104 outline[j] != tip) {
105 outline.erase(outline.begin() + static_cast<std::ptrdiff_t>(j));
106 shortened = true;
107 break;
108 }
109 }
110 }
111 }
112 }
113 std::vector<V> contour;
114 for (std::size_t i = 0; i < outline.size(); ++i) {
115 const V p = outline[(i + outline.size() - 1) % outline.size()], v = outline[i],
116 q = outline[(i + 1) % outline.size()];
117 const V incoming = sub(p, v), outgoing = sub(q, v);
118 const double cosine = dot(unit(incoming), unit(outgoing));
119 const double desiredCut = 2. * radius * (flowing && v != tip ? 3. : 1.) *
120 std::sqrt(std::max(0., (1. + cosine) * 0.5)) / std::max(1e-8, (1. - cosine) * 0.5);
121 const double cut = std::min({desiredCut, length(incoming) * 0.45, length(outgoing) * 0.45});
122 const V a = add(v, mul(unit(incoming), cut)), b = add(v, mul(unit(outgoing), cut));
123 // Already smooth path samples need no additional corner subdivision.
124 if (dot(unit(incoming), unit(outgoing)) < -0.99) {
125 contour.push_back(v);
126 continue;
127 }
128 for (int j = 0; j <= steps; ++j) {
129 const double t = static_cast<double>(j) / steps;
130 contour.push_back(add(add(mul(a, (1 - t) * (1 - t)), mul(v, 2 * t * (1 - t))), mul(b, t * t)));
131 }
132 }
133 const std::size_t count = contour.size();
134 std::vector<V> insetDirections;
135 for (std::size_t i = 0; i < count; ++i) {
136 const V prev = unit(sub(contour[i], contour[(i + count - 1) % count]));
137 const V next = unit(sub(contour[(i + 1) % count], contour[i]));
138 const V n0{-prev[1], prev[0], 0.}, n1{-next[1], next[0], 0.};
139 const double denominator = 1. + dot(n0, n1);
140 if (denominator < 1e-6) return Result<MeshBuild>::failure(invalid());
141 insetDirections.push_back(mul(add(n0, n1), 1. / denominator));
142 }
143 std::vector<double> radii, thicknesses;
144 for (V point : contour) {
145 const double ratio = flowing ? taper(progress(point)) : 1.;
146 const double h = thickness;
147 thicknesses.push_back(h);
148 radii.push_back(flowing ? std::min({radius, shaft * ratio * 0.2, h * 0.45}) : radius);
149 }
150 std::vector<std::vector<V>> rings;
151 const auto appendRing = [&](double insetFactor, double sign, double riseFactor) {
152 std::vector<V> ring;
153 for (std::size_t i = 0; i < count; ++i) {
154 V v = add(contour[i], mul(insetDirections[i], radii[i] * insetFactor));
155 v[2] += sign * thicknesses[i] * 0.5 + radii[i] * riseFactor;
156 ring.push_back(v);
157 }
158 rings.push_back(std::move(ring));
159 };
160 for (int j = 0; j <= steps; ++j) {
161 const double angle = std::numbers::pi * 0.5 * j / steps;
162 appendRing(1. - std::sin(angle), -1., 1. - std::cos(angle));
163 }
164 appendRing(0., 1., -1.);
165 for (int j = 1; j <= steps; ++j) {
166 const double angle = std::numbers::pi * 0.5 * j / steps;
167 appendRing(1. - std::cos(angle), 1., std::sin(angle) - 1.);
168 }
169 // Reject overlapping inset contours instead of publishing a broken bevel.
170 for (const auto& ring : rings) {
171 for (std::size_t i = 0; i < count; ++i)
172 for (std::size_t j = i + 2; j < count; ++j) {
173 if (i == 0 && j + 1 == count) continue;
174 const V a = ring[i], b = ring[(i + 1) % count], c = ring[j], d = ring[(j + 1) % count];
175 if (turn(a, b, c) * turn(a, b, d) < 0. && turn(c, d, a) * turn(c, d, b) < 0.)
176 return Result<MeshBuild>::failure(invalid("Flat arrow inset intersects itself at edges " +
177 std::to_string(i) + ", " + std::to_string(j)));
178 }
179 }
180 MeshBuild mesh;
181 mesh.setActiveGroup("bevel");
182 for (std::size_t r = 0; r + 1 < rings.size(); ++r)
183 for (std::size_t i = 0; i < count; ++i) {
184 const std::size_t j = (i + 1) % count;
185 quad(mesh, rings[r][i], rings[r][j], rings[r + 1][j], rings[r + 1][i], 0., 1.);
186 }
187 mesh.setActiveGroup("face");
188 std::vector<std::size_t> remaining;
189 remaining.reserve(count);
190 for (std::size_t i = 0; i < count; ++i) remaining.push_back(i);
191 const auto& top = rings.back();
192 const auto& bottom = rings.front();
193 while (remaining.size() > 2) {
194 bool clipped = false;
195 for (std::size_t i = 0; i < remaining.size(); ++i) {
196 const auto a = remaining[(i + remaining.size() - 1) % remaining.size()], b = remaining[i],
197 c = remaining[(i + 1) % remaining.size()];
198 if (turn(top[a], top[b], top[c]) <= 1e-12) continue;
199 bool occupied = false;
200 for (auto k : remaining) {
201 if (k == a || k == b || k == c) continue;
202 if (turn(top[a], top[b], top[k]) >= -1e-12 && turn(top[b], top[c], top[k]) >= -1e-12 &&
203 turn(top[c], top[a], top[k]) >= -1e-12) {
204 occupied = true;
205 break;
206 }
207 }
208 if (occupied) continue;
209 triangle(mesh, top[a], top[b], top[c], 0., 0.5, 1.);
210 triangle(mesh, bottom[c], bottom[b], bottom[a], 1., 0.5, 0.);
211 remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(i));
212 clipped = true;
213 break;
214 }
215 if (!clipped) return Result<MeshBuild>::failure(invalid("Flat arrow cap cannot be triangulated"));
216 }
217 return Result<MeshBuild>::success(std::move(mesh));
218}
219// Split the surface along the thickness transition before deformation, so cap
220// triangles cannot stretch the head's extra height across the thin shaft.
221struct HeadVertex {
223 double u, v;
224};
225MeshBuild shapeFlatSurface(const MeshBuild& source, V base, V axis, double length, double centerZ, double scale,
226 const std::vector<V>& path, bool flowing, double shaftWidth, double headWidth) {
227 MeshBuild output;
228 int active = -2;
229 const auto distance = [&](V p) { return dot(sub(p, base), axis); };
230 std::vector<double> arc{0.};
231 for (std::size_t i = 1; i < path.size(); ++i)
232 arc.push_back(arc.back() + std::sqrt(dot(sub(path[i], path[i - 1]), sub(path[i], path[i - 1]))));
233 std::vector<std::pair<V, double>> cuts;
234 if (flowing) {
235 const V chord = sub(path.back(), path.front());
236 const double chordLength = std::sqrt(dot(chord, chord));
237 const V direction = mul(chord, 1. / chordLength);
238 for (int i = 1; i < 16; ++i) cuts.emplace_back(direction, dot(path.front(), direction) + chordLength * i / 16.);
239 }
240 if (flowing) {
241 // Sample the crowned head in both directions, not only along its perimeter.
242 for (int i = 1; i < 13; ++i) cuts.emplace_back(axis, dot(base, axis) + length * i / 13.);
243 const V transverse{-axis[1], axis[0], 0.};
244 for (int i = 1; i < 10; ++i) cuts.emplace_back(transverse, dot(base, transverse) + headWidth * (i / 10. - 0.5));
245 }
246 if (scale != 1.)
247 for (int i = 0; i <= 4; ++i) cuts.emplace_back(axis, dot(base, axis) + length * (-0.25 + 0.25 * i / 4.));
248 for (int i = 0; i < source.getIndexCount(); i += 3) {
249 const int group = source.getTriangleGroup(i / 3);
250 if (group != active) {
251 output.setActiveGroup(source.getGroupName(group));
252 active = group;
253 }
254 std::vector<std::vector<HeadVertex>> polygons(1);
255 for (int j = 0; j < 3; ++j) {
256 const int index = source.getIndex(i + j);
257 polygons[0].push_back({{source.getPositionX(index), source.getPositionY(index), source.getPositionZ(index)},
258 source.getUvU(index),
259 source.getUvV(index)});
260 }
261 for (const auto& [clipAxis, plane] : cuts) {
262 const auto projection = [&](V point) { return dot(point, clipAxis); };
263 const auto intersection = [&](HeadVertex a, HeadVertex b) {
264 if (b.position < a.position) std::swap(a, b);
265 const double t = (plane - projection(a.position)) / (projection(b.position) - projection(a.position));
266 V point = add(a.position, mul(sub(b.position, a.position), t));
267 for (auto& value : point) value = static_cast<float>(value);
268 return HeadVertex{point, a.u + (b.u - a.u) * t, a.v + (b.v - a.v) * t};
269 };
270 std::vector<std::vector<HeadVertex>> next;
271 for (auto polygon : polygons) {
272 const double tolerance = length * 1e-6;
273 for (auto& vertex : polygon) {
274 const double delta = projection(vertex.position) - plane;
275 if (std::abs(delta) <= tolerance) {
276 vertex.position = sub(vertex.position, mul(clipAxis, delta));
277 for (auto& value : vertex.position) value = static_cast<float>(value);
278 }
279 }
280 double minimum = projection(polygon[0].position), maximum = minimum;
281 for (const auto& vertex : polygon) {
282 minimum = std::min(minimum, projection(vertex.position));
283 maximum = std::max(maximum, projection(vertex.position));
284 }
285 if (minimum >= plane - tolerance || maximum <= plane + tolerance) {
286 next.push_back(polygon);
287 continue;
288 }
289 std::vector<HeadVertex> low, high;
290 for (std::size_t k = 0; k < polygon.size(); ++k) {
291 const auto a = polygon[k], b = polygon[(k + 1) % polygon.size()];
292 double da = projection(a.position) - plane, db = projection(b.position) - plane;
293 if (std::abs(da) <= tolerance) da = 0.;
294 if (std::abs(db) <= tolerance) db = 0.;
295 if (da <= 0.) low.push_back(a);
296 if (da >= 0.) high.push_back(a);
297 if ((da < 0. && db > 0.) || (da > 0. && db < 0.)) {
298 const auto cut = intersection(a, b);
299 low.push_back(cut);
300 high.push_back(cut);
301 }
302 }
303 if (low.size() >= 3) next.push_back(std::move(low));
304 if (high.size() >= 3) next.push_back(std::move(high));
305 }
306 polygons = std::move(next);
307 }
308 for (auto& polygon : polygons) {
309 for (auto& vertex : polygon) {
310 const double t = std::clamp((distance(vertex.position) / length + 0.25) * 4., 0., 1.);
311 const double weight = t * t * (3. - 2. * t);
312 double taper = 1., crown = 1.;
313 if (flowing) {
314 const auto sample = samplePath(vertex.position, path, arc);
315 taper = flowingRatio(sample.progress);
316 const double headDistance = distance(vertex.position);
317 const double headHalfWidth = headWidth * 0.5 * std::clamp(1. - headDistance / length, 0., 1.);
318 const double halfWidth = (1. - weight) * shaftWidth * 0.5 * taper + weight * headHalfWidth;
319 const double lateral =
320 headDistance >= 0. ? std::abs(cross(axis, sub(vertex.position, base))[2]) : sample.lateral;
321 const double fraction = halfWidth > 1e-8 ? lateral / halfWidth : 1.;
322 crown = 1. + 0.35 * std::max(0., 1. - fraction * fraction);
323 }
324 vertex.position[2] =
325 centerZ + (vertex.position[2] - centerZ) * taper * crown * (1. + (scale - 1.) * weight);
326 vertex.position[2] = static_cast<float>(vertex.position[2]);
327 }
328 for (std::size_t j = 1; j + 1 < polygon.size(); ++j) {
329 const HeadVertex tri[]{polygon[0], polygon[j], polygon[j + 1]};
330 const V normalVector =
331 cross(sub(tri[1].position, tri[0].position), sub(tri[2].position, tri[0].position));
332 if (dot(normalVector, normalVector) < 1e-32) continue;
333 const V n = unit(normalVector);
334 const auto first = static_cast<uint32_t>(output.getVertexCount());
335 for (const auto& vertex : tri)
336 output.addVertex(static_cast<float>(vertex.position[0]), static_cast<float>(vertex.position[1]),
337 static_cast<float>(vertex.position[2]), static_cast<float>(n[0]),
338 static_cast<float>(n[1]), static_cast<float>(n[2]), static_cast<float>(vertex.u),
339 static_cast<float>(vertex.v));
340 output.addTriangle(first, first + 1, first + 2);
341 }
342 }
343 }
344 return output;
345}
346// Contract the front nose edge/face into one geometric apex at the target.
347// Thickness and lateral width both taper; merely sharpening the XY silhouette
348// would retain the old vertical edge at the end of an extruded arrow.
349Result<MeshBuild> pointFlatTip(const MeshBuild& source, V base, V axis, V tip, double headLength) {
350 const double start = headLength * 0.55;
351 const double tolerance = headLength * 1e-6;
352 const auto distance = [&](V p) { return dot(sub(p, base), axis); };
353 double front = 0.;
354 for (int i = 0; i < source.getVertexCount(); ++i)
355 front = std::max(front, distance({source.getPositionX(i), source.getPositionY(i), source.getPositionZ(i)}));
356 if (front <= start + tolerance || front > headLength + tolerance)
357 return Result<MeshBuild>::failure(invalid("Flat arrow has no valid nose interval before its target"));
358 std::vector<V> positions;
359 for (int i = 0; i < source.getVertexCount(); ++i) {
360 V p{source.getPositionX(i), source.getPositionY(i), source.getPositionZ(i)};
361 const double d = distance(p);
362 if (d >= front - tolerance)
363 p = tip;
364 else if (d > start) {
365 const double t = std::clamp((d - start) / (front - start), 0., 1.);
366 const double forward = d + (headLength - front) * t * t * (3. - 2. * t);
367 const V lateral = sub(sub(p, base), mul(axis, d));
368 p = add(base, add(mul(axis, forward), mul(V{lateral[0], lateral[1], 0.}, std::sqrt(1. - t))));
369 p[2] = tip[2] + (lateral[2]) * (1. - t * t);
370 }
371 for (auto& value : p) value = static_cast<float>(value);
372 positions.push_back(p);
373 }
374 MeshBuild mesh;
375 int active = -2;
376 for (int i = 0; i < source.getIndexCount(); i += 3) {
377 const int indices[]{source.getIndex(i), source.getIndex(i + 1), source.getIndex(i + 2)};
378 const V a = positions[indices[0]], b = positions[indices[1]], c = positions[indices[2]];
379 // These faces belonged to the contracted nose edge and carry no remaining area.
380 if (a == b || b == c || c == a) continue;
381 const V area = cross(sub(b, a), sub(c, a));
382 if (length(area) < 1e-16)
383 return Result<MeshBuild>::failure(invalid("Pointed arrow tip exceeds float mesh precision"));
384 const V normal = unit(area);
385 const int group = source.getTriangleGroup(i / 3);
386 if (group != active) {
387 mesh.setActiveGroup(source.getGroupName(group));
388 active = group;
389 }
390 const auto first = static_cast<uint32_t>(mesh.getVertexCount());
391 for (int index : indices) {
392 const V p = positions[index];
393 mesh.addVertex(static_cast<float>(p[0]), static_cast<float>(p[1]), static_cast<float>(p[2]),
394 static_cast<float>(normal[0]), static_cast<float>(normal[1]), static_cast<float>(normal[2]),
395 source.getUvU(index), source.getUvV(index));
396 }
397 mesh.addTriangle(first, first + 1, first + 2);
398 }
399 return Result<MeshBuild>::success(std::move(mesh));
400}
401} // namespace
402
403Result<void> ArrowGenerator::setEndpoints(float ax, float ay, float az, float bx, float by, float bz) {
404 const V a{ax, ay, az}, b{bx, by, bz};
405 if (!valid(a) || !valid(b) || length(sub(b, a)) < 1e-5) return Result<void>::failure(invalid());
406 a_ = a;
407 b_ = b;
408 return Result<void>::success();
409}
411 const V value{x, y, z};
412 if (!valid(value)) return Result<void>::failure(invalid());
413 bend_ = value;
414 return Result<void>::success();
415}
416Result<void> ArrowGenerator::setMode(std::string_view mode) {
417 if (mode != "2d" && mode != "3d" && mode != "flat") return Result<void>::failure(invalid());
418 planar_ = mode != "3d";
419 flat_ = mode == "flat";
420 return Result<void>::success();
421}
422Result<void> ArrowGenerator::setSize(float shaftWidth, float headWidth, float headLength) {
423 if (!valid({shaftWidth, headWidth, headLength}) || shaftWidth < 1e-5f || headWidth <= shaftWidth ||
424 headLength < 1e-5f)
426 shaftWidth_ = shaftWidth;
427 headWidth_ = headWidth;
428 headLength_ = headLength;
429 return Result<void>::success();
430}
432 if (profile != "uniform" && profile != "flowing") return Result<void>::failure(invalid());
433 flowing_ = profile == "flowing";
434 return Result<void>::success();
435}
437 if (!std::isfinite(scale) || scale < 1.f || scale > 4.f) return Result<void>::failure(invalid());
438 headThicknessScale_ = scale;
439 return Result<void>::success();
440}
442 if (!valid({thickness, radius, 0.}) || radius < 1e-5f || thickness <= 2. * radius || segments < 2 || segments > 12)
444 thickness_ = thickness;
445 bevelRadius_ = radius;
446 bevelSegments_ = segments;
447 return Result<void>::success();
448}
450 if (segments < 2 || segments > 256 || sides < 3 || sides > 64) return Result<void>::failure(invalid());
451 segments_ = segments;
452 sides_ = sides;
453 return Result<void>::success();
454}
456 const V chord = sub(b_, a_);
457 const double chordLength = length(chord);
458 // A strictly forward control polygon excludes cusps and repeated samples.
459 if (std::abs(dot(bend_, unit(chord))) >= chordLength * 0.499 || (planar_ && (a_[2] != b_[2] || bend_[2] != 0.)))
461 const V control = add(mul(add(a_, b_), 0.5), bend_);
462 const auto sampleCapacity = static_cast<std::size_t>(segments_) + 2;
463 std::vector<V> points;
464 points.reserve(sampleCapacity);
465 points.push_back(a_);
466 std::vector<double> arc;
467 arc.reserve(sampleCapacity);
468 arc.push_back(0.);
469 for (int i = 1; i <= segments_; ++i) {
470 const double t = static_cast<double>(i) / segments_;
471 const V p = i == segments_
472 ? b_
473 : add(add(mul(a_, (1. - t) * (1. - t)), mul(control, 2. * t * (1. - t))), mul(b_, t * t));
474 arc.push_back(arc.back() + length(sub(p, points.back())));
475 points.push_back(p);
476 }
477 const double total = arc.back();
478 if (total <= headLength_ + 1e-5 || headLength_ >= chordLength * 0.9) return Result<MeshBuild>::failure(invalid());
479 // Trim by distance from B: the final cone has the requested axial length.
480 std::size_t cut = points.size() - 2;
481 while (cut > 0 && length(sub(points[cut], b_)) < headLength_) --cut;
482 V lo = points[cut], hi = points[cut + 1];
483 for (int i = 0; i < 48; ++i) {
484 const V mid = mul(add(lo, hi), 0.5);
485 if (length(sub(mid, b_)) > headLength_)
486 lo = mid;
487 else
488 hi = mid;
489 }
490 const V base = mul(add(lo, hi), 0.5);
491 points.resize(cut + 1);
492 arc.resize(cut + 1);
493 const double last = length(sub(base, points.back()));
494 if (last > 1e-8) {
495 points.push_back(base);
496 arc.push_back(arc.back() + last);
497 } else
498 points.back() = base;
499 const V headAxis = unit(sub(b_, base));
500 if (flat_ && flowing_) {
501 // Align the neck with the head while retaining the tail and distant curve.
502 const double neckSpan = std::min(headLength_ * 0.5, length(sub(base, points.front())) * 0.5);
503 for (auto& point : points) {
504 const V offset = sub(point, base);
505 const double t = std::clamp(1. - length(offset) / neckSpan, 0., 1.);
506 const double weight = t * t * (3. - 2. * t);
507 const V aligned = add(base, mul(headAxis, dot(offset, headAxis)));
508 point = add(mul(point, 1. - weight), mul(aligned, weight));
509 }
510 }
511 std::vector<V> tangents, normals;
512 tangents.reserve(points.size());
513 normals.reserve(points.size());
514 for (std::size_t i = 0; i < points.size(); ++i) {
515 V t = i + 1 == points.size() ? headAxis : unit(sub(points[i + 1], points[i]));
516 if (i > 0 && i + 1 < points.size()) t = unit(add(t, unit(sub(points[i], points[i - 1]))));
517 tangents.push_back(t);
518 if (planar_)
519 normals.push_back({-t[1], t[0], 0.});
520 else {
521 const V reference = i == 0 ? (std::abs(t[2]) < 0.9 ? V{0., 0., 1.} : V{0., 1., 0.}) : normals.back();
522 const V projected = sub(reference, mul(t, dot(reference, t)));
523 if (length(projected) < 1e-8) return Result<MeshBuild>::failure(invalid());
524 normals.push_back(unit(projected));
525 }
526 }
528 const int sides = planar_ ? 2 : sides_;
529 const auto ringPoint = [&](std::size_t i, int j, double radius) {
530 if (planar_) return add(points[i], mul(normals[i], j == 0 ? radius : -radius));
531 const double angle = 2. * std::numbers::pi * j / sides;
532 return add(
533 points[i],
534 mul(add(mul(normals[i], std::cos(angle)), mul(cross(tangents[i], normals[i]), std::sin(angle))), radius));
535 };
536 if (flat_) {
537 auto result =
538 flatArrow(points, normals, b_, shaftWidth_, headWidth_, thickness_, bevelRadius_, bevelSegments_, flowing_);
539 if (!result.ok()) return Result<MeshBuild>::failure(result.status());
540 mesh = std::move(result).takeValue();
541 if (headThicknessScale_ != 1. || flowing_)
542 mesh = shapeFlatSurface(mesh, base, headAxis, headLength_, a_[2], headThicknessScale_, points, flowing_,
543 shaftWidth_, headWidth_);
544 } else {
545 mesh.setActiveGroup("shaft");
546 for (std::size_t i = 0; i + 1 < points.size(); ++i)
547 for (int j = 0; j < (planar_ ? 1 : sides); ++j) {
548 const int k = (j + 1) % sides;
549 quad(mesh, ringPoint(i, j, shaftWidth_ / 2.), ringPoint(i, k, shaftWidth_ / 2.),
550 ringPoint(i + 1, k, shaftWidth_ / 2.), ringPoint(i + 1, j, shaftWidth_ / 2.), arc[i] / total,
551 arc[i + 1] / total);
552 }
553 const std::size_t end = points.size() - 1;
554 mesh.setActiveGroup("head");
555 if (planar_)
556 triangle(mesh, ringPoint(end, 1, headWidth_ / 2.), b_, ringPoint(end, 0, headWidth_ / 2.),
557 arc.back() / total, 1., arc.back() / total);
558 else {
559 for (int j = 0; j < sides; ++j) {
560 const int k = (j + 1) % sides;
561 triangle(mesh, ringPoint(end, j, headWidth_ / 2.), ringPoint(end, k, headWidth_ / 2.), b_,
562 arc.back() / total, arc.back() / total, 1.);
563 quad(mesh, ringPoint(end, j, shaftWidth_ / 2.), ringPoint(end, k, shaftWidth_ / 2.),
564 ringPoint(end, k, headWidth_ / 2.), ringPoint(end, j, headWidth_ / 2.), arc.back() / total,
565 arc.back() / total);
566 triangle(mesh, points[0], ringPoint(0, k, shaftWidth_ / 2.), ringPoint(0, j, shaftWidth_ / 2.), 0., 0.,
567 0.);
568 }
569 }
570 }
571 if (flat_) {
572 auto pointed = pointFlatTip(mesh, base, headAxis, b_, headLength_);
573 if (!pointed.ok()) return Result<MeshBuild>::failure(pointed.status());
574 mesh = std::move(pointed).takeValue();
575 }
576 // Float mesh streams must still represent every generated face at the chosen world scale.
577 for (int i = 0; i < mesh.getIndexCount(); i += 3) {
578 V p[3];
579 for (int j = 0; j < 3; ++j) {
580 const int index = mesh.getIndex(i + j);
581 p[j] = {mesh.getPositionX(index), mesh.getPositionY(index), mesh.getPositionZ(index)};
582 }
583 if (length(cross(sub(p[1], p[0]), sub(p[2], p[0]))) < 1e-16)
584 return Result<MeshBuild>::failure(invalid("Mesh contains a degenerate float triangle"));
585 }
586 if (flat_ && flowing_) {
587 // Angle-weighted normals are stable across uneven cap tessellation and preserve face UV seams.
588 std::map<V, V> accumulated;
589 for (int i = 0; i < mesh.getIndexCount(); i += 3) {
590 V p[3];
591 for (int j = 0; j < 3; ++j) {
592 const int k = mesh.getIndex(i + j);
593 p[j] = {mesh.getPositionX(k), mesh.getPositionY(k), mesh.getPositionZ(k)};
594 }
595 const V normal = unit(cross(sub(p[1], p[0]), sub(p[2], p[0])));
596 for (int j = 0; j < 3; ++j) {
597 const V a = unit(sub(p[(j + 1) % 3], p[j])), b = unit(sub(p[(j + 2) % 3], p[j]));
598 const double angle = std::acos(std::clamp(dot(a, b), -1., 1.));
599 accumulated[p[j]] = add(accumulated[p[j]], mul(normal, angle));
600 }
601 }
602 for (int i = 0; i < mesh.getVertexCount(); ++i) {
603 const V point{mesh.getPositionX(i), mesh.getPositionY(i), mesh.getPositionZ(i)};
604 const V sum = accumulated.at(point);
605 if (length(sum) < 1e-16)
606 return Result<MeshBuild>::failure(invalid("Flowing arrow has an undefined normal"));
607 const V average = unit(sum);
608 const V face{mesh.getNormalX(i), mesh.getNormalY(i), mesh.getNormalZ(i)};
609 // Preserve a crease when a shared average exceeds 75 degrees from this face.
610 const V normal = dot(average, face) >= 0.2588190451 ? average : face;
611 for (int j = 0; j < 3; ++j)
612 mesh.normals()[static_cast<std::size_t>(i) * 3 + j] = static_cast<float>(normal[j]);
613 }
614 }
615 return Result<MeshBuild>::success(std::move(mesh));
616}
617} // namespace eve::procgen
double z
double y
double m[16]
double x
Duration start
bool & active
int tip
Definition AnimSmr.cpp:121
int mid
Definition AnimSmr.cpp:120
double lateral
std::string output
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
glm::vec4 p[6]
int triangle
Definition FluidSdf.cpp:554
ScriptForceVector chord
std::string message
float maximum[3]
float minimum[3]
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
std::vector< float > normals
std::vector< float > positions
float v
float halfWidth
std::int32_t c
std::int32_t first
int h
float ratio
float length
JointPoint2D axis
size_t offset
std::array< float, 3 > position
std::array< float, 3 > scale
float thickness
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Texture * normal
OceanMeshSettings mesh
std::string path
Definition PlayHost.cpp:111
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float d
int steps
float t
RoadLaneDirection direction
int cuts
Definition RockMesh.cpp:25
bool found
std::string_view source
size_t end
bool occupied
Definition Shadow.cpp:155
int count
AbilityActivationGroup group
std::map< Cell, int > best
TacticalUnit * unit
TacticalUnit::TurnResources turn
int segments
Definition TreeMesh.cpp:281
float taper
Definition TreeMesh.cpp:271
int sides
Definition TreeMesh.cpp:459
double weight
uint32_t index
float fraction
V forward
std::array< float, 4 > radii
glm::vec3 point
float bottom
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
Result< void > setResolution(int curveSegments, int radialSides)
Set tessellation budgets; failure preserves state.
Result< void > setBevel(float thickness, float radius, int segments)
Configure the flat mode's thin extrusion and rounded rim.
Result< MeshBuild > buildMeshResult() const
Build a new owning mesh without changing this builder or any previously built mesh.
Result< void > setFlatProfile(std::string_view profile)
Select flat geometry's uniform outline or tapered, softly rounded flowing profile.
Result< void > setBend(float x, float y, float z)
Set quadratic Bezier control offset from the A/B midpoint; zero gives a straight line.
Result< void > setEndpoints(float ax, float ay, float az, float bx, float by, float bz)
Set finite world-space endpoints; failure preserves previous endpoints.
Result< void > setSize(float shaftWidth, float headWidth, float headLength)
Set positive full shaft width, full head width and head length, each at most 1e6.
Result< void > setHeadThicknessScale(float scale)
Set the flat arrow head's thickness relative to its shaft, with a short shoulder ramp.
Result< void > setMode(std::string_view mode)
Choose "2d" (XY ribbon), "3d" (closed tube/cone), or "flat" (beveled XY slab).
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
SQInteger top
Definition Snapshot.cpp:115
eve::Diagnostic Diagnostic
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Vec3 sub(Vec3 a, Vec3 b)
Vec3 mul(Vec3 a, float scale)
double sample(const Heightmap &map, double u, double v)
Sample.
Result< int > invalid(std::string message)
Invalid.
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29