载入中...
搜索中...
未找到
SplinePath.cpp
浏览该文件的文档.
2#include "common/Assert.h"
4
5#include <algorithm>
6#include <array>
7#include <cmath>
8#include <limits>
9#include <string>
10
11namespace eve::procgen {
12namespace {
13
14bool finite(const SplinePoint& p) {
15 return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z) && std::isfinite(p.inX) &&
16 std::isfinite(p.inY) && std::isfinite(p.inZ) && std::isfinite(p.outX) && std::isfinite(p.outY) &&
17 std::isfinite(p.outZ) && std::isfinite(p.rollDegrees) && std::isfinite(p.rollPivotSide) &&
18 std::isfinite(p.scaleX) && std::isfinite(p.scaleY) && std::isfinite(p.pitchDegrees) &&
19 std::isfinite(p.yawDegrees) && p.scaleX > 0.f && p.scaleY > 0.f &&
20 p.scaleXInterpolation <= SplineScaleInterpolation::CatmullRom &&
21 p.rollInterpolation <= SplineRollInterpolation::SmoothStep && std::isfinite(p.spanStrength) &&
22 p.spanStrength >= .01f && p.spanStrength <= 1.f && p.spanControl <= SplineSpanControl::Circular;
23}
24
25struct V3 {
26 float x, y, z;
27};
28
29V3 add(V3 a, V3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
30V3 sub(V3 a, V3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
31V3 mul(V3 a, float s) { return {a.x * s, a.y * s, a.z * s}; }
32float dot(V3 a, V3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
33V3 cross(V3 a, V3 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}; }
34float length(V3 value) { return std::sqrt(value.x * value.x + value.y * value.y + value.z * value.z); }
35V3 normalized(V3 value) {
36 const float magnitude = length(value);
37 return magnitude > 1e-7f ? mul(value, 1.f / magnitude) : V3{1.f, 0.f, 0.f};
38}
39V3 rotateAround(V3 value, V3 axis, float angle) {
40 const float c = std::cos(angle), s = std::sin(angle);
41 return add(add(mul(value, c), mul(cross(axis, value), s)), mul(axis, dot(axis, value) * (1.f - c)));
42}
43V3 position(const SplinePoint& p) { return {p.x, p.y, p.z}; }
44
45Result<detail::CircularArcXZ> circleForSpan(const std::vector<SplinePoint>& points, int aIndex, int bIndex,
46 bool closed) {
47 const auto& a = points[static_cast<std::size_t>(aIndex)];
48 const auto& b = points[static_cast<std::size_t>(bIndex)];
49 int previous = aIndex, next = bIndex;
50 if (aIndex > 0 && !a.breakBefore)
51 previous = aIndex - 1;
52 else if (closed && aIndex == 0)
53 previous = static_cast<int>(points.size()) - 1;
54 if (bIndex + 1 < static_cast<int>(points.size()) && !points[static_cast<std::size_t>(bIndex + 1)].breakBefore)
55 next = bIndex + 1;
56 else if (closed && bIndex == static_cast<int>(points.size()) - 1)
57 next = 0;
58 double dx = static_cast<double>(b.x) - a.x, dz = static_cast<double>(b.z) - a.z;
59 if (a.circularFromEnd && next != bIndex) {
60 dx = static_cast<double>(points[static_cast<std::size_t>(next)].x) - b.x;
61 dz = static_cast<double>(points[static_cast<std::size_t>(next)].z) - b.z;
62 }
63 if (!a.circularFromEnd && previous != aIndex) {
64 dx = static_cast<double>(a.x) - points[static_cast<std::size_t>(previous)].x;
65 dz = static_cast<double>(a.z) - points[static_cast<std::size_t>(previous)].z;
66 }
67 if (previous != aIndex && next != bIndex) {
68 const auto& before = points[static_cast<std::size_t>(previous)];
69 const auto& after = points[static_cast<std::size_t>(next)];
70 if (!a.circularFromEnd)
72 a.x, a.z, b.x, b.z, a.x - static_cast<double>(before.x), a.z - static_cast<double>(before.z),
73 static_cast<double>(after.x) - b.x, static_cast<double>(after.z) - b.z);
75 b.x, b.z, a.x, a.z, b.x - static_cast<double>(after.x), b.z - static_cast<double>(after.z),
76 static_cast<double>(before.x) - a.x, static_cast<double>(before.z) - a.z);
77 if (!arc.ok()) return arc;
78 arc.value().reversed = true;
79 return arc;
80 }
82 a.x, a.z, b.x, b.z, dx, dz,
84}
85
86} // namespace
87
89 if (kind != "linear" && kind != "catmullRom" && kind != "quadraticBezier" && kind != "bezier")
91 DiagnosticCode::InvalidArgument, "spline kind must be linear, catmullRom, quadraticBezier, or bezier",
92 "kind", {}, "procgen.splinePath"));
93 kind_ = kind;
94 invalidate();
95 return Result<void>::success();
96}
97
98void SplinePath::setClosed(bool closed) {
99 bool changed = closed_ != closed;
100 if (closed)
101 for (std::size_t i = 1; i < points_.size(); ++i) {
102 changed = changed || points_[i].breakBefore;
103 points_[i].breakBefore = false;
104 }
105 if (!changed) return;
106 closed_ = closed;
107 invalidate();
108}
109
111 if (!finite(point))
112 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "spline point must be finite",
113 "point", {}, "procgen.splinePath"));
114 points_.push_back(point);
115 invalidate();
116 return Result<void>::success();
117}
118
120 if (index < 0 || index >= pointCount())
121 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "spline point index is out of range",
122 "point.index", {}, "procgen.splinePath"));
123 if (!finite(point))
124 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "spline point must be finite",
125 "point", {}, "procgen.splinePath"));
126 points_[static_cast<std::size_t>(index)] = point;
127 invalidate();
128 return Result<void>::success();
129}
130
131Result<void> SplinePath::setPointProfileResult(int index, float rollDegrees, float scaleX, float scaleY) {
132 if (index < 0 || index >= pointCount())
133 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "spline point index is out of range",
134 "point.index", {}, "procgen.splinePath"));
135 if (!std::isfinite(rollDegrees) || !std::isfinite(scaleX) || !std::isfinite(scaleY) || scaleX <= 0.f ||
136 scaleY <= 0.f)
138 "spline point profile requires finite roll and positive scales",
139 "point.profile", {}, "procgen.splinePath"));
140 auto candidate = points_[static_cast<std::size_t>(index)];
141 candidate.rollDegrees = rollDegrees;
142 candidate.scaleX = scaleX;
143 candidate.scaleY = scaleY;
144 points_[static_cast<std::size_t>(index)] = candidate;
145 invalidate();
146 return Result<void>::success();
147}
148
149Result<void> SplinePath::setPointRotationResult(int index, float pitchDegrees, float yawDegrees, float rollDegrees) {
150 if (index < 0 || index >= pointCount())
151 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "spline point index is out of range",
152 "point.index", {}, "procgen.splinePath"));
153 if (!std::isfinite(pitchDegrees) || !std::isfinite(yawDegrees) || !std::isfinite(rollDegrees))
155 "spline point rotation must be finite", "point.rotation", {},
156 "procgen.splinePath"));
157 auto candidate = points_[static_cast<std::size_t>(index)];
158 candidate.pitchDegrees = pitchDegrees;
159 candidate.yawDegrees = yawDegrees;
160 candidate.rollDegrees = rollDegrees;
161 points_[static_cast<std::size_t>(index)] = candidate;
162 invalidate();
163 return Result<void>::success();
164}
165
167 if (index <= 0 || index >= pointCount())
169 "chunk breaks require a non-first existing spline point",
170 "point.index", {}, "procgen.splinePath"));
171 if (closed_ && disconnected)
173 "closed splines cannot contain disconnected chunks", "closed",
174 {}, "procgen.splinePath"));
175 if (points_[static_cast<std::size_t>(index)].breakBefore == disconnected) return Result<void>::success();
176 points_[static_cast<std::size_t>(index)].breakBefore = disconnected;
177 invalidate();
178 return Result<void>::success();
179}
180
182 if (index < 0 || index >= pointCount())
183 return Result<void>::failure(Diagnostic::error(DiagnosticCode::NotFound, "spline point index is out of range",
184 "point.index", {}, "procgen.splinePath"));
185 points_.erase(points_.begin() + index);
186 invalidate();
187 return Result<void>::success();
188}
189
191 if (points_.empty()) return;
192 points_.clear();
193 invalidate();
194}
195
196int SplinePath::segmentCount() const noexcept {
197 if (points_.size() < 2u) return 0;
198 int result = closed_ ? 1 : 0;
199 for (std::size_t i = 1; i < points_.size(); ++i)
200 if (!points_[i].breakBefore) ++result;
201 return result;
202}
203
204int SplinePath::chunkCount() const noexcept {
205 if (points_.empty()) return 0;
206 int result = 1;
207 for (std::size_t i = 1; i < points_.size(); ++i)
208 if (points_[i].breakBefore) ++result;
209 return result;
210}
211
213 if (chunk < 0 || chunk >= chunkCount())
215 DiagnosticCode::NotFound, "spline chunk index is out of range", "chunk.index", {}, "procgen.splinePath"));
217 result.kind_ = kind_;
218 int current = 0;
219 for (std::size_t i = 0; i < points_.size(); ++i) {
220 if (i > 0u && points_[i].breakBefore) ++current;
221 if (current != chunk) continue;
222 auto point = points_[i];
223 point.breakBefore = false;
224 result.points_.push_back(point);
225 }
226 result.closed_ = closed_ && chunkCount() == 1;
227 result.revision_ = revision_;
228 if (result.segmentCount() == 0)
230 "each spline chunk requires at least two points",
231 "chunk.points", {}, "procgen.splinePath"));
232 return Result<SplinePath>::success(std::move(result));
233}
234
235std::vector<std::pair<int, int>> SplinePath::segmentEndpoints() const {
236 std::vector<std::pair<int, int>> result;
237 for (int i = 0; i + 1 < pointCount(); ++i)
238 if (!points_[static_cast<std::size_t>(i + 1)].breakBefore) result.emplace_back(i, i + 1);
239 if (closed_ && pointCount() > 1) result.emplace_back(pointCount() - 1, 0);
240 return result;
241}
242
243Result<void> SplinePath::validateReady() const {
244 if (segmentCount() == 0)
246 "spline requires at least two points", "points", {},
247 "procgen.splinePath"));
248 if (std::any_of(points_.begin(), points_.end(),
249 [](const auto& point) { return point.spanControl == SplineSpanControl::Circular; }))
250 for (const auto& [a, b] : segmentEndpoints())
251 if (points_[static_cast<std::size_t>(a)].spanControl == SplineSpanControl::Circular) {
252 auto arc = circleForSpan(points_, a, b, closed_);
253 if (!arc.ok()) return Result<void>::failure(arc.status());
254 const auto& start = points_[static_cast<std::size_t>(a)];
255 const auto& end = points_[static_cast<std::size_t>(b)];
257 detail::sampleCircularArcXZ(arc.value(), 0.), 0.,
258 {static_cast<double>(end.x) - start.x, static_cast<double>(end.y) - start.y,
259 static_cast<double>(end.z) - start.z});
260 if (!ghost.ok()) return Result<void>::failure(ghost.status());
261 }
262 return Result<void>::success();
263}
264
265SplineSample SplinePath::evaluateUnchecked(float t) const {
266 t = std::clamp(t, 0.f, 1.f);
267 const int segments = segmentCount();
268 const float scaled = t * static_cast<float>(segments);
269 const int segment = std::min(static_cast<int>(scaled), segments - 1);
270 const float u = segment == segments - 1 && t == 1.f ? 1.f : scaled - static_cast<float>(segment);
271 return evaluateSegmentUnchecked(segment, u, t);
272}
273
274SplineSample SplinePath::evaluateSegmentUnchecked(int segment, float u, float normalizedDistance) const {
275 const auto endpoints = segmentEndpoints();
276 const int aIndex = endpoints[static_cast<std::size_t>(segment)].first;
277 const int bIndex = endpoints[static_cast<std::size_t>(segment)].second;
278 const auto& a = points_[static_cast<std::size_t>(aIndex)];
279 const auto& b = points_[static_cast<std::size_t>(bIndex)];
280 int chunkIndex = 0;
281 for (int i = 1; i <= aIndex; ++i)
282 if (points_[static_cast<std::size_t>(i)].breakBefore) ++chunkIndex;
283 V3 value{}, tangent{};
284 float scaleX = std::lerp(a.scaleX, b.scaleX, u);
285 if (kind_ == "linear") {
287 tangent = sub(position(b), position(a));
288 } else if (kind_ == "quadraticBezier") {
289 const V3 p0 = position(a), p2 = position(b);
290 const V3 outgoing = add(p0, {a.outX, a.outY, a.outZ});
291 const V3 incoming = add(p2, {b.inX, b.inY, b.inZ});
292 const V3 p1 = mul(add(outgoing, incoming), 0.5f);
293 const float v = 1.f - u;
294 value = add(add(mul(p0, v * v), mul(p1, 2.f * v * u)), mul(p2, u * u));
295 tangent = add(mul(sub(p1, p0), 2.f * v), mul(sub(p2, p1), 2.f * u));
296 } else if (kind_ == "bezier") {
297 const V3 p0 = position(a), p1 = add(p0, {a.outX, a.outY, a.outZ});
298 const V3 p3 = position(b), p2 = add(p3, {b.inX, b.inY, b.inZ});
299 const float v = 1.f - u;
300 value =
301 add(add(mul(p0, v * v * v), mul(p1, 3.f * v * v * u)), add(mul(p2, 3.f * v * u * u), mul(p3, u * u * u)));
302 tangent = add(add(mul(sub(p1, p0), 3.f * v * v), mul(sub(p2, p1), 6.f * v * u)), mul(sub(p3, p2), 3.f * u * u));
303 } else {
304 int previous = aIndex;
305 if (aIndex > 0 && !points_[static_cast<std::size_t>(aIndex)].breakBefore)
306 previous = aIndex - 1;
307 else if (closed_ && aIndex == 0)
308 previous = pointCount() - 1;
309 int next = bIndex;
310 if (bIndex + 1 < pointCount() && !points_[static_cast<std::size_t>(bIndex + 1)].breakBefore)
311 next = bIndex + 1;
312 else if (closed_ && bIndex == pointCount() - 1)
313 next = 0;
314 const V3 p0 = position(points_[static_cast<std::size_t>(previous)]);
315 const V3 p1 = position(a), p2 = position(b);
316 const V3 p3 = position(points_[static_cast<std::size_t>(next)]);
317 const float u2 = u * u, u3 = u2 * u;
318 if (a.scaleXInterpolation == SplineScaleInterpolation::CatmullRom) {
319 const double p0s = points_[static_cast<std::size_t>(previous)].scaleX, p1s = a.scaleX, p2s = b.scaleX,
320 p3s = points_[static_cast<std::size_t>(next)].scaleX;
321 const double cubic = .5 * (2.0 * p1s + (-p0s + p2s) * u + (2.0 * p0s - 5.0 * p1s + 4.0 * p2s - p3s) * u2 +
322 (-p0s + 3.0 * p1s - 3.0 * p2s + p3s) * u3);
323 scaleX =
324 static_cast<float>(std::clamp(cubic, 1e-4, static_cast<double>(std::numeric_limits<float>::max())));
325 }
326 value = mul(add(add(mul(p1, 2.f), mul(sub(p2, p0), u)),
327 add(mul(add(add(mul(p0, 2.f), mul(p1, -5.f)), add(mul(p2, 4.f), mul(p3, -1.f))), u2),
328 mul(add(add(mul(p0, -1.f), mul(p1, 3.f)), add(mul(p2, -3.f), p3)), u3))),
329 0.5f);
330 tangent = mul(
331 add(sub(p2, p0), add(mul(add(add(mul(p0, 2.f), mul(p1, -5.f)), add(mul(p2, 4.f), mul(p3, -1.f))), 2.f * u),
332 mul(add(add(mul(p0, -1.f), mul(p1, 3.f)), add(mul(p2, -3.f), p3)), 3.f * u2))),
333 0.5f);
334 const bool circularStart = previous != aIndex && points_[static_cast<std::size_t>(previous)].spanControl ==
336 const bool circularEnd = next != bIndex && b.spanControl == SplineSpanControl::Circular;
337 const bool alignStart = a.spanControl == SplineSpanControl::Inherit &&
338 (a.alignStraightStart || circularStart) && previous != aIndex &&
339 points_[static_cast<std::size_t>(previous)].spanControl != SplineSpanControl::Inherit;
340 const bool alignEnd = a.spanControl == SplineSpanControl::Inherit && (a.alignStraightEnd || circularEnd) &&
341 next != bIndex && b.spanControl != SplineSpanControl::Inherit;
342 const float strength = a.spanControl == SplineSpanControl::Inherit ? a.spanStrength : .5f;
343 if (strength != .5f || alignStart || alignEnd) {
344 V3 d1 = mul(sub(p2, p0), strength), d2 = mul(sub(p3, p1), strength);
345 auto align = [&](V3& derivative, V3 axis) {
346 const double square = static_cast<double>(axis.x) * axis.x + static_cast<double>(axis.z) * axis.z;
347 if (square > 1e-12) {
348 const double coefficient =
349 2.0 * strength *
350 ((static_cast<double>(p2.x) - p1.x) * axis.x + (static_cast<double>(p2.z) - p1.z) * axis.z) /
351 square;
352 derivative.x = static_cast<float>(coefficient * axis.x);
353 derivative.z = static_cast<float>(coefficient * axis.z);
354 }
355 };
356 if (alignStart) {
357 V3 axis = sub(p1, p0);
358 if (points_[static_cast<std::size_t>(previous)].spanControl == SplineSpanControl::Circular) {
359 auto arc = circleForSpan(points_, previous, aIndex, closed_);
360 EV_ASSERT(arc.ok(), "validated circular neighbor must remain valid");
361 auto end = detail::sampleCircularArcXZ(arc.value(), 1.);
362 if (arc.value().line && points_[static_cast<std::size_t>(previous)].circularFromEnd) {
363 end.dx = static_cast<double>(p2.x) - p1.x;
364 end.dz = static_cast<double>(p2.z) - p1.z;
365 }
367 end, .5 * (static_cast<double>(p2.y) - p0.y),
368 {static_cast<double>(p1.x) - p0.x, static_cast<double>(p1.y) - p0.y,
369 static_cast<double>(p1.z) - p0.z});
370 EV_ASSERT(ghost.ok(), "validated circular neighbor must retain a representable chord");
371 axis = {ghost.value()[0], ghost.value()[1], ghost.value()[2]};
372 d1 = mul(add(sub(p2, p1), axis), strength);
373 }
374 if (!circularStart) align(d1, axis);
375 if (!circularStart) d1.y = 0.f;
376 }
377 if (alignEnd) {
378 V3 axis = sub(p3, p2);
379 if (b.spanControl == SplineSpanControl::Circular) {
380 auto arc = circleForSpan(points_, bIndex, next, closed_);
381 EV_ASSERT(arc.ok(), "validated circular neighbor must remain valid");
382 auto start = detail::sampleCircularArcXZ(arc.value(), 0.);
383 if (arc.value().line && !b.circularFromEnd) {
384 start.dx = static_cast<double>(p2.x) - p1.x;
385 start.dz = static_cast<double>(p2.z) - p1.z;
386 }
388 start, .5 * (static_cast<double>(p3.y) - p1.y),
389 {static_cast<double>(p3.x) - p2.x, static_cast<double>(p3.y) - p2.y,
390 static_cast<double>(p3.z) - p2.z});
391 EV_ASSERT(ghost.ok(), "validated circular neighbor must retain a representable chord");
392 axis = {ghost.value()[0], ghost.value()[1], ghost.value()[2]};
393 d2 = mul(add(sub(p2, p1), axis), strength);
394 }
395 if (!circularEnd) align(d2, axis);
396 if (!circularEnd) d2.y = 0.f;
397 }
398 value = add(add(mul(p1, 2.f * u3 - 3.f * u2 + 1.f), mul(d1, u3 - 2.f * u2 + u)),
399 add(mul(p2, -2.f * u3 + 3.f * u2), mul(d2, u3 - u2)));
400 tangent = add(add(mul(p1, 6.f * u2 - 6.f * u), mul(d1, 3.f * u2 - 4.f * u + 1.f)),
401 add(mul(p2, -6.f * u2 + 6.f * u), mul(d2, 3.f * u2 - 2.f * u)));
402 }
403 }
404 if (a.spanControl == SplineSpanControl::StraightXZ || a.spanControl == SplineSpanControl::StraightXYZ) {
405 value.x = std::lerp(a.x, b.x, u);
406 value.z = std::lerp(a.z, b.z, u);
407 tangent.x = b.x - a.x;
408 tangent.z = b.z - a.z;
409 if (a.spanControl == SplineSpanControl::StraightXYZ) {
410 value.y = std::lerp(a.y, b.y, u);
411 tangent.y = b.y - a.y;
412 }
413 }
414 if (a.spanControl == SplineSpanControl::Circular) {
415 auto arc = circleForSpan(points_, aIndex, bIndex, closed_);
416 EV_ASSERT(arc.ok(), "validated circular span must remain valid");
417 const auto evaluated = detail::sampleCircularArcXZ(arc.value(), u);
418 value.x = static_cast<float>(evaluated.x);
419 value.z = static_cast<float>(evaluated.z);
420 tangent.x = static_cast<float>(evaluated.dx);
421 tangent.z = static_cast<float>(evaluated.dz);
422 const double magnitude = std::hypot(evaluated.dx, static_cast<double>(tangent.y), evaluated.dz);
423 if (std::isfinite(magnitude) && magnitude > 1e-7)
424 tangent = {static_cast<float>(evaluated.dx / magnitude), static_cast<float>(tangent.y / magnitude),
425 static_cast<float>(evaluated.dz / magnitude)};
426 }
427 const float tangentLength = length(tangent);
428 if (tangentLength > 1e-7f)
429 tangent = mul(tangent, 1.f / tangentLength);
430 else
431 tangent = {1.f, 0.f, 0.f};
432 return {value.x,
433 value.y,
434 value.z,
435 tangent.x,
436 tangent.y,
437 tangent.z,
438 normalizedDistance,
439 std::lerp(a.rollDegrees, b.rollDegrees,
440 a.rollInterpolation == SplineRollInterpolation::SmoothStep ? u * u * (3.f - 2.f * u) : u),
441 scaleX,
442 std::lerp(a.scaleY, b.scaleY, u),
443 chunkIndex,
444 std::lerp(a.pitchDegrees, b.pitchDegrees, u),
445 std::lerp(a.yawDegrees, b.yawDegrees, u),
446 a.worldUpFrame,
447 std::lerp(a.rollPivotSide, b.rollPivotSide,
448 a.rollInterpolation == SplineRollInterpolation::SmoothStep ? u * u * (3.f - 2.f * u) : u)};
449}
450
452 auto valid = validateReady();
453 if (!valid.ok()) return Result<SplineSample>::failure(valid.status());
454 if (!std::isfinite(t))
456 DiagnosticCode::InvalidArgument, "spline parameter must be finite", "t", {}, "procgen.splinePath"));
457 return Result<SplineSample>::success(evaluateUnchecked(t));
458}
459
460Result<void> SplinePath::ensureArcTable(int samplesPerSegment) const {
461 auto valid = validateReady();
462 if (!valid.ok()) return valid;
463 if (samplesPerSegment < 2 || samplesPerSegment > 1024)
465 "arc samples per segment must be in [2, 1024]",
466 "samplesPerSegment", {}, "procgen.splinePath"));
467 if (arcSamplesPerSegment_ == samplesPerSegment && !arcTable_.empty()) return Result<void>::success();
468 arcTable_.clear();
469 arcTable_.reserve(static_cast<std::size_t>(segmentCount() * (samplesPerSegment + 1)));
470 float distance = 0.f;
471 const auto endpoints = segmentEndpoints();
472 for (int segment = 0; segment < segmentCount(); ++segment) {
473 auto previous =
474 evaluateSegmentUnchecked(segment, 0.f, static_cast<float>(segment) / static_cast<float>(segmentCount()));
475 // Retain both endpoint parameterizations at a connected boundary so the first
476 // interval of the next span interpolates from its own u=0 instead of jumping.
477 arcTable_.push_back({segment, 0.f, distance});
478 for (int sample = 1; sample <= samplesPerSegment; ++sample) {
479 const float u = static_cast<float>(sample) / static_cast<float>(samplesPerSegment);
480 const auto current = evaluateSegmentUnchecked(
481 segment, u, (static_cast<float>(segment) + u) / static_cast<float>(segmentCount()));
483 arcTable_.push_back({segment, u, distance});
485 }
486 }
487 arcSamplesPerSegment_ = samplesPerSegment;
488 return Result<void>::success();
489}
490
491Result<float> SplinePath::lengthResult(int samplesPerSegment) const {
492 auto ready = ensureArcTable(samplesPerSegment);
493 if (!ready.ok()) return Result<float>::failure(ready.status());
494 return Result<float>::success(arcTable_.back().distance);
495}
496
498 if (!std::isfinite(distance))
500 DiagnosticCode::InvalidArgument, "spline distance must be finite", "distance", {}, "procgen.splinePath"));
501 auto ready = ensureArcTable(samplesPerSegment);
502 if (!ready.ok()) return Result<SplineSample>::failure(ready.status());
503 const float total = arcTable_.back().distance;
504 distance = std::clamp(distance, 0.f, total);
505 const auto upper = std::lower_bound(arcTable_.begin(), arcTable_.end(), distance,
506 [](const ArcEntry& entry, float value) { return entry.distance < value; });
507 int segment = 0;
508 float u = 0.f;
509 if (upper == arcTable_.begin()) {
510 segment = upper->segment;
511 u = upper->u;
512 } else if (upper == arcTable_.end()) {
513 segment = arcTable_.back().segment;
514 u = arcTable_.back().u;
515 } else {
516 const auto& before = *(upper - 1);
517 const float span = upper->distance - before.distance;
518 if (before.segment != upper->segment || span <= 1e-7f) {
519 segment = upper->segment;
520 u = upper->u;
521 } else {
522 segment = upper->segment;
523 u = std::lerp(before.u, upper->u, (distance - before.distance) / span);
524 }
525 }
526 auto sample =
527 evaluateSegmentUnchecked(segment, u, (static_cast<float>(segment) + u) / static_cast<float>(segmentCount()));
528 sample.normalizedDistance = total > 1e-7f ? distance / total : 0.f;
530}
531
532Result<SplineSample> SplinePath::closestPointResult(float x, float y, float z, int samplesPerSegment) const {
533 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
535 DiagnosticCode::InvalidArgument, "closest point query must be finite", "point", {}, "procgen.splinePath"));
536 auto ready = ensureArcTable(samplesPerSegment);
537 if (!ready.ok()) return Result<SplineSample>::failure(ready.status());
538 float bestSquared = 0.f;
540 bool assigned = false;
541 for (const auto& entry : arcTable_) {
542 auto sample = evaluateSegmentUnchecked(
543 entry.segment, entry.u, (static_cast<float>(entry.segment) + entry.u) / static_cast<float>(segmentCount()));
544 const float dx = sample.x - x, dy = sample.y - y, dz = sample.z - z;
545 const float squared = dx * dx + dy * dy + dz * dz;
546 if (!assigned || squared < bestSquared) {
547 assigned = true;
548 bestSquared = squared;
549 best = sample;
550 best.normalizedDistance =
551 arcTable_.back().distance > 1e-7f ? entry.distance / arcTable_.back().distance : 0.f;
552 }
553 }
555}
556
558 float rollDegrees, int samplesPerSegment,
559 bool preserveMarkers) const {
560 if (sampleCount < 1 || sampleCount > 4096)
562 Diagnostic::error(DiagnosticCode::InvalidArgument, "frame sampleCount must be in [1, 4096]", "sampleCount",
563 {}, "procgen.splinePath"));
564 if (!std::isfinite(rollDegrees))
566 DiagnosticCode::InvalidArgument, "frame roll must be finite", "rollDegrees", {}, "procgen.splinePath"));
567 float totalLength = 0.f;
568 if (uniformByDistance) {
569 auto measured = lengthResult(samplesPerSegment);
570 if (!measured.ok()) return Result<std::vector<SplineFrameSample>>::failure(measured.status());
571 totalLength = measured.value();
572 } else {
573 auto ready = validateReady();
574 if (!ready.ok()) return Result<std::vector<SplineFrameSample>>::failure(ready.status());
575 }
576
577 std::vector<std::pair<float, int>> locations;
578 for (int index = 0; index <= sampleCount; ++index)
579 locations.emplace_back(static_cast<float>(index) / static_cast<float>(sampleCount), -1);
580 if (preserveMarkers) {
581 if (chunkCount() != 1 || (uniformByDistance && totalLength <= 1e-7f))
584 "marker-preserving sampling requires a continuous positive-length path", "preserveMarkers"));
585 if (uniformByDistance) {
586 float previousAnchor = -1.f;
587 for (const auto& entry : arcTable_)
588 if (entry.u == 0.f) {
589 if (entry.distance <= previousAnchor)
592 "marker-preserving distance sampling requires positive-length spans", "preserveMarkers"));
593 locations.emplace_back(entry.distance / totalLength, entry.segment);
594 previousAnchor = entry.distance;
595 }
596 } else {
597 for (int segment = 0; segment < segmentCount(); ++segment)
598 locations.emplace_back(static_cast<float>(segment) / static_cast<float>(segmentCount()), segment);
599 }
600 locations.emplace_back(1.f, segmentCount() - 1);
601 std::sort(locations.begin(), locations.end(), [](const auto& a, const auto& b) {
602 return a.first < b.first || (a.first == b.first && a.second > b.second);
603 });
604 locations.erase(std::unique(locations.begin(), locations.end(),
605 [](const auto& a, const auto& b) { return a.first == b.first; }),
606 locations.end());
607 if (locations.size() > 4097u)
610 "marker-preserving sampling exceeds the frame budget", "preserveMarkers"));
611 }
612 std::vector<SplineFrameSample> frames;
613 frames.reserve(locations.size());
614 std::vector<float> ratios;
615 ratios.reserve(locations.size());
616 for (std::size_t index = 0; index < locations.size(); ++index) {
617 const auto [ratio, marker] = locations[index];
618 auto sampled =
619 uniformByDistance ? evaluateDistanceResult(totalLength * ratio, samplesPerSegment) : evaluateResult(ratio);
620 if (!sampled.ok()) return Result<std::vector<SplineFrameSample>>::failure(sampled.status());
621 if (marker >= 0)
622 sampled = Result<SplineSample>::success(evaluateSegmentUnchecked(marker, ratio == 1.f ? 1.f : 0.f, ratio));
624 frame.sample = sampled.value();
625 frame.authoredMarker = marker >= 0;
626 frames.push_back(frame);
627 ratios.push_back(ratio);
628 }
629 return orientFrameSamplesResult(std::move(frames), ratios, rollDegrees);
630}
631
633 int samplesPerSegment) const {
634 if (parameters.empty() || parameters.size() > 4097u)
636 DiagnosticCode::InvalidArgument, "explicit frame parameters require 1..4097 samples", "parameters"));
637 float previous = -1.f;
638 for (float parameter : parameters) {
639 if (!std::isfinite(parameter) || parameter < 0.f || parameter > 1.f || parameter <= previous)
640 return Result<std::vector<SplineFrameSample>>::failure(
642 "explicit frame parameters must increase strictly within [0,1]", "parameters"));
644 }
645 auto ready = ensureArcTable(samplesPerSegment);
646 if (!ready.ok()) return Result<std::vector<SplineFrameSample>>::failure(ready.status());
647 const float total = arcTable_.back().distance;
648 if (!std::isfinite(total) || total <= 1e-7f)
651 "explicit frame arc distance requires a positive finite path length", "path"));
652 std::vector<SplineFrameSample> frames;
653 frames.reserve(parameters.size());
654 for (float parameter : parameters) {
655 const float scaled = parameter * static_cast<float>(segmentCount());
656 const int segment = std::min(static_cast<int>(scaled), segmentCount() - 1);
657 const float u = parameter == 1.f ? 1.f : scaled - static_cast<float>(segment);
658 const auto upper = std::lower_bound(
659 arcTable_.begin(), arcTable_.end(), std::pair{segment, u}, [](const ArcEntry& entry, const auto& target) {
660 return entry.segment < target.first || (entry.segment == target.first && entry.u < target.second);
661 });
662 float distance = total;
663 if (upper != arcTable_.end()) {
664 distance = upper->distance;
665 if (upper != arcTable_.begin()) {
666 const auto& before = *(upper - 1);
667 if (before.segment == segment && upper->u > before.u)
668 distance = std::lerp(before.distance, upper->distance, (u - before.u) / (upper->u - before.u));
669 }
670 }
672 frame.sample = evaluateSegmentUnchecked(segment, u, distance / total);
673 frame.authoredMarker = u == 0.f || u == 1.f;
674 frames.push_back(frame);
675 }
676 return orientFrameSamplesResult(std::move(frames), parameters, 0.f);
677}
678
679Result<std::vector<SplineFrameSample>> SplinePath::orientFrameSamplesResult(std::vector<SplineFrameSample> frames,
680 std::span<const float> ratios,
681 float rollDegrees) const {
682 EV_ASSERT(frames.size() == ratios.size(), "frame transport ratios must match samples");
683 EV_ASSERT(!frames.empty(), "frame transport requires a sample");
684 V3 previousTangent{}, previousSide{};
685 for (std::size_t index = 0; index < frames.size(); ++index) {
686 const auto sample = frames[index].sample;
687 const V3 tangent = normalized({sample.tangentX, sample.tangentY, sample.tangentZ});
688 V3 side;
689 if (sample.worldUpFrame || index == 0 || sample.chunkIndex != frames[index - 1].sample.chunkIndex) {
690 const float verticalLimit = sample.worldUpFrame ? .999999f : .9f;
691 const V3 reference = std::abs(tangent.y) < verticalLimit ? V3{0.f, 1.f, 0.f} : V3{1.f, 0.f, 0.f};
692 side = normalized(cross(reference, tangent));
693 } else {
694 const V3 axis = cross(previousTangent, tangent);
695 const float axisSize = length(axis);
696 if (axisSize > 1e-7f) {
697 const float angle = std::atan2(axisSize, std::clamp(dot(previousTangent, tangent), -1.f, 1.f));
698 side = rotateAround(previousSide, mul(axis, 1.f / axisSize), angle);
699 } else if (dot(previousTangent, tangent) < 0.f) {
700 side = mul(previousSide, -1.f);
701 } else {
702 side = previousSide;
703 }
704 side = normalized(sub(side, mul(tangent, dot(side, tangent))));
705 }
706 V3 up = normalized(cross(tangent, side));
707 side = normalized(cross(up, tangent));
708 auto& frame = frames[index];
709 frame.sideX = side.x;
710 frame.sideY = side.y;
711 frame.sideZ = side.z;
712 frame.upX = up.x;
713 frame.upY = up.y;
714 frame.upZ = up.z;
715 frame.forwardX = tangent.x;
716 frame.forwardY = tangent.y;
717 frame.forwardZ = tangent.z;
718 previousTangent = tangent;
719 previousSide = side;
720 }
721
722 if (closed_ && ratios.front() == 0.f && ratios.back() == 1.f && frames.size() > 1u &&
723 !frames.front().sample.worldUpFrame) {
724 const V3 firstSide{frames.front().sideX, frames.front().sideY, frames.front().sideZ};
725 const V3 lastSide{frames.back().sideX, frames.back().sideY, frames.back().sideZ};
726 const V3 tangent{frames.front().sample.tangentX, frames.front().sample.tangentY,
727 frames.front().sample.tangentZ};
728 const float correction =
729 std::atan2(dot(tangent, cross(lastSide, firstSide)), std::clamp(dot(lastSide, firstSide), -1.f, 1.f));
730 for (std::size_t index = 1; index < frames.size(); ++index) {
731 auto& frame = frames[static_cast<std::size_t>(index)];
732 const float ratio = ratios[index];
733 const V3 currentTangent{frame.sample.tangentX, frame.sample.tangentY, frame.sample.tangentZ};
734 V3 side = rotateAround({frame.sideX, frame.sideY, frame.sideZ}, currentTangent, correction * ratio);
735 V3 up = normalized(cross(currentTangent, side));
736 side = normalized(cross(up, currentTangent));
737 frame.sideX = side.x;
738 frame.sideY = side.y;
739 frame.sideZ = side.z;
740 frame.upX = up.x;
741 frame.upY = up.y;
742 frame.upZ = up.z;
743 }
744 frames.back() = frames.front();
745 frames.back().sample.normalizedDistance = 1.f;
746 }
747
748 for (auto& frame : frames) {
749 V3 side{frame.sideX, frame.sideY, frame.sideZ};
750 V3 up{frame.upX, frame.upY, frame.upZ};
751 V3 forward{frame.sample.tangentX, frame.sample.tangentY, frame.sample.tangentZ};
752 const float yaw = frame.sample.yawDegrees * 0.01745329251994329577f;
753 if (std::abs(yaw) > 1e-7f) {
754 forward = rotateAround(forward, up, yaw);
755 side = rotateAround(side, up, yaw);
756 }
757 const float pitch = frame.sample.pitchDegrees * 0.01745329251994329577f;
758 if (std::abs(pitch) > 1e-7f) {
759 forward = rotateAround(forward, side, pitch);
760 up = rotateAround(up, side, pitch);
761 }
762 const float roll = (rollDegrees + frame.sample.rollDegrees) * 0.01745329251994329577f;
763 if (std::abs(roll) > 1e-7f) {
764 const float c = std::cos(roll), s = std::sin(roll);
765 const V3 rolledSide = add(mul(side, c), mul(up, s));
766 const V3 shift = mul(sub(side, rolledSide), frame.sample.rollPivotSide * frame.sample.scaleX);
767 frame.sample.x += shift.x;
768 frame.sample.y += shift.y;
769 frame.sample.z += shift.z;
770 if (!std::isfinite(frame.sample.x) || !std::isfinite(frame.sample.y) || !std::isfinite(frame.sample.z))
771 return Result<std::vector<SplineFrameSample>>::failure(
773 "roll-pivot displacement exceeds finite frame coordinates", "rollPivotSide"));
774 up = add(mul(up, c), mul(side, -s));
775 side = rolledSide;
776 }
777 frame.sideX = side.x;
778 frame.sideY = side.y;
779 frame.sideZ = side.z;
780 frame.upX = up.x;
781 frame.upY = up.y;
782 frame.upZ = up.z;
783 frame.forwardX = forward.x;
784 frame.forwardY = forward.y;
785 frame.forwardZ = forward.z;
786 }
787 return Result<std::vector<SplineFrameSample>>::success(std::move(frames));
788}
789
791 if (index < 0 || index >= count())
793 "spline distribution index is out of range",
794 "distribution.index", {}, "procgen.splinePath"));
795 return Result<SplineSample>::success(frames_[static_cast<std::size_t>(index)].sample);
796}
797
799 if (index < 0 || index >= count())
801 "spline distribution index is out of range",
802 "distribution.index", {}, "procgen.splinePath"));
803 return Result<SplineFrameSample>::success(frames_[static_cast<std::size_t>(index)]);
804}
805
806int SplinePolyline::count() const noexcept {
807 int result = 0;
808 for (const auto& chunk : chunks_) result += static_cast<int>(chunk.size());
809 return result;
810}
811
812int SplinePolyline::chunkPointCount(int chunk) const noexcept {
813 return chunk < 0 || chunk >= chunkCount() ? 0 : static_cast<int>(chunks_[static_cast<std::size_t>(chunk)].size());
814}
815
817 if (chunk < 0 || chunk >= chunkCount() || index < 0 || index >= chunkPointCount(chunk))
819 "spline polyline index is out of range",
820 "polyline.index", {}, "procgen.splinePath"));
821 return Result<SplineSample>::success(chunks_[static_cast<std::size_t>(chunk)][static_cast<std::size_t>(index)]);
822}
823
825 if (index >= 0)
826 for (const auto& chunk : chunks_) {
827 if (index < static_cast<int>(chunk.size()))
828 return Result<SplineSample>::success(chunk[static_cast<std::size_t>(index)]);
829 index -= static_cast<int>(chunk.size());
830 }
832 DiagnosticCode::NotFound, "spline polyline index is out of range", "polyline.index", {}, "procgen.splinePath"));
833}
834
835Result<SplineSample> SplinePath::travelResult(float distance, std::string_view wrapMode, int samplesPerSegment) const {
836 if (!std::isfinite(distance))
838 "spline travel distance must be finite", "distance", {},
839 "procgen.splinePath"));
840 if (wrapMode != "clamp" && wrapMode != "loop" && wrapMode != "pingPong")
842 DiagnosticCode::InvalidArgument, "spline travel wrap mode must be clamp, loop, or pingPong", "wrapMode", {},
843 "procgen.splinePath"));
844 auto measured = lengthResult(samplesPerSegment);
845 if (!measured.ok()) return Result<SplineSample>::failure(measured.status());
846 const float total = measured.value();
847 float resolved = distance;
848 if (wrapMode == "loop" && total > 1e-7f) {
849 resolved = std::fmod(distance, total);
850 if (resolved < 0.f) resolved += total;
851 } else if (wrapMode == "pingPong" && total > 1e-7f) {
852 const float period = total * 2.f;
853 resolved = std::fmod(distance, period);
854 if (resolved < 0.f) resolved += period;
855 if (resolved > total) resolved = period - resolved;
856 }
857 return evaluateDistanceResult(resolved, samplesPerSegment);
858}
859
861 int samplesPerSegment) const {
862 auto sample = travelResult(distance, wrapMode, samplesPerSegment);
863 if (!sample.ok()) return Result<SplineFrameSample>::failure(sample.status());
864 const int frameIntervals = std::clamp(segmentCount() * samplesPerSegment, 1, 4096);
865 auto frames = sampleFramesResult(frameIntervals, true, 0.f, samplesPerSegment);
866 if (!frames.ok()) return Result<SplineFrameSample>::failure(frames.status());
867 const float location = sample.value().normalizedDistance * static_cast<float>(frameIntervals);
868 const int lowerIndex = std::clamp(static_cast<int>(std::floor(location)), 0, frameIntervals);
869 const int upperIndex = std::min(lowerIndex + 1, frameIntervals);
870 const float blend = location - static_cast<float>(lowerIndex);
871 const auto& lower = frames.value()[static_cast<std::size_t>(lowerIndex)];
872 const auto& upper = frames.value()[static_cast<std::size_t>(upperIndex)];
873 V3 forward =
874 normalized({std::lerp(lower.forwardX, upper.forwardX, blend), std::lerp(lower.forwardY, upper.forwardY, blend),
875 std::lerp(lower.forwardZ, upper.forwardZ, blend)});
876 V3 side = normalized({std::lerp(lower.sideX, upper.sideX, blend), std::lerp(lower.sideY, upper.sideY, blend),
877 std::lerp(lower.sideZ, upper.sideZ, blend)});
878 side = normalized(sub(side, mul(forward, dot(side, forward))));
879 const V3 up = normalized(cross(forward, side));
880 side = normalized(cross(up, forward));
881 auto projected = sample.value();
882 if (projected.rollPivotSide != 0.f) {
883 const float angle = projected.rollDegrees * .01745329251994329577f;
884 const V3 unrolledSide = sub(mul(side, std::cos(angle)), mul(up, std::sin(angle)));
885 const V3 shift = mul(sub(unrolledSide, side), projected.rollPivotSide * projected.scaleX);
886 projected.x += shift.x;
887 projected.y += shift.y;
888 projected.z += shift.z;
889 if (!std::isfinite(projected.x) || !std::isfinite(projected.y) || !std::isfinite(projected.z))
892 "roll-pivot displacement exceeds finite frame coordinates", "rollPivotSide"));
893 }
895 {projected, side.x, side.y, side.z, up.x, up.y, up.z, forward.x, forward.y, forward.z});
896}
897
899 int samplesPerSegment) const {
900 if (instanceCount < 1 || instanceCount > 100000)
902 "spline instanceCount must be in [1, 100000]",
903 "instanceCount", {}, "procgen.splinePath"));
904 const bool duplicateEnd = includeEnd && !closed_ && instanceCount > 1;
905 const int intervals = duplicateEnd ? instanceCount - 1 : instanceCount;
906 auto frames = sampleFramesResult(std::max(1, intervals), true, 0.f, samplesPerSegment);
907 if (!frames.ok()) return Result<SplineDistribution>::failure(frames.status());
908 frames.value().resize(static_cast<std::size_t>(instanceCount));
909 return Result<SplineDistribution>::success(SplineDistribution(std::move(frames).takeValue()));
910}
911
912Result<SplinePolyline> SplinePath::polylineResult(int sampleCount, bool uniformByDistance,
913 int samplesPerSegment) const {
914 if (sampleCount < 2 || sampleCount > 65536)
916 "spline polyline sampleCount must be in [2, 65536]",
917 "sampleCount", {}, "procgen.splinePath"));
918 if (sampleCount < chunkCount() * 2)
920 DiagnosticCode::InvalidArgument, "spline polyline requires at least two samples per chunk", "sampleCount",
921 {}, "procgen.splinePath"));
922 std::vector<std::vector<SplineSample>> chunks;
923 chunks.reserve(static_cast<std::size_t>(chunkCount()));
924 int remaining = sampleCount;
925 for (int chunk = 0; chunk < chunkCount(); ++chunk) {
926 auto path = chunkPathResult(chunk);
927 if (!path.ok()) return Result<SplinePolyline>::failure(path.status());
928 const int chunksLeft = chunkCount() - chunk;
929 const int maximum = remaining - (chunksLeft - 1) * 2;
930 const int proposed = sampleCount * path.value().segmentCount() / segmentCount();
931 const int chunkSamples = chunksLeft == 1 ? remaining : std::clamp(proposed, 2, maximum);
932 remaining -= chunkSamples;
933 auto measured = uniformByDistance ? path.value().lengthResult(samplesPerSegment) : Result<float>::success(0.f);
934 if (!measured.ok()) return Result<SplinePolyline>::failure(measured.status());
935 std::vector<SplineSample> points;
936 points.reserve(static_cast<std::size_t>(chunkSamples));
937 const int denominator = path.value().isClosed() ? chunkSamples : chunkSamples - 1;
938 for (int index = 0; index < chunkSamples; ++index) {
939 const float ratio = static_cast<float>(index) / static_cast<float>(denominator);
940 auto sample = uniformByDistance
941 ? path.value().evaluateDistanceResult(measured.value() * ratio, samplesPerSegment)
942 : path.value().evaluateResult(ratio);
943 if (!sample.ok()) return Result<SplinePolyline>::failure(sample.status());
944 points.push_back(sample.value());
945 }
946 chunks.push_back(std::move(points));
947 }
948 return Result<SplinePolyline>::success(SplinePolyline(std::move(chunks), closed_));
949}
950
951Result<void> SplinePath::applyShapePresetResult(std::string_view preset, int pointCount, float radius, float height,
952 float turns) {
953 if (preset != "line" && preset != "circle" && preset != "arc" && preset != "spiral" && preset != "wave")
955 "spline preset must be line, circle, arc, spiral, or wave",
956 "preset", {}, "procgen.splinePath"));
957 if (pointCount < 2 || pointCount > 4096 || (preset == "circle" && pointCount < 3))
959 "spline preset pointCount is invalid", "pointCount", {},
960 "procgen.splinePath"));
961 if (!std::isfinite(radius) || !std::isfinite(height) || !std::isfinite(turns) || radius <= 0.f || turns <= 0.f)
963 "spline preset requires finite positive radius and turns",
964 "preset.parameters", {}, "procgen.splinePath"));
965 constexpr float tau = 6.28318530717958647692f;
966 std::vector<SplinePoint> candidate;
967 candidate.reserve(static_cast<std::size_t>(pointCount));
968 for (int index = 0; index < pointCount; ++index) {
969 const float t = pointCount > 1 ? static_cast<float>(index) / static_cast<float>(pointCount - 1) : 0.f;
971 if (preset == "line") {
972 point = {-radius + 2.f * radius * t, height * t, 0.f};
973 } else if (preset == "circle") {
974 const float angle = tau * static_cast<float>(index) / static_cast<float>(pointCount);
975 point = {std::cos(angle) * radius, 0.f, std::sin(angle) * radius};
976 } else if (preset == "arc") {
977 const float angle = (-0.25f + 0.5f * t) * tau * turns;
978 point = {std::cos(angle) * radius, height * t, std::sin(angle) * radius};
979 } else if (preset == "spiral") {
980 const float angle = tau * turns * t;
981 const float ring = radius * t;
982 point = {std::cos(angle) * ring, height * t, std::sin(angle) * ring};
983 } else {
984 point = {-radius + 2.f * radius * t, std::sin(tau * turns * t) * height, 0.f};
985 }
986 candidate.push_back(point);
987 }
988 points_ = std::move(candidate);
989 kind_ = preset == "line" ? "linear" : "catmullRom";
990 closed_ = preset == "circle";
991 invalidate();
992 return Result<void>::success();
993}
994
995void SplinePath::invalidate() {
996 ++revision_;
997 arcTable_.clear();
998 arcSamplesPerSegment_ = 0;
999}
1000
1001} // namespace eve::procgen
double z
double y
double x
LogicalId target
Duration start
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
float yaw
Definition BushMesh.cpp:37
bool changed
glm::vec4 p[6]
float strength
float maximum[3]
std::uint32_t instanceCount
float u
Definition Grass.cpp:233
float v
HexVec3 up
std::int32_t second
std::int32_t c
std::int32_t first
float blend
std::uint32_t height
float ratio
float length
JointPoint2D axis
std::array< float, 3 > position
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
ssq::Object frame
glm::dvec3 dx
glm::dvec3 dz
std::shared_ptr< const OceanSprayFrame > previous
bool finite
std::array< uint32_t, 9 > parameters
std::string path
Definition PlayHost.cpp:111
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
int detail
float t
std::string parameter
RoadNetwork resolved
size_t end
std::string kind
double current
float dy
Definition Shadow.cpp:151
int count
std::map< Cell, int > best
int segments
Definition TreeMesh.cpp:281
float size
Definition TreeMesh.cpp:158
uint32_t index
int turns
V forward
glm::vec3 point
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
Owning uniformly distributed spline samples for instancing.
Definition SplinePath.h:72
Result< SplineSample > sampleResult(int index) const
Return one sample value, or a structured out-of-range diagnostic.
Result< SplineFrameSample > frameResult(int index) const
Return one sample with its transported orientation frame.
Owning multi-segment 3D spline with deterministic bounded sampling.
Definition SplinePath.h:118
Result< void > setPointRotationResult(int index, float pitchDegrees, float yawDegrees, float rollDegrees)
Atomically replace point-local pitch, yaw, and roll orientation.
Result< void > setPointResult(int index, const SplinePoint &point)
Replace a control point atomically.
Result< void > applyShapePresetResult(std::string_view preset, int pointCount, float radius, float height, float turns=1.f)
Atomically replace this path with line, circle, arc, spiral, or wave preset points.
Result< std::vector< SplineFrameSample > > sampleFramesAtParametersResult(std::span< const float > parameters, int samplesPerSegment=24) const
Build frames at explicitly ordered curve parameters using the canonical transport and roll pipeline.
Result< void > removePointResult(int index)
Remove a control point by stable current index.
Result< SplineSample > evaluateResult(float t) const
Evaluate by normalized segment parameter, not arc length.
void clear()
Remove every point.
void setClosed(bool closed)
Configure whether the final point connects back to the first.
int chunkCount() const noexcept
Return the number of independently connected chunks.
Result< std::vector< SplineFrameSample > > sampleFramesResult(int sampleCount, bool uniformByDistance, float rollDegrees=0.f, int samplesPerSegment=24, bool preserveMarkers=false) const
Sample stable parallel-transport frames for extrusion and placement.
Result< void > setKindResult(std::string_view kind)
Select linear, catmullRom, quadraticBezier, or cubic bezier interpolation.
std::string_view kind() const noexcept
Return interpolation kind.
Definition SplinePath.h:207
int pointCount() const noexcept
Return point count.
Definition SplinePath.h:199
Result< SplinePolyline > polylineResult(int sampleCount=64, bool uniformByDistance=true, int samplesPerSegment=24) const
Build an owning sampled polyline without depending on a graphics module.
Result< void > setPointChunkBreakResult(int index, bool disconnected)
Start or reconnect an open-path chunk before one non-first point.
Result< SplinePath > chunkPathResult(int chunk) const
Copy one independently connected chunk as an owning path.
Result< SplineSample > evaluateDistanceResult(float distance, int samplesPerSegment=24) const
Evaluate by world-space distance using a bounded arc-length table.
Result< void > addPointResult(const SplinePoint &point)
Append an owning control point after validating finite coordinates.
Result< void > setPointProfileResult(int index, float rollDegrees, float scaleX, float scaleY)
Atomically replace per-point roll and cross-section scale after finite positive validation.
Result< SplineSample > travelResult(float distance, std::string_view wrapMode="clamp", int samplesPerSegment=24) const
Evaluate distance-driven travel using clamp, loop, or pingPong wrapping without reading wall time.
Result< SplineDistribution > distributeResult(int instanceCount, bool includeEnd=true, int samplesPerSegment=24) const
Produce owning arc-length-uniform samples for instance distribution.
Result< SplineSample > closestPointResult(float x, float y, float z, int samplesPerSegment=32) const
Return the sampled closest path location to a point.
Result< float > lengthResult(int samplesPerSegment=24) const
Return approximate total world-space length.
int segmentCount() const noexcept
Return segment count.
Result< SplineFrameSample > travelFrameResult(float distance, std::string_view wrapMode="clamp", int samplesPerSegment=24) const
Evaluate distance-driven travel with a transported orientation frame.
Owning sampled polyline for renderer-neutral runtime visualization adapters.
Definition SplinePath.h:88
Result< SplineSample > chunkPointResult(int chunk, int index) const
Return one point inside one disconnected chunk.
int count() const noexcept
Return sampled point count.
Result< SplineSample > pointResult(int index) const
Return one point sample or a structured range error.
int chunkPointCount(int chunk) const noexcept
Return point count for one chunk, or zero for an invalid index.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
constexpr HexVec3 lerp(HexVec3 a, HexVec3 b, float t) noexcept
Linear interpolation between two positions.
Definition HexMetrics.h:51
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)
CircularArcSampleXZ sampleCircularArcXZ(const CircularArcXZ &arc, double u)
Sample validated coefficients with u in [0,1]; endpoints remain exact. @ownership Returns a copied sa...
CircularArcReference
Which endpoint tangent determines a circular span's orientation.
Result< CircularArcXZ > makeCircularArcXZ(double ax, double az, double bx, double bz, double dx, double dz, CircularArcReference reference)
Construct a finite circle from two endpoints and one endpoint direction. @ownership Returns owning co...
Result< std::array< float, 3 > > scaleCircularTangentToChord(const CircularArcSampleXZ &tangent, double heightDerivative, const std::array< double, 3 > &chord)
Scale a circular neighbor tangent to its owning 3D marker chord.
Result< CircularArcXZ > makeCircularLeadArcXZ(double ax, double az, double bx, double bz, double dx, double dz, double endDx, double endDz)
Fit a forward straight lead followed by a circle tangent to both neighboring directions....
double sample(const Heightmap &map, double u, double v)
Sample.
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
SplineSpanControl
Native outgoing overrides; Inherit uses the path kind.
Definition SplinePath.h:22
SplineRollInterpolation
Roll interpolation on one outgoing span; generic splines retain Linear.
Definition SplinePath.h:19
Owning section frame; sample position includes roll-pivot displacement, unlike the author centerline ...
Definition SplinePath.h:63
One spline anchor with incoming and outgoing handle offsets.
Definition SplinePath.h:25
Evaluated spline position and normalized tangent.
Definition SplinePath.h:49