载入中...
搜索中...
未找到
UrbanCrossField.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstdint>
5#include <limits>
6#include <numeric>
7#include <utility>
8#include <vector>
10
11// UrbanCrossField.cpp
13namespace {
14
15constexpr double kPi = 3.14159265358979323846;
16
18struct CrossField {
19 int nx = 0;
20 int ny = 0;
21 double ox = 0.0; // origin
22 double oy = 0.0;
23 double spacing = 1.0;
24 std::vector<double> phi; // 2θ in radians, wrapped to [-π, π)
25 std::vector<char> inside;
26
27 bool cellInside(int x, int y) const {
28 if (x < 0 || y < 0 || x >= nx || y >= ny) return false;
29 return inside[size_t(y) * size_t(nx) + size_t(x)] != 0;
30 }
31
32 bool cellInsideClamped(int x, int y, int* cx, int* cy) const {
33 const int xx = std::clamp(x, 0, nx - 1);
34 const int yy = std::clamp(y, 0, ny - 1);
35 if (cx) *cx = xx;
36 if (cy) *cy = yy;
37 return inside[size_t(yy) * size_t(nx) + size_t(xx)] != 0;
38 }
39
41 double thetaAt(const Vec2& p) const {
42 const double fx = (p.x - ox) / spacing;
43 const double fy = (p.y - oy) / spacing;
44 const int x0 = std::clamp(int(std::floor(fx)), 0, nx - 1);
45 const int y0 = std::clamp(int(std::floor(fy)), 0, ny - 1);
46 const int x1 = std::min(x0 + 1, nx - 1);
47 const int y1 = std::min(y0 + 1, ny - 1);
48 const double tx = std::clamp(fx - double(x0), 0.0, 1.0);
49 const double ty = std::clamp(fy - double(y0), 0.0, 1.0);
50 // Wrapped bilinear interpolation via unit vectors.
51 const int ix[2] = {x0, x1};
52 const int iy[2] = {y0, y1};
53 Vec2 avg{0, 0};
54 for (int j = 0; j < 2; ++j) {
55 for (int i = 0; i < 2; ++i) {
56 const int cx = ix[i];
57 const int cy = iy[j];
58 double a = 0.0;
59 if (cellInside(cx, cy)) {
60 a = phi[size_t(cy) * size_t(nx) + size_t(cx)];
61 } else {
62 int ccx = cx, ccy = cy;
63 int guard = 0;
64 while (!cellInside(ccx, ccy) && guard++ < 64) {
65 // Cheap fallback: search a small spiral for the nearest inside cell.
66 bool found = false;
67 for (int r = 1; r <= 4; ++r) {
68 for (int dy = -r; dy <= r && !found; ++dy) {
69 for (int dx = -r; dx <= r && !found; ++dx) {
70 if (cellInside(cx + dx, cy + dy)) {
71 ccx = cx + dx;
72 ccy = cy + dy;
73 found = true;
74 }
75 }
76 }
77 if (found) break;
78 }
79 if (!found) {
80 ccx = cx;
81 ccy = cy;
82 break;
83 }
84 }
85 a = phi[size_t(ccy) * size_t(nx) + size_t(ccx)];
86 }
87 const double w = (i == 0 ? 1.0 - tx : tx) * (j == 0 ? 1.0 - ty : ty);
88 avg = avg + Vec2{std::cos(a), std::sin(a)} * w;
89 }
90 }
91 double a = std::atan2(avg.y, avg.x);
92 if (a < 0) a += 2.0 * kPi;
93 return a * 0.5; // θ = φ/2
94 }
95};
96
98CrossField buildCrossField(const Polygon& poly, double spacing) {
99 double minX = poly[0].x, minY = poly[0].y, maxX = poly[0].x, maxY = poly[0].y;
100 for (const Vec2& p : poly) {
101 minX = std::min(minX, p.x);
102 minY = std::min(minY, p.y);
103 maxX = std::max(maxX, p.x);
104 maxY = std::max(maxY, p.y);
105 }
106 const double margin = spacing * 0.5;
107 minX -= margin;
108 minY -= margin;
109 maxX += margin;
110 maxY += margin;
111 CrossField f;
112 f.spacing = spacing;
113 f.ox = minX;
114 f.oy = minY;
115 f.nx = std::max(2, int(std::ceil((maxX - minX) / spacing)));
116 f.ny = std::max(2, int(std::ceil((maxY - minY) / spacing)));
117 f.phi.assign(size_t(f.nx) * size_t(f.ny), 0.0);
118 f.inside.assign(size_t(f.nx) * size_t(f.ny), 0);
119
120 // Initialize: nearest-boundary tangent angle (θ mod π → φ = 2θ).
121 for (int y = 0; y < f.ny; ++y) {
122 for (int x = 0; x < f.nx; ++x) {
123 const Vec2 c{f.ox + (double(x) + 0.5) * spacing, f.oy + (double(y) + 0.5) * spacing};
124 if (!pointInPolygon(c, poly)) continue;
125 f.inside[size_t(y) * size_t(f.nx) + size_t(x)] = 1;
126 BoundaryPosition pos;
128 // Tangent of the closest boundary edge.
129 const size_t n = poly.size();
130 const Vec2& a = poly[size_t(pos.edgeIndex)];
131 const Vec2& b = poly[size_t((pos.edgeIndex + 1) % int(n))];
132 const double tangent = std::atan2(b.y - a.y, b.x - a.x);
133 double phi = std::fmod(2.0 * tangent, 2.0 * kPi);
134 if (phi < 0) phi += 2.0 * kPi;
135 f.phi[size_t(y) * size_t(f.nx) + size_t(x)] = phi;
136 }
137 }
138
139 // Smooth the wrapped angle field with Jacobi iterations.
140 const int iterations = 240;
141 std::vector<double> next(f.phi.size(), 0.0);
142 for (int it = 0; it < iterations; ++it) {
143 for (int y = 0; y < f.ny; ++y) {
144 for (int x = 0; x < f.nx; ++x) {
145 const size_t idx = size_t(y) * size_t(f.nx) + size_t(x);
146 if (!f.inside[idx]) continue;
147 Vec2 sum{0, 0};
148 int count = 0;
149 const int dx[4] = {1, -1, 0, 0};
150 const int dy[4] = {0, 0, 1, -1};
151 for (int d = 0; d < 4; ++d) {
152 const int nx = x + dx[d];
153 const int ny = y + dy[d];
154 if (!f.cellInside(nx, ny)) continue;
155 const double a = f.phi[size_t(ny) * size_t(f.nx) + size_t(nx)];
156 sum = sum + Vec2{std::cos(a), std::sin(a)};
157 ++count;
158 }
159 if (count > 0) {
160 double a = std::atan2(sum.y, sum.x);
161 if (a < 0) a += 2.0 * kPi;
162 next[idx] = a;
163 } else {
164 next[idx] = f.phi[idx];
165 }
166 }
167 }
168 f.phi.swap(next);
169 }
170 return f;
171}
172
177Polyline traceStreamline(const CrossField& field, const Polygon& poly, const Vec2& seed, const Vec2& initialDir,
178 double spacing, int maxSteps) {
180 out.push_back(seed);
181 Vec2 p = seed;
182 Vec2 d = normalize(initialDir);
183 const double step = spacing * 0.5;
184 const double boundaryTol = spacing * 0.75;
185 for (int s = 0; s < maxSteps; ++s) {
186 const double theta = field.thetaAt(p);
187 const double c = std::cos(theta);
188 const double sn = std::sin(theta);
189 const Vec2 axes[2] = {{c, sn}, {-sn, c}};
190 // Choose the axis (and sign) best aligned with the current direction.
191 double bestScore = -1.0;
192 Vec2 bestDir = d;
193 for (int i = 0; i < 2; ++i) {
194 for (int sgn = -1; sgn <= 1; sgn += 2) {
195 const Vec2 cand = axes[i] * double(sgn);
196 const double sc = std::fabs(dot(cand, d));
197 if (sc > bestScore) {
198 bestScore = sc;
199 bestDir = cand;
200 }
201 }
202 }
203 d = bestDir;
204 Vec2 np = p + d * step;
205 if (!pointInPolygon(np, poly)) {
206 // Hit the boundary: project back onto it and finish.
207 BoundaryPosition pos;
208 const Vec2 hit = closestPointOnBoundary(poly, np, &pos);
209 if (distance(hit, out.back()) > 1e-9) out.push_back(hit);
210 break;
211 }
212 // Stop when close to the boundary.
213 BoundaryPosition pos;
214 const Vec2 bpt = closestPointOnBoundary(poly, np, &pos);
215 if (distance(np, bpt) < boundaryTol) {
216 if (distance(bpt, out.back()) > 1e-9) out.push_back(bpt);
217 break;
218 }
219 out.push_back(np);
220 p = np;
221 }
222 return out;
223}
224
225double polylineChord(const Polyline& pl) {
226 if (pl.size() < 2) return 0.0;
227 return distance(pl.front(), pl.back());
228}
229
230} // namespace
231
232std::vector<SplitCandidate> generateSplitCandidates(const Polygon& poly, int maxCandidates, double minHalfArea) {
233 std::vector<SplitCandidate> out;
234 if (poly.size() < 3) return out;
235 const double polyArea = area(poly);
236 if (polyArea <= 1e-9) return out;
237
238 const double spacing =
239 std::clamp(std::sqrt(polyArea) / 20.0, std::sqrt(polyArea) * 0.01, std::sqrt(polyArea) * 0.2);
240 const int seedCount = std::clamp(int(perimeter(poly) / std::max(1e-6, spacing)), 24, 96);
241 const std::vector<BoundarySample> samples = sampleBoundary(poly, seedCount);
242 const CrossField field = buildCrossField(poly, spacing);
243 const int maxSteps = std::max(64, int(std::ceil(perimeter(poly) / spacing)));
244
245 // Trace from every boundary sample along each field axis that points into the parcel.
246 const Vec2 c = centroid(poly);
247 std::vector<Polyline> traces;
248 for (const BoundarySample& s : samples) {
249 const Vec2 inward = normalize(c - s.p);
250 const double theta = s.tangentAngle;
251 const Vec2 axes[2] = {{std::cos(theta), std::sin(theta)}, {-std::sin(theta), std::cos(theta)}};
252 for (const Vec2& axis : axes) {
253 if (dot(axis, inward) <= 0.05) continue; // axis must point into the parcel
254 Polyline tr = traceStreamline(field, poly, s.p, axis, spacing, maxSteps);
255 if (tr.size() < 4) continue;
256 if (polylineChord(tr) < spacing * 2.0) continue;
257 traces.push_back(std::move(tr));
258 }
259 }
260
261 // Validate + dedupe traces, keep the geometrically best ones.
262 std::vector<SplitCandidate> valid;
263 for (const Polyline& tr : traces) {
264 Polygon a, b;
265 double frac = 0.0;
266 if (!validSplit(poly, tr, minHalfArea, &a, &b, &frac)) continue;
267 SplitCandidate cand;
268 cand.line = tr;
269 cand.areaFrac = frac;
270 valid.push_back(std::move(cand));
271 if (valid.size() >= size_t(maxCandidates) * 3) break;
272 }
273
274 // Straight-chord fallback when tracing gives too few usable splits. Sample a
275 // spread of boundary-separation distances so the generator's metric can choose
276 // among axis-aligned and diagonal candidates.
277 if (valid.size() < size_t(maxCandidates)) {
278 const int k = std::max(32, seedCount);
279 const std::vector<BoundarySample> dense = sampleBoundary(poly, k);
280 std::vector<SplitCandidate> chords;
281 // Arc-separation steps, largest first: near-balanced chords (e.g. top-bottom
282 // connections of a rectangle) are generated before small corner cuts.
283 const int half = k / 2;
284 std::vector<int> steps;
285 for (int s = half; s >= 3; --s) steps.push_back(s);
286 for (const int step : steps) {
287 for (size_t i = 0; i < dense.size(); i += 2) {
288 const size_t j = (i + size_t(step)) % dense.size();
289 if (j == i) continue;
290 Polyline chord{dense[i].p, dense[j].p};
291 Polygon a, b;
292 double frac = 0.0;
293 if (!validSplit(poly, chord, minHalfArea, &a, &b, &frac)) continue;
294 SplitCandidate cand;
295 cand.line = std::move(chord);
296 cand.areaFrac = frac;
297 chords.push_back(std::move(cand));
298 if (chords.size() >= size_t(maxCandidates) * 3) break;
299 }
300 if (chords.size() >= size_t(maxCandidates) * 3) break;
301 }
302 // Append fallbacks (streamlines remain preferred).
303 valid.insert(valid.end(), chords.begin(), chords.end());
304 }
305
306 // Candidate *selection* is left to the quality metric (paper Eq. 2); here we just
307 // keep a diverse set: streamlines first (cross-field), then straight chords, with
308 // near-duplicate lines removed. No geometry-based ranking — that would bias the
309 // metric (e.g. a rectangle's diagonal is perfectly balanced but should lose to a
310 // regular axis-aligned split once regularity is scored).
311 const double eps = std::sqrt(area(poly)) * 1e-3;
312 for (const SplitCandidate& cand : valid) {
313 bool dup = false;
314 for (const SplitCandidate& keep : out) {
315 const double d1 = distance(cand.line.front(), keep.line.front());
316 const double d2 = distance(cand.line.back(), keep.line.back());
317 const double d3 = distance(cand.line.front(), keep.line.back());
318 const double d4 = distance(cand.line.back(), keep.line.front());
319 if ((d1 < eps && d2 < eps) || (d3 < eps && d4 < eps)) {
320 dup = true;
321 break;
322 }
323 }
324 if (dup) continue;
325 out.push_back(cand);
326 if (int(out.size()) >= maxCandidates) break;
327 }
328 return out;
329}
330
331} // namespace eve::procgen::urban
332
333// UrbanGeometry.cpp
334namespace eve::procgen::urban {
335namespace {
336
337constexpr double kEps = 1e-9;
338
339int wrapIndex(int i, int n) {
340 if (n <= 0) return 0;
341 return ((i % n) + n) % n;
342}
343
344bool samePoint(const Vec2& a, const Vec2& b, double eps) {
345 return std::fabs(a.x - b.x) <= eps && std::fabs(a.y - b.y) <= eps;
346}
347
348bool onSegmentTol(const Vec2& p, const Vec2& a, const Vec2& b, double eps) {
349 const Vec2 ab = b - a;
350 const double l2 = lengthSq(ab);
351 if (l2 <= eps * eps) return samePoint(p, a, eps);
352 const double t = dot(p - a, ab) / l2;
353 if (t < -eps || t > 1.0 + eps) return false;
354 const Vec2 proj = a + ab * t;
355 return distance(p, proj) <= eps;
356}
357
358} // namespace
359
360double signedArea(const Polygon& poly) {
361 const size_t n = poly.size();
362 if (n < 3) return 0.0;
363 double s = 0.0;
364 for (size_t i = 0; i < n; ++i) {
365 const Vec2& a = poly[i];
366 const Vec2& b = poly[wrapIndex(int(i) + 1, int(n))];
367 s += cross(a, b);
368 }
369 return s * 0.5;
370}
371
372double area(const Polygon& poly) { return std::fabs(signedArea(poly)); }
373
374double polylineLength(const Polyline& pl) {
375 double l = 0.0;
376 for (size_t i = 1; i < pl.size(); ++i) l += distance(pl[i - 1], pl[i]);
377 return l;
378}
379
380Vec2 centroid(const Polygon& poly) {
381 const size_t n = poly.size();
382 if (n == 0) return {0, 0};
383 if (n == 1) return poly[0];
384 if (n == 2) return (poly[0] + poly[1]) * 0.5;
385 double a = 0.0;
386 Vec2 c{0, 0};
387 for (size_t i = 0; i < n; ++i) {
388 const Vec2& p = poly[i];
389 const Vec2& q = poly[wrapIndex(int(i) + 1, int(n))];
390 const double cr = cross(p, q);
391 a += cr;
392 c = c + (p + q) * cr;
393 }
394 if (std::fabs(a) < 1e-12) return poly[0];
395 return c / (3.0 * a);
396}
397
398double perimeter(const Polygon& poly) {
399 double p = 0.0;
400 for (size_t i = 0; i < poly.size(); ++i) p += distance(poly[i], poly[wrapIndex(int(i) + 1, int(poly.size()))]);
401 return p;
402}
403
404bool ensureCCW(Polygon& poly) {
405 if (signedArea(poly) < 0.0) {
406 std::reverse(poly.begin(), poly.end());
407 return true;
408 }
409 return false;
410}
411
412void cleanupRing(Polygon& poly, double eps) {
413 Polygon out;
414 out.reserve(poly.size());
415 for (const Vec2& p : poly) {
416 if (!out.empty() && samePoint(out.back(), p, eps)) continue;
417 // Drop points that lie (almost) on the segment between their neighbours.
418 if (out.size() >= 2) {
419 const Vec2& a = out[out.size() - 2];
420 const Vec2& b = out.back();
421 if (distanceToSegment(p, a, b) <= eps) {
422 out.back() = p;
423 continue;
424 }
425 }
426 out.push_back(p);
427 }
428 // Wrap-around cleanup: first vs last.
429 while (out.size() > 3 && samePoint(out.front(), out.back(), eps)) out.pop_back();
430 if (out.size() >= 3) {
431 const Vec2& a = out[out.size() - 1];
432 const Vec2& b = out[0];
433 if (distanceToSegment(out[1], a, b) <= eps) out[1] = b;
434 }
435 poly = std::move(out);
436}
437
438bool pointInPolygon(const Vec2& p, const Polygon& poly) {
439 if (poly.size() < 3) return false;
440 bool inside = false;
441 for (size_t i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
442 const Vec2& a = poly[i];
443 const Vec2& b = poly[j];
444 if (pointOnSegment(p, a, b)) return true;
445 const bool crosses = ((a.y > p.y) != (b.y > p.y)) && (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x);
446 if (crosses) inside = !inside;
447 }
448 return inside;
449}
450
451bool pointOnSegment(const Vec2& p, const Vec2& a, const Vec2& b, double eps) { return onSegmentTol(p, a, b, eps); }
452
453bool segmentsIntersect(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, Vec2* out) {
454 const Vec2 ab = b - a;
455 const Vec2 cd = d - c;
456 const Vec2 ac = c - a;
457 const double denom = cross(ab, cd);
458 const double eps = 1e-12;
459 if (std::fabs(denom) <= eps) return false; // parallel (collinear handled by point tests)
460 const double t = cross(ac, cd) / denom;
461 const double u = cross(ac, ab) / denom;
462 if (t < -eps || t > 1.0 + eps || u < -eps || u > 1.0 + eps) return false;
463 if (out) *out = a + ab * t;
464 return true;
465}
466
467bool segmentIntersectsPolyline(const Vec2& a, const Vec2& b, const Polyline& pl) {
468 for (size_t i = 1; i < pl.size(); ++i) {
469 Vec2 hit;
470 if (segmentsIntersect(a, b, pl[i - 1], pl[i], &hit)) return true;
471 }
472 return false;
473}
474
476 for (size_t i = 1; i < pl.size(); ++i) {
477 for (size_t j = i + 2; j < pl.size(); ++j) {
478 Vec2 hit;
479 if (segmentsIntersect(pl[i - 1], pl[i], pl[j - 1], pl[j], &hit)) return true;
480 }
481 }
482 return false;
483}
484
485bool polygonIsSimple(const Polygon& poly) {
486 const size_t n = poly.size();
487 if (n < 3) return false;
488 for (size_t i = 0; i < n; ++i) {
489 const Vec2& a = poly[i];
490 const Vec2& b = poly[wrapIndex(int(i) + 1, int(n))];
491 for (size_t j = i + 1; j < n; ++j) {
492 const size_t jn = wrapIndex(int(j) + 1, int(n));
493 // Adjacent segments share an endpoint and are allowed to touch.
494 if (j == i + 1) continue; // share poly[j]
495 if (i == 0 && j == n - 1) continue; // wrap-around pair shares poly[0]
496 Vec2 hit;
497 if (segmentsIntersect(a, b, poly[j], poly[jn], &hit)) return false;
498 }
499 }
500 return area(poly) > 1e-12;
501}
502
503double closestPointOnSegment(const Vec2& p, const Vec2& a, const Vec2& b, Vec2* out) {
504 const Vec2 ab = b - a;
505 const double l2 = lengthSq(ab);
506 if (l2 <= 1e-18) {
507 if (out) *out = a;
508 return distance(p, a);
509 }
510 const double t = std::clamp(dot(p - a, ab) / l2, 0.0, 1.0);
511 if (out) *out = a + ab * t;
512 return distance(p, a + ab * t);
513}
514
516 const size_t n = poly.size();
517 if (n == 0) return p;
518 double best = std::numeric_limits<double>::infinity();
519 Vec2 bestP = poly[0];
520 int bestEdge = 0;
521 double bestT = 0.0;
522 for (size_t i = 0; i < n; ++i) {
523 const Vec2& a = poly[i];
524 const Vec2& b = poly[wrapIndex(int(i) + 1, int(n))];
525 const Vec2 ab = b - a;
526 const double l2 = lengthSq(ab);
527 double t = 0.0;
528 if (l2 > 1e-18) t = std::clamp(dot(p - a, ab) / l2, 0.0, 1.0);
529 const Vec2 q = a + ab * t;
530 const double d = distance(p, q);
531 if (d < best) {
532 best = d;
533 bestP = q;
534 bestEdge = int(i);
535 bestT = t;
536 }
537 }
538 if (pos) {
539 pos->edgeIndex = bestEdge;
540 pos->t = bestT;
541 }
542 return bestP;
543}
544
546 const size_t n = poly.size();
547 if (n == 0) return {0, 0};
548 const double total = perimeter(poly);
549 double t = std::fmod(s, total);
550 if (t < 0) t += total;
551 double acc = 0.0;
552 for (size_t i = 0; i < n; ++i) {
553 const Vec2& a = poly[i];
554 const Vec2& b = poly[wrapIndex(int(i) + 1, int(n))];
555 const double seg = distance(a, b);
556 if (acc + seg >= t || i + 1 == n) {
557 const double f = seg > 1e-12 ? (t - acc) / seg : 0.0;
558 if (pos) {
559 pos->edgeIndex = int(i);
560 pos->t = std::clamp(f, 0.0, 1.0);
561 }
562 return a + (b - a) * f;
563 }
564 acc += seg;
565 }
566 if (pos) {
567 pos->edgeIndex = 0;
568 pos->t = 0.0;
569 }
570 return poly[0];
571}
572
573std::vector<BoundarySample> sampleBoundary(const Polygon& poly, int count) {
574 std::vector<BoundarySample> samples;
575 const size_t n = poly.size();
576 if (n < 3) return samples;
577 const int k = std::max(8, count);
578 const double total = perimeter(poly);
579 samples.reserve(size_t(k));
580 for (int i = 0; i < k; ++i) {
581 const double s = double(i) * total / double(k);
583 const Vec2 p = pointAtBoundaryLength(poly, s, &pos);
584 const Vec2& a = poly[size_t(pos.edgeIndex)];
585 const Vec2& b = poly[wrapIndex(pos.edgeIndex + 1, int(n))];
586 const Vec2 dir = normalize(b - a);
587 samples.push_back({p, std::atan2(dir.y, dir.x), s});
588 }
589 return samples;
590}
591
592double includedAngleDeg(const Vec2& u, const Vec2& v) {
593 const Vec2 nu = normalize(u);
594 const Vec2 nv = normalize(v);
595 const double c = std::clamp(dot(nu, nv), -1.0, 1.0);
596 return std::acos(c) * 180.0 / 3.14159265358979323846;
597}
598
599bool isCollinear(const Vec2& prev, const Vec2& shared, const Vec2& next) {
600 return includedAngleDeg(prev - shared, next - shared) > 135.0;
601}
602
604 const size_t n = ring.size();
605 if (n <= 3) return ring;
606 Polygon out;
607 // Group maximal runs of collinear consecutive edges; each run keeps first+last vertex.
608 std::vector<char> merged(n, 0);
609 for (size_t i = 0; i < n; ++i) {
610 const Vec2& prev = ring[wrapIndex(int(i) - 1, int(n))];
611 const Vec2& cur = ring[i];
612 const Vec2& next = ring[wrapIndex(int(i) + 1, int(n))];
613 if (isCollinear(prev, cur, next)) merged[i] = 1;
614 }
615 for (size_t i = 0; i < n; ++i) {
616 if (merged[i]) continue;
617 out.push_back(ring[i]);
618 }
619 if (out.size() < 3) return ring;
620 // Wrap-around: if the ring starts/ends with merged vertices, drop them at the seam.
621 while (out.size() > 3) {
622 const Vec2& a = out[out.size() - 2];
623 const Vec2& b = out.back();
624 const Vec2& c = out[0];
625 if (isCollinear(a, b, c)) {
626 out.pop_back();
627 continue;
628 }
629 const Vec2& d = out[1];
630 if (isCollinear(b, out[0], d)) {
631 out.erase(out.begin());
632 continue;
633 }
634 break;
635 }
637 return out;
638}
639
640double shapeIrregularity(const Polygon& approxRing, double gammaAngle, double gammaSide) {
641 const size_t n = approxRing.size();
642 if (n < 3) return std::numeric_limits<double>::infinity();
643 // Interior angles.
644 std::vector<double> angles(n);
645 double angleMean = 0.0;
646 for (size_t i = 0; i < n; ++i) {
647 const Vec2& prev = approxRing[wrapIndex(int(i) - 1, int(n))];
648 const Vec2& cur = approxRing[i];
649 const Vec2& next = approxRing[wrapIndex(int(i) + 1, int(n))];
650 const Vec2 u = normalize(prev - cur);
651 const Vec2 v = normalize(next - cur);
652 const double c = std::clamp(dot(u, v), -1.0, 1.0);
653 // Interior angle in [0, 2π): the smaller angle may be the exterior one for reflex corners.
654 // Use the angle that keeps the polygon inside; for simple CCW polygons the interior
655 // angle is the one on the left side of the direction change.
656 double a = std::acos(c);
657 if (cross(u, v) < 0.0) a = 2.0 * 3.14159265358979323846 - a;
658 angles[i] = a;
659 angleMean += a;
660 }
661 angleMean /= double(n);
662 double sideMean = 0.0;
663 std::vector<double> sides(n);
664 for (size_t i = 0; i < n; ++i) {
665 const double l = distance(approxRing[i], approxRing[wrapIndex(int(i) + 1, int(n))]);
666 sides[i] = l;
667 sideMean += l;
668 }
669 sideMean /= double(n);
670 double angleVar = 0.0;
671 double sideVar = 0.0;
672 for (size_t i = 0; i < n; ++i) {
673 const double da = angles[i] - angleMean;
674 angleVar += da * da;
675 const double dl = sides[i] - sideMean;
676 sideVar += dl * dl;
677 }
678 angleVar /= double(n);
679 sideVar /= double(n);
680 if (sideMean <= 1e-12) return std::numeric_limits<double>::infinity();
681 return gammaAngle * angleVar + gammaSide * sideVar / (sideMean * sideMean);
682}
683
684namespace {
685
687Polygon boundaryChain(const Polygon& poly, const BoundaryPosition& from, const BoundaryPosition& to, const Vec2& pFrom,
688 const Vec2& pTo) {
689 const size_t n = poly.size();
690 Polygon chain;
691 const int startEdge = from.edgeIndex;
692 const int endEdge = to.edgeIndex;
693 if (startEdge == endEdge) {
694 if (from.t <= to.t) {
695 // Both points on the same edge, A before B: the forward chain is the short sub-segment.
696 chain.push_back(pFrom);
697 if (!(pFrom == pTo)) chain.push_back(pTo);
698 return chain;
699 }
700 // A after B on the same edge: the forward chain wraps all the way around.
701 chain.push_back(pFrom);
702 int e = startEdge;
703 while (true) {
704 e = wrapIndex(e + 1, int(n));
705 if (e == endEdge) break;
706 chain.push_back(poly[size_t(e)]);
707 }
708 chain.push_back(poly[size_t(endEdge)]);
709 chain.push_back(pTo);
710 return chain;
711 }
712 chain.push_back(pFrom);
713 int e = wrapIndex(startEdge + 1, int(n));
714 while (e != endEdge) {
715 chain.push_back(poly[size_t(e)]);
716 e = wrapIndex(e + 1, int(n));
717 }
718 if (to.t > 1e-12) chain.push_back(poly[size_t(endEdge)]);
719 chain.push_back(pTo);
720 return chain;
721}
722
723} // namespace
724
725bool splitPolygonByPolyline(const Polygon& poly, const Polyline& split, const BoundaryPosition& posA,
726 const BoundaryPosition& posB, Polygon& outA, Polygon& outB) {
727 if (poly.size() < 3 || split.size() < 2) return false;
728 if (posA.edgeIndex == posB.edgeIndex && std::fabs(posA.t - posB.t) < 1e-9) {
729 return false; // degenerate: same boundary point
730 }
731 const Vec2 pa = split.front();
732 const Vec2 pb = split.back();
733
734 Polygon chainAB = boundaryChain(poly, posA, posB, pa, pb); // boundary A -> B (CCW)
735 Polygon chainBA = boundaryChain(poly, posB, posA, pb, pa); // boundary B -> A (CCW)
736
737 // Loop 1: chain(A->B) + reversed split (B->A)
738 outA = chainAB;
739 for (auto it = split.rbegin(); it != split.rend(); ++it) outA.push_back(*it);
740 // Loop 2: chain(B->A) + split (A->B)
741 outB = chainBA;
742 for (const Vec2& p : split) outB.push_back(p);
743
744 cleanupRing(outA);
745 cleanupRing(outB);
746 ensureCCW(outA);
747 ensureCCW(outB);
748 return polygonIsSimple(outA) && polygonIsSimple(outB);
749}
750
751bool validSplit(const Polygon& poly, const Polyline& split, double minHalfArea, Polygon* outA, Polygon* outB,
752 double* fracA) {
753 if (split.size() < 2) return false;
754 // Endpoints must lie on the boundary.
755 BoundaryPosition posA, posB;
756 const Vec2 pa = closestPointOnBoundary(poly, split.front(), &posA);
757 const Vec2 pb = closestPointOnBoundary(poly, split.back(), &posB);
758 const double snapTol = 1e-4 * std::max(1.0, perimeter(poly));
759 if (distance(pa, split.front()) > snapTol || distance(pb, split.back()) > snapTol) return false;
760 if (distance(pa, pb) <= 1e-9) return false;
761 // Every segment midpoint must be strictly inside the polygon (endpoints on the boundary).
762 for (size_t i = 1; i < split.size(); ++i) {
763 const Vec2 mid = (split[i - 1] + split[i]) * 0.5;
764 if (!pointInPolygon(mid, poly)) return false;
765 }
766 if (polylineSelfIntersects(split)) return false;
767
768 Polygon a, b;
769 Polyline snapped = split;
770 snapped.front() = pa;
771 snapped.back() = pb;
772 if (!splitPolygonByPolyline(poly, snapped, posA, posB, a, b)) return false;
773 const double areaPoly = area(poly);
774 const double areaA = area(a);
775 const double areaB = area(b);
776 if (areaPoly <= 1e-12) return false;
777 // Sum-of-areas invariant.
778 if (std::fabs(areaA + areaB - areaPoly) > 0.02 * areaPoly) return false;
779 if (areaA < minHalfArea || areaB < minHalfArea) return false;
780 const double fa = areaA / areaPoly;
781 if (fa < 0.02 || fa > 0.98) return false;
782 if (outA) *outA = std::move(a);
783 if (outB) *outB = std::move(b);
784 if (fracA) *fracA = fa;
785 return true;
786}
787
788bool triangulatePolygon(const Polygon& poly, std::vector<int>& outTriangles) {
789 const size_t n = poly.size();
790 outTriangles.clear();
791 if (n < 3) return false;
792 if (!polygonIsSimple(poly)) return false;
793 std::vector<int> idx(n);
794 for (size_t i = 0; i < n; ++i) idx[size_t(i)] = int(i);
795 int guard = 0;
796 while (idx.size() > 3 && guard++ < 100000) {
797 bool clipped = false;
798 const size_t m = idx.size();
799 for (size_t i = 0; i < m; ++i) {
800 const int iPrev = idx[wrapIndex(int(i) - 1, int(m))];
801 const int iCur = idx[size_t(i)];
802 const int iNext = idx[wrapIndex(int(i) + 1, int(m))];
803 const Vec2& a = poly[size_t(iPrev)];
804 const Vec2& b = poly[size_t(iCur)];
805 const Vec2& c = poly[size_t(iNext)];
806 // Convex ear? For CCW polygon, cross(ab, bc) > 0 means the corner is convex.
807 if (cross(b - a, c - b) <= 0.0) continue;
808 // No other vertex inside the ear triangle.
809 bool empty = true;
810 for (size_t j = 0; j < m; ++j) {
811 const int v = idx[size_t(j)];
812 if (v == iPrev || v == iCur || v == iNext) continue;
813 if (pointInPolygon(poly[size_t(v)], {a, b, c})) {
814 empty = false;
815 break;
816 }
817 }
818 if (!empty) continue;
819 outTriangles.push_back(iPrev);
820 outTriangles.push_back(iCur);
821 outTriangles.push_back(iNext);
822 idx.erase(idx.begin() + long(i));
823 clipped = true;
824 break;
825 }
826 if (!clipped) {
827 outTriangles.clear();
828 return false;
829 }
830 }
831 if (idx.size() == 3) {
832 outTriangles.push_back(idx[0]);
833 outTriangles.push_back(idx[1]);
834 outTriangles.push_back(idx[2]);
835 }
836 return outTriangles.size() >= 3;
837}
838
839double distanceToSegment(const Vec2& p, const Vec2& a, const Vec2& b) {
840 Vec2 unused;
841 return closestPointOnSegment(p, a, b, &unused);
842}
843
844} // namespace eve::procgen::urban
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int mid
Definition AnimSmr.cpp:120
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
glm::vec4 p[6]
std::vector< double > angles
ScriptForceVector chord
float u
Definition Grass.cpp:233
float area
Definition Grass.cpp:62
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
std::uint32_t ab
double r
std::uint32_t ac
float v
std::int32_t c
JointPoint2D axis
std::string to
std::string from
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
Vec3 centroid
float tr
glm::dvec3 dx
int idx
float f
bool hit
float d
int steps
float t
glm::mat4 proj
bool found
std::array< std::array< double, 3 >, 3 > axes
ScriptStructure out
float dy
Definition Shadow.cpp:151
int count
std::map< Cell, int > best
int spacing
int margin
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
int sides
Definition TreeMesh.cpp:459
V3 dir
Definition TreeMesh.cpp:151
std::vector< double > phi
double oy
std::vector< char > inside
double ox
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Polygon approximatePolygon(const Polygon &ring)
Simplify a ring to its approximate polygon: consecutive edges with included angle > 135° are merged i...
bool validSplit(const Polygon &poly, const Polyline &split, double minHalfArea, Polygon *outA, Polygon *outB, double *fracA)
Validity of a candidate split: both halves simple, positive area, inside the original.
std::vector< Vec2 > Polyline
Open polyline (e.g. a streamline candidate or a street centerline).
Definition UrbanTypes.h:57
double includedAngleDeg(const Vec2 &u, const Vec2 &v)
Included angle in degrees at the shared vertex between edge u (prev->shared) and v (shared->next),...
bool pointInPolygon(const Vec2 &p, const Polygon &poly)
Point-in-polygon test (ray casting; boundary counts as inside).
Vec2 pointAtBoundaryLength(const Polygon &poly, double s, BoundaryPosition *pos)
Interpolate the boundary point at arc length s in [0, perimeter).
bool splitPolygonByPolyline(const Polygon &poly, const Polyline &split, const BoundaryPosition &posA, const BoundaryPosition &posB, Polygon &outA, Polygon &outB)
Split a CCW simple polygon by a polyline whose endpoints lie on the boundary and whose interior point...
bool triangulatePolygon(const Polygon &poly, std::vector< int > &outTriangles)
Triangulate a simple polygon by ear clipping; returns CCW triangles (3*i..3*i+2).
bool polylineSelfIntersects(const Polyline &pl)
True if any two non-adjacent segments of the open polyline cross.
double closestPointOnSegment(const Vec2 &p, const Vec2 &a, const Vec2 &b, Vec2 *out)
Closest point on segment a-b; returns distance and writes out.
double distanceToSegment(const Vec2 &p, const Vec2 &a, const Vec2 &b)
Raster helper: does the pixel-center fall within eps of segment a-b?
Vec2 normalize(const Vec2 &a)
Normalize.
Definition UrbanTypes.h:44
double dot(const Vec2 &a, const Vec2 &b)
Dot.
Definition UrbanTypes.h:38
std::vector< Vec2 > Polygon
Closed polygon ring, stored CCW, without repeating the first point.
Definition UrbanTypes.h:55
double cross(const Vec2 &a, const Vec2 &b)
Cross.
Definition UrbanTypes.h:36
bool segmentsIntersect(const Vec2 &a, const Vec2 &b, const Vec2 &c, const Vec2 &d, Vec2 *out)
True if the open segments a-b and c-d properly cross; out receives the crossing.
double perimeter(const Polygon &poly)
Perimeter length of a closed ring.
double lengthSq(const Vec2 &a)
Length sq.
Definition UrbanTypes.h:42
std::vector< BoundarySample > sampleBoundary(const Polygon &poly, int count)
Uniformly sample the polygon boundary (approx. count samples, at least 8). Samples are ordered along ...
bool polygonIsSimple(const Polygon &poly)
Simple polygon test: no self intersections among non-adjacent ring edges.
double signedArea(const Polygon &poly)
Return the raw (possibly negative) signed area of a polygon ring.
bool pointOnSegment(const Vec2 &p, const Vec2 &a, const Vec2 &b, double eps)
True if p lies on segment a-b (within tolerance).
double shapeIrregularity(const Polygon &approxRing, double gammaAngle, double gammaSide)
Shape irregularity metric of Eq. (1) over the approximate polygon: I = γ1·(1/N)·Σ(θi−θ̄)² + γ2·(1/(N·...
void cleanupRing(Polygon &poly, double eps)
Remove consecutive duplicate points (within eps) and points that create zero spikes.
double polylineLength(const Polyline &pl)
Total length of an open polyline.
std::vector< SplitCandidate > generateSplitCandidates(const Polygon &poly, int maxCandidates, double minHalfArea)
Generate candidate streamlines for binary partitioning of poly.
bool segmentIntersectsPolyline(const Vec2 &a, const Vec2 &b, const Polyline &pl)
True if a segment crosses any segment of an open polyline (excluding shared endpoints).
Vec2 closestPointOnBoundary(const Polygon &poly, const Vec2 &p, BoundaryPosition *pos)
Closest point on the polygon boundary; writes edge index + t in [0,1].
bool ensureCCW(Polygon &poly)
Ensure the ring is CCW (positive signed area); returns whether it was flipped.
bool isCollinear(const Vec2 &prev, const Vec2 &shared, const Vec2 &next)
True when two consecutive edges are considered collinear (included angle > 135°).
Where a point sits on the polygon boundary: edge edgeIndex at parameter t in [0,1].
Definition UrbanTypes.h:152
A boundary sample used for field constraints / candidate seeds.
Definition UrbanTypes.h:158
Candidate splitting lines for a parcel (paper Section 4.1). Each candidate is a polyline from one bou...
Minimal 2D vector used by the urban layout algorithms (paper coordinates).
Definition UrbanTypes.h:15