15constexpr double kPi = 3.14159265358979323846;
24 std::vector<double>
phi;
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;
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);
37 return inside[size_t(yy) * size_t(nx) + size_t(xx)] != 0;
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);
51 const int ix[2] = {x0, x1};
52 const int iy[2] = {y0, y1};
54 for (
int j = 0; j < 2; ++j) {
55 for (
int i = 0; i < 2; ++i) {
59 if (cellInside(
cx,
cy)) {
60 a =
phi[size_t(
cy) * size_t(nx) + size_t(
cx)];
62 int ccx =
cx, ccy =
cy;
64 while (!cellInside(ccx, ccy) && guard++ < 64) {
67 for (
int r = 1;
r <= 4; ++
r) {
85 a =
phi[size_t(ccy) * size_t(nx) + size_t(ccx)];
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;
91 double a = std::atan2(avg.y, avg.x);
92 if (
a < 0)
a += 2.0 * kPi;
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);
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);
121 for (
int y = 0;
y <
f.ny; ++
y) {
122 for (
int x = 0;
x <
f.nx; ++
x) {
125 f.inside[size_t(
y) * size_t(
f.nx) + size_t(
x)] = 1;
126 BoundaryPosition
pos;
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;
141 std::vector<double>
next(
f.phi.size(), 0.0);
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;
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) {
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)};
160 double a = std::atan2(sum.y, sum.x);
161 if (
a < 0)
a += 2.0 * kPi;
177Polyline traceStreamline(
const CrossField& field,
const Polygon& poly,
const Vec2&
seed,
const Vec2& initialDir,
178 double spacing,
int maxSteps) {
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);
191 double bestScore = -1.0;
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) {
207 BoundaryPosition
pos;
213 BoundaryPosition
pos;
215 if (
distance(np, bpt) < boundaryTol) {
225double polylineChord(
const Polyline& pl) {
226 if (pl.size() < 2)
return 0.0;
227 return distance(pl.front(), pl.back());
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;
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)));
247 std::vector<Polyline> traces;
250 const double theta =
s.tangentAngle;
251 const Vec2 axes[2] = {{std::cos(theta), std::sin(theta)}, {-std::sin(theta), std::cos(theta)}};
253 if (
dot(
axis, inward) <= 0.05)
continue;
255 if (
tr.size() < 4)
continue;
256 if (polylineChord(
tr) <
spacing * 2.0)
continue;
257 traces.push_back(std::move(
tr));
262 std::vector<SplitCandidate>
valid;
270 valid.push_back(std::move(cand));
271 if (
valid.size() >= size_t(maxCandidates) * 3)
break;
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;
283 const int half = k / 2;
284 std::vector<int>
steps;
285 for (
int s = half;
s >= 3; --
s)
steps.push_back(
s);
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;
297 chords.push_back(std::move(cand));
298 if (chords.size() >=
size_t(maxCandidates) * 3)
break;
300 if (chords.size() >=
size_t(maxCandidates) * 3)
break;
303 valid.insert(
valid.end(), chords.begin(), chords.end());
311 const double eps = std::sqrt(
area(poly)) * 1e-3;
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)) {
326 if (
int(
out.size()) >= maxCandidates)
break;
337constexpr double kEps = 1e-9;
339int wrapIndex(
int i,
int n) {
340 if (
n <= 0)
return 0;
341 return ((i %
n) +
n) %
n;
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;
348bool onSegmentTol(
const Vec2&
p,
const Vec2&
a,
const Vec2&
b,
double eps) {
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;
361 const size_t n = poly.size();
362 if (
n < 3)
return 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))];
376 for (
size_t i = 1; i < pl.size(); ++i) l +=
distance(pl[i - 1], pl[i]);
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;
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))];
392 c =
c + (
p +
q) * cr;
394 if (std::fabs(
a) < 1e-12)
return poly[0];
395 return c / (3.0 *
a);
400 for (
size_t i = 0; i < poly.size(); ++i)
p +=
distance(poly[i], poly[wrapIndex(
int(i) + 1,
int(poly.size()))]);
406 std::reverse(poly.begin(), poly.end());
414 out.reserve(poly.size());
415 for (
const Vec2&
p : poly) {
416 if (!
out.empty() && samePoint(
out.back(),
p, eps))
continue;
418 if (
out.size() >= 2) {
429 while (
out.size() > 3 && samePoint(
out.front(),
out.back(), eps))
out.pop_back();
430 if (
out.size() >= 3) {
435 poly = std::move(
out);
439 if (poly.size() < 3)
return 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];
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);
457 const double denom =
cross(
ab, cd);
458 const double eps = 1e-12;
459 if (std::fabs(denom) <= eps)
return false;
460 const double t =
cross(
ac, cd) / denom;
462 if (t < -eps || t > 1.0 + eps || u < -eps || u > 1.0 + eps)
return false;
468 for (
size_t i = 1; i < pl.size(); ++i) {
476 for (
size_t i = 1; i < pl.size(); ++i) {
477 for (
size_t j = i + 2; j < pl.size(); ++j) {
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));
494 if (j == i + 1)
continue;
495 if (i == 0 && j ==
n - 1)
continue;
500 return area(poly) > 1e-12;
510 const double t = std::clamp(
dot(
p -
a,
ab) / l2, 0.0, 1.0);
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];
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))];
528 if (l2 > 1e-18)
t = std::clamp(
dot(
p -
a,
ab) / l2, 0.0, 1.0);
539 pos->edgeIndex = bestEdge;
546 const size_t n = poly.size();
547 if (
n == 0)
return {0, 0};
549 double t = std::fmod(
s, total);
550 if (
t < 0)
t += total;
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))];
556 if (acc + seg >=
t || i + 1 ==
n) {
557 const double f = seg > 1e-12 ? (
t - acc) / seg : 0.0;
559 pos->edgeIndex = int(i);
560 pos->t = std::clamp(
f, 0.0, 1.0);
562 return a + (
b -
a) *
f;
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);
579 samples.reserve(
size_t(k));
580 for (
int i = 0; i < k; ++i) {
581 const double s = double(i) * total / double(k);
584 const Vec2&
a = poly[size_t(
pos.edgeIndex)];
585 const Vec2&
b = poly[wrapIndex(
pos.edgeIndex + 1,
int(
n))];
587 samples.push_back({
p, std::atan2(
dir.y,
dir.x),
s});
595 const double c = std::clamp(
dot(nu, nv), -1.0, 1.0);
596 return std::acos(
c) * 180.0 / 3.14159265358979323846;
604 const size_t n = ring.size();
605 if (
n <= 3)
return ring;
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))];
615 for (
size_t i = 0; i <
n; ++i) {
616 if (merged[i])
continue;
617 out.push_back(ring[i]);
619 if (
out.size() < 3)
return ring;
621 while (
out.size() > 3) {
641 const size_t n = approxRing.size();
642 if (
n < 3)
return std::numeric_limits<double>::infinity();
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))];
652 const double c = std::clamp(
dot(
u,
v), -1.0, 1.0);
656 double a = std::acos(
c);
657 if (
cross(
u,
v) < 0.0)
a = 2.0 * 3.14159265358979323846 -
a;
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))]);
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;
675 const double dl =
sides[i] - sideMean;
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);
687Polygon boundaryChain(
const Polygon& poly,
const BoundaryPosition&
from,
const BoundaryPosition&
to,
const Vec2& pFrom,
689 const size_t n = poly.size();
691 const int startEdge =
from.edgeIndex;
692 const int endEdge =
to.edgeIndex;
693 if (startEdge == endEdge) {
696 chain.push_back(pFrom);
697 if (!(pFrom == pTo)) chain.push_back(pTo);
701 chain.push_back(pFrom);
704 e = wrapIndex(e + 1,
int(
n));
705 if (e == endEdge)
break;
706 chain.push_back(poly[
size_t(e)]);
708 chain.push_back(poly[
size_t(endEdge)]);
709 chain.push_back(pTo);
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));
718 if (
to.t > 1e-12) chain.push_back(poly[
size_t(endEdge)]);
719 chain.push_back(pTo);
727 if (poly.size() < 3 || split.size() < 2)
return false;
731 const Vec2 pa = split.front();
732 const Vec2 pb = split.back();
734 Polygon chainAB = boundaryChain(poly, posA, posB, pa, pb);
735 Polygon chainBA = boundaryChain(poly, posB, posA, pb, pa);
739 for (
auto it = split.rbegin(); it != split.rend(); ++it) outA.push_back(*it);
742 for (
const Vec2&
p : split) outB.push_back(
p);
753 if (split.size() < 2)
return false;
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;
762 for (
size_t i = 1; i < split.size(); ++i) {
763 const Vec2 mid = (split[i - 1] + split[i]) * 0.5;
770 snapped.front() = pa;
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;
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;
789 const size_t n = poly.size();
790 outTriangles.clear();
791 if (
n < 3)
return false;
793 std::vector<int>
idx(
n);
794 for (
size_t i = 0; i <
n; ++i)
idx[
size_t(i)] = int(i);
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)];
807 if (
cross(
b -
a,
c -
b) <= 0.0)
continue;
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;
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));
827 outTriangles.clear();
831 if (
idx.size() == 3) {
832 outTriangles.push_back(
idx[0]);
833 outTriangles.push_back(
idx[1]);
834 outTriangles.push_back(
idx[2]);
836 return outTriangles.size() >= 3;
std::vector< double > angles
std::array< double, 10 > q
std::array< std::array< double, 3 >, 3 > axes
std::map< Cell, int > best
std::vector< double > phi
std::vector< char > inside
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).
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).
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.
double dot(const Vec2 &a, const Vec2 &b)
Dot.
std::vector< Vec2 > Polygon
Closed polygon ring, stored CCW, without repeating the first point.
double cross(const Vec2 &a, const Vec2 &b)
Cross.
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.
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].
A boundary sample used for field constraints / candidate seeds.
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).