载入中...
搜索中...
未找到
UrbanOutput.cpp
浏览该文件的文档.
2
4#include "procgen/Grid2D.h"
5#include "procgen/MeshBuild.h"
6#include "procgen/Params.h"
7#include "procgen/Semantic.h"
12
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <limits>
17#include <sstream>
18#include <string>
19#include <vector>
20
21namespace eve::procgen::urban {
22namespace {
23
24constexpr double kPi = 3.14159265358979323846;
25
26std::vector<std::string> split(const std::string& s, char sep) {
27 std::vector<std::string> parts;
28 std::string cur;
29 for (const char c : s) {
30 if (c == sep) {
31 if (!cur.empty()) parts.push_back(cur);
32 cur.clear();
33 } else {
34 cur.push_back(c);
35 }
36 }
37 if (!cur.empty()) parts.push_back(cur);
38 return parts;
39}
40
41bool parsePoints(const std::string& text, Polygon& out) {
42 out.clear();
43 for (const std::string& pair : split(text, ';')) {
44 const auto xy = split(pair, ',');
45 if (xy.size() != 2) return false;
46 try {
47 out.push_back({std::stod(xy[0]), std::stod(xy[1])});
48 } catch (...) {
49 return false;
50 }
51 }
52 return out.size() >= 3;
53}
54
55bool makePresetLand(const std::string& preset, double w, double h, Polygon& out) {
56 out.clear();
57 const std::string p = preset.empty() ? "rect" : preset;
58 if (p == "rect") {
59 out = {{0, 0}, {w, 0}, {w, h}, {0, h}};
60 } else if (p == "triangle") {
61 out = {{0, 0}, {w, 0}, {w * 0.5, h}};
62 } else if (p == "ellipse" || p == "circle") {
63 const int segs = 28;
64 const double rx = w * 0.5;
65 const double ry = h * 0.5;
66 for (int i = 0; i < segs; ++i) {
67 const double a = double(i) * 2.0 * kPi / double(segs);
68 out.push_back({w * 0.5 + rx * std::cos(a), h * 0.5 + ry * std::sin(a)});
69 }
70 } else if (p == "l") {
71 out = {{0, 0}, {w, 0}, {w, h * 0.55}, {w * 0.45, h * 0.55}, {w * 0.45, h}, {0, h}};
72 } else if (p == "hexagon") {
73 const double cx = w * 0.5;
74 const double cy = h * 0.5;
75 for (int i = 0; i < 6; ++i) {
76 const double a = -kPi * 0.5 + double(i) * kPi / 3.0;
77 out.push_back({cx + w * 0.5 * std::cos(a), cy + h * 0.5 * std::sin(a)});
78 }
79 } else {
80 return false;
81 }
82 return out.size() >= 3;
83}
84
85void addQuad(MeshBuild& m, const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, float y, float uScale) {
86 const int base = m.getVertexCount();
87 const float ax = float(a.x), az = float(a.y);
88 const float bx = float(b.x), bz = float(b.y);
89 const float cx = float(c.x), cz = float(c.y);
90 const float dx = float(d.x), dz = float(d.y);
91 m.addVertex(ax, y, az, 0.f, 1.f, 0.f, ax * uScale, az * uScale);
92 m.addVertex(bx, y, bz, 0.f, 1.f, 0.f, bx * uScale, bz * uScale);
93 m.addVertex(cx, y, cz, 0.f, 1.f, 0.f, cx * uScale, cz * uScale);
94 m.addVertex(dx, y, dz, 0.f, 1.f, 0.f, dx * uScale, dz * uScale);
95 m.addTriangle(uint32_t(base), uint32_t(base + 1), uint32_t(base + 2));
96 m.addTriangle(uint32_t(base), uint32_t(base + 2), uint32_t(base + 3));
97}
98
99// Intersect inward edge half-planes. The result is an interior convex footprint;
100// parcels too narrow for the requested setback have no buildable footprint.
101Polygon buildingFootprint(const Polygon& parcel, double setback) {
102 if (setback <= 0.0) return parcel;
103 Polygon clipped = parcel;
104 for (size_t edge = 0; edge < parcel.size() && !clipped.empty(); ++edge) {
105 const Vec2 a = parcel[edge];
106 const Vec2 normal = perpendicular(normalize(parcel[(edge + 1) % parcel.size()] - a));
108 Vec2 previous = clipped.back();
109 double previousDistance = dot(previous - a, normal) - setback;
110 for (const Vec2 current : clipped) {
111 const double currentDistance = dot(current - a, normal) - setback;
112 if ((currentDistance >= 0.0) != (previousDistance >= 0.0)) {
113 const double t = previousDistance / (previousDistance - currentDistance);
114 next.push_back(previous + (current - previous) * t);
115 }
116 if (currentDistance >= 0.0) next.push_back(current);
118 previousDistance = currentDistance;
119 }
120 clipped = std::move(next);
121 }
122 cleanupRing(clipped);
123 if (clipped.size() < 3 || area(clipped) < 1e-6) return {};
124 return clipped;
125}
126
127} // namespace
128
129bool parseUrbanOptions(const Params& params, UrbanOptions& opts, std::string& error) {
130 opts = UrbanOptions{};
131 opts.seed = params.getSeed();
132 const double w = std::max(1.0, double(params.getFloat("landWidth", 100.f)));
133 const double h = std::max(1.0, double(params.getFloat("landHeight", 60.f)));
134 const std::string landParam = params.getString("land", "rect");
135 std::string landText = params.getString("landPoints", "");
136 if (landText.empty()) landText = landParam;
137 if (!makePresetLand(landParam, w, h, opts.land)) {
138 if (!parsePoints(landText, opts.land)) {
139 error = "urban: unknown land preset '" + landParam +
140 "' (use rect|triangle|ellipse|l|hexagon or explicit 'x,y;x,y;...' points)";
141 return false;
142 }
143 }
144 ensureCCW(opts.land);
145 opts.minParcelArea = double(params.getFloat("minParcelArea", 4.f));
146 if (!std::isfinite(opts.minParcelArea) || opts.minParcelArea <= 0.0) {
147 error = "urban: minParcelArea must be finite and positive";
148 return false;
149 }
150 opts.targetParcels = std::max(0, params.getInt("targetParcels", 120));
151 opts.maxLevels = std::max(1, params.getInt("maxLevels", 10));
152
153 opts.lambdaSize = std::max(0.0, double(params.getFloat("lambdaSize", 0.3f)));
154 opts.lambdaRegu = std::max(0.0, double(params.getFloat("lambdaRegu", 0.5f)));
155 opts.lambdaAcce = std::max(0.0, double(params.getFloat("lambdaAcce", 0.2f)));
156 opts.lambdaOrient = std::max(0.0, double(params.getFloat("lambdaOrient", 0.f)));
157 opts.gammaAngle = std::clamp(double(params.getFloat("gammaAngle", 0.75f)), 0.0, 100.0);
158 opts.gammaSide = std::clamp(double(params.getFloat("gammaSide", 0.25f)), 0.0, 100.0);
159 opts.accessThreshold = std::clamp(double(params.getFloat("accessThreshold", 0.5f)), 0.01, 10.0);
160 opts.shortEdgeFactor = std::clamp(double(params.getFloat("shortEdgeFactor", 0.2f)), 0.0, 1.0);
161 opts.streetWidth = std::max(0.1, double(params.getFloat("streetWidth", 1.f)));
162 opts.dijkstraJunctionWeight = std::max(0.0, double(params.getFloat("dijkstraJunctionWeight", 1.5f)));
163 opts.boundaryStreetFraction = std::clamp(double(params.getFloat("boundaryStreetFraction", 0.5f)), 0.0, 1.0);
164
165 const std::string pattern = params.getString("streetPattern", "default");
166 if (pattern == "loop")
167 opts.streetPattern = 1;
168 else if (pattern == "culdesac")
169 opts.streetPattern = 2;
170 else if (pattern == "tree")
171 opts.streetPattern = 3;
172 else
173 opts.streetPattern = 0;
174 opts.culDeSacAfterLevel = std::max(1, params.getInt("culDeSacAfterLevel", 4));
175
176 const std::string orient = params.getString("orientation", "none");
177 opts.orientation = orient == "east-west" ? 1 : orient == "north-south" ? 2 : 0;
178
179 const std::string boundary = params.getString("boundaryStreet", "all");
180 opts.boundaryStreetMode = boundary == "none" ? 1 : boundary == "random" ? 2 : 0;
181
182 opts.optimize = params.getInt("optimize", 1) != 0;
183 opts.optimizeIterations = std::clamp(params.getInt("optimizeIterations", 160), 0, 2000);
184 opts.optRegu = std::max(0.0, double(params.getFloat("optRegu", 0.2f)));
185 opts.optSide = std::max(0.0, double(params.getFloat("optSide", 1.f)));
186 opts.optStre = std::max(0.0, double(params.getFloat("optStre", 1.f)));
187 opts.optJunc = std::max(0.0, double(params.getFloat("optJunc", 0.5f)));
188 opts.optClose = std::max(0.0, double(params.getFloat("optClose", 0.3f)));
189 return true;
190}
191
192bool generateUrbanGrid(const Params& params, Grid2D& out, std::string& error) {
193 UrbanOptions opts;
194 if (!parseUrbanOptions(params, opts, error)) return false;
195 UrbanGenerator gen(opts);
196 if (!gen.generate(&error)) return false;
197 const UrbanLayout& layout = gen.layout();
198 if (layout.parcels.empty()) {
199 error = "urban.parcels: no parcels generated";
200 return false;
201 }
202
203 double minX = opts.land[0].x, minY = opts.land[0].y;
204 double maxX = opts.land[0].x, maxY = opts.land[0].y;
205 for (const Vec2& p : opts.land) {
206 minX = std::min(minX, p.x);
207 minY = std::min(minY, p.y);
208 maxX = std::max(maxX, p.x);
209 maxY = std::max(maxY, p.y);
210 }
211 const double landW = std::max(1e-6, maxX - minX);
212 const double landH = std::max(1e-6, maxY - minY);
213 const double cellSize = std::max(0.05, double(params.getFloat("cellSize", 1.f)));
214 const int gridW = std::clamp(int(std::ceil(landW / cellSize)) + 2, 3, 1024);
215 const int gridH = std::clamp(int(std::ceil(landH / cellSize)) + 2, 3, 1024);
216 const double ox = minX - cellSize;
217 const double oy = minY - cellSize;
218 const double halfStreet = opts.streetWidth * 0.5;
219
220 out.resize(gridW, gridH);
221 out.fill(Semantic::Wall);
222 for (int gy = 0; gy < gridH; ++gy) {
223 for (int gx = 0; gx < gridW; ++gx) {
224 const Vec2 c{ox + (double(gx) + 0.5) * cellSize, oy + (double(gy) + 0.5) * cellSize};
225 if (!pointInPolygon(c, opts.land)) continue;
226 bool onStreet = false;
227 for (const Street& s : layout.streets) {
228 for (size_t i = 1; i < s.pts.size(); ++i) {
229 if (distanceToSegment(c, s.pts[i - 1], s.pts[i]) <= halfStreet) {
230 onStreet = true;
231 break;
232 }
233 }
234 if (onStreet) break;
235 }
236 if (onStreet) {
237 out.setCell(gx, gy, int(Semantic::Road));
238 continue;
239 }
240 int pid = 0;
241 for (size_t p = 0; p < layout.parcels.size(); ++p) {
242 Polygon poly;
243 for (const int ci : layout.parcels[p].ring) poly.push_back(layout.corners[size_t(ci)]);
244 if (pointInPolygon(c, poly)) {
245 pid = int(p) + 1;
246 break;
247 }
248 }
249 out.setCell(gx, gy, pid > 0 ? int(Semantic::Floor) : int(Semantic::Wall));
250 if (pid > 0) out.setDetail(gx, gy, std::min(pid, 254));
251 }
252 }
253
254 // Parcel anchors for building placement.
255 out.clearObjects();
256 for (size_t p = 0; p < layout.parcels.size(); ++p) {
257 Polygon poly;
258 for (const int ci : layout.parcels[p].ring) poly.push_back(layout.corners[size_t(ci)]);
259 const Vec2 c = centroid(poly);
260 out.addObjectAt("parcel" + std::to_string(p), "parcel", float((c.x - ox) / cellSize),
261 float((c.y - oy) / cellSize));
262 }
263
264 out.setMeta("algorithm", "urban.parcels");
265 out.setMeta("seed", std::to_string(opts.seed));
266 out.setMeta("parcels", std::to_string(layout.parcels.size()));
267 out.setMeta("streets", std::to_string(layout.streets.size()));
268 out.setMeta("junctions", std::to_string(layout.streetJunctions));
269 out.setMeta("streetLength", std::to_string(layout.totalStreetLength));
270 out.setMeta("avgIrregularity", std::to_string(layout.avgIrregularity));
271 out.setMeta("levels", std::to_string(layout.levelsUsed));
272 out.setMeta("streetPattern", params.getString("streetPattern", "default"));
273 out.setMeta("optimize", opts.optimize ? "1" : "0");
274 out.setMeta("cellSize", std::to_string(cellSize));
275 return true;
276}
277
278bool generateUrbanMesh(const Params& params, MeshBuild& out, std::string& error) {
279 UrbanOptions opts;
280 if (!parseUrbanOptions(params, opts, error)) return false;
281 UrbanGenerator gen(opts);
282 if (!gen.generate(&error)) return false;
283 const UrbanLayout& layout = gen.layout();
284 if (layout.parcels.empty()) {
285 error = "mesh.urban: no parcels generated";
286 return false;
287 }
288
289 out.clear();
290 const float extrude = std::max(0.f, params.getFloat("extrude", 0.f));
291 const float uvScale = std::max(0.001f, params.getFloat("uvScale", 0.1f));
292 const float inset = params.getFloat("parcelInset", 0.f);
293 const float variation = params.getFloat("heightVariation", 0.f);
294 const bool details = params.getBool("presentationDetails", false) && extrude > 0.f;
295 const bool vertexColors = params.getBool("vertexColors", false) || details;
296 if (!std::isfinite(inset) || inset < 0.f || !std::isfinite(variation) || variation < 0.f || variation > 1.f) {
297 error = "mesh.urban: parcelInset must be nonnegative and heightVariation must be in [0,1]";
298 return false;
299 }
300 int windowCount = 0, treeCount = 0, markingCount = 0, parkCount = 0, crossingCount = 0;
301 int omittedFootprints = 0;
302 std::vector<float> colors;
303
304
305 // Street ribbons (slightly above the ground plane).
306 for (const Street& s : layout.streets) {
307 if (s.pts.size() < 2) continue;
308 const double half = s.width * 0.5;
309 for (size_t i = 1; i < s.pts.size(); ++i) {
310 const Vec2 dir = normalize(s.pts[i] - s.pts[i - 1]);
311 const Vec2 perp = perpendicular(dir);
312 const Vec2 l0 = s.pts[i - 1] + perp * half;
313 const Vec2 r0 = s.pts[i - 1] - perp * half;
314 const Vec2 l1 = s.pts[i] + perp * half;
315 const Vec2 r1 = s.pts[i] - perp * half;
316 addQuad(out, l0, l1, r1, r0, 0.01f, uvScale);
317 }
318 }
319
320 if (vertexColors) {
321 colors.resize(size_t(out.getVertexCount()) * 4u);
322 for (size_t v = 0; v < colors.size(); v += 4) {
323 colors[v] = 0.075f;
324 colors[v + 1] = 0.095f;
325 colors[v + 2] = 0.115f;
326 colors[v + 3] = 1.f;
327 }
328 }
329
330 // Detail meshes share the recipe's owned output and deterministic seed.
331 auto quad = [&](const Vec2& a, const Vec2& b, float bottom, float top, float nx, float ny, float nz, float r,
332 float g, float blue) {
333 const int base = out.getVertexCount();
334 out.addVertex(float(a.x), bottom, float(a.y), nx, ny, nz, 0.f, 0.f);
335 out.addVertex(float(b.x), bottom, float(b.y), nx, ny, nz, 1.f, 0.f);
336 out.addVertex(float(b.x), top, float(b.y), nx, ny, nz, 1.f, 1.f);
337 out.addVertex(float(a.x), top, float(a.y), nx, ny, nz, 0.f, 1.f);
338 out.addTriangle(base, base + 2, base + 1);
339 out.addTriangle(base, base + 3, base + 2);
340 for (int v = 0; v < 4; ++v) colors.insert(colors.end(), {r, g, blue, 1.f});
341 };
342 auto groundQuad = [&](const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, float y, float r, float g,
343 float blue) {
344 addQuad(out, a, b, c, d, y, uvScale);
345 for (int v = 0; v < 4; ++v) colors.insert(colors.end(), {r, g, blue, 1.f});
346 };
347 auto tree = [&](const Vec2& center, float size) {
348 const Vec2 trunkA{center.x - .09, center.y}, trunkB{center.x + .09, center.y};
349 quad(trunkA, trunkB, .13f, 1.1f * size, 0.f, 0.f, 1.f, .16f, .09f, .045f);
350 // Eight flat-shaded crown facets, with a broad middle ring.
351 for (int i = 0; i < 8; ++i) {
352 double a = 2 * kPi * i / 8, b = 2 * kPi * (i + 1) / 8;
353 Vec2 pa{center.x + std::cos(a) * .75 * size, center.y + std::sin(a) * .75 * size};
354 Vec2 pb{center.x + std::cos(b) * .75 * size, center.y + std::sin(b) * .75 * size};
355 for (int half = 0; half < 2; ++half) {
356 const int v = out.getVertexCount();
357 float normalY = half == 0 ? .65f : -.4f;
358 float tip = half == 0 ? 2.9f * size : .8f * size;
359 out.addVertex(float(center.x), tip, float(center.y), float(std::cos(a)), normalY, float(std::sin(a)), 0,
360 0);
361 out.addVertex(float(pa.x), 1.6f * size, float(pa.y), float(std::cos(a)), normalY, float(std::sin(a)), 0,
362 0);
363 out.addVertex(float(pb.x), 1.6f * size, float(pb.y), float(std::cos(a)), normalY, float(std::sin(a)), 0,
364 0);
365 if (half == 0)
366 out.addTriangle(v, v + 2, v + 1);
367 else
368 out.addTriangle(v, v + 1, v + 2);
369 for (int k = 0; k < 3; ++k)
370 colors.insert(colors.end(), {.055f + .012f * (i % 3), .22f + .025f * (i % 3), .105f, 1.f});
371 }
372 }
373 ++treeCount;
374 };
375 if (details) {
376 for (const Street& street : layout.streets)
377 for (size_t i = 1; i < street.pts.size(); ++i) {
378 const Vec2 a = street.pts[i - 1], b = street.pts[i], direction = normalize(b - a),
379 side = perpendicular(direction);
380 const double length = std::sqrt(dot(b - a, b - a));
381 if (length > 7.)
382 for (int endIndex = 0; endIndex < 2; ++endIndex) {
383 const Vec2 endpoint = endIndex == 0 ? a : b;
384 const Vec2 inward = endIndex == 0 ? direction : -direction;
385 bool meetsStreet = false;
386 for (const Street& other : layout.streets) {
387 if (&other == &street) continue;
388 for (size_t j = 1; j < other.pts.size(); ++j)
389 if (distanceToSegment(endpoint, other.pts[j - 1], other.pts[j]) < .2)
390 meetsStreet = true;
391 }
392 if (!meetsStreet) continue;
393 for (int stripe = 0; stripe < 4; ++stripe) {
394 Vec2 c = endpoint + inward * (1.6 + stripe * .32);
395 Vec2 d = c + inward * .17;
396 groundQuad(c + side * street.width * .38, d + side * street.width * .38,
397 d - side * street.width * .38, c - side * street.width * .38, .04f, .75f, .77f,
398 .69f);
399 }
400 ++crossingCount;
401 }
402 for (double t = 2.; t + 1. < length - 1.5; t += 3.) {
403 Vec2 start = a + direction * t, end = a + direction * (t + 1.);
404 bool junction = false;
405 for (const Street& other : layout.streets) {
406 if (&other == &street) continue;
407 for (size_t j = 1; j < other.pts.size(); ++j)
408 if (distanceToSegment((start + end) * .5, other.pts[j - 1], other.pts[j]) <
409 other.width * .65)
410 junction = true;
411 }
412 if (junction) continue;
413 groundQuad(start + side * .055, end + side * .055, end - side * .055, start - side * .055, .035f,
414 .80f, .65f, .29f);
415 ++markingCount;
416 }
417 }
418 }
419
420 for (size_t p = 0; p < layout.parcels.size(); ++p) {
421 Polygon poly;
422 for (const int ci : layout.parcels[p].ring) poly.push_back(layout.corners[size_t(ci)]);
423 Polygon sidewalk =
424 details ? buildingFootprint(poly, std::max(double(inset) * .75, opts.streetWidth * .5 + .12)) : Polygon{};
425 poly = buildingFootprint(poly, inset);
426 if (poly.empty()) {
427 ++omittedFootprints;
428 continue;
429 }
430 if (details && !sidewalk.empty()) {
431 std::vector<int> paving;
432 if (!triangulatePolygon(sidewalk, paving)) {
433 error = "mesh.urban: sidewalk triangulation failed";
434 return false;
435 }
436 const int base = out.getVertexCount();
437 for (const auto& v : sidewalk) {
438 out.addVertex(float(v.x), .10f, float(v.y), 0, 1, 0, 0, 0);
439 colors.insert(colors.end(), {.32f, .34f, .32f, 1.f});
440 }
441 for (size_t t = 0; t + 2 < paving.size(); t += 3)
442 out.addTriangle(base + paving[t], base + paving[t + 2], base + paving[t + 1]);
443 }
444 const bool park = details && ((uint32_t(p) + uint32_t(opts.seed)) % 9u == 0u);
445 if (park) {
446 std::vector<int> lawn;
447 if (!triangulatePolygon(poly, lawn)) {
448 error = "mesh.urban: park triangulation failed";
449 return false;
450 }
451 int base = out.getVertexCount();
452 Vec2 center{};
453 for (const auto& v : poly) {
454 center = center + v;
455 out.addVertex(float(v.x), .13f, float(v.y), 0, 1, 0, 0, 0);
456 colors.insert(colors.end(), {.095f, .24f, .13f, 1.f});
457 }
458 for (size_t t = 0; t + 2 < lawn.size(); t += 3)
459 out.addTriangle(base + lawn[t], base + lawn[t + 2], base + lawn[t + 1]);
460 center = center * (1. / double(poly.size()));
461 for (size_t i = 0; i < poly.size(); i += 2) tree(center * .55 + poly[i] * .45, .85f);
462 ++parkCount;
463 continue;
464 }
465 const int firstVertex = out.getVertexCount();
466 // A named recipe seed and parcel index own the variation; independent of frame time.
467 const uint32_t parcelHash = uint32_t(opts.seed) ^ (uint32_t(p) + 1u) * 0x9e3779b9u;
468 const float noise = float((parcelHash ^ (parcelHash >> 16)) & 0xffffu) / 65535.f;
469 const float parcelHeight = extrude * (1.f + variation * (2.f * noise - 1.f));
470 std::vector<int> tris;
471 if (!triangulatePolygon(poly, tris)) {
472 error = "mesh.urban: failed to triangulate parcel " + std::to_string(p);
473 return false;
474 }
475 auto emitVert = [&](const Vec2& v, float y, float nx, float ny, float nz) {
476 out.addVertex(float(v.x), y, float(v.y), nx, ny, nz, float(v.x) * uvScale, float(v.y) * uvScale);
477 };
478 if (extrude <= 0.f) {
479 const int base = out.getVertexCount();
480 for (size_t i = 0; i < poly.size(); ++i) emitVert(poly[i], 0.f, 0.f, 1.f, 0.f);
481 for (size_t t = 0; t + 2 < tris.size(); t += 3)
482 // Ear-clipping emits CCW (x,y) which is -Y in the XZ plane; flip for +Y.
483 out.addTriangle(uint32_t(base + tris[t]), uint32_t(base + tris[t + 2]), uint32_t(base + tris[t + 1]));
484 } else {
485 const double yTop = double(parcelHeight);
486 const int baseTop = out.getVertexCount();
487 for (size_t i = 0; i < poly.size(); ++i) emitVert(poly[i], float(yTop), 0.f, 1.f, 0.f);
488 for (size_t t = 0; t + 2 < tris.size(); t += 3)
489 out.addTriangle(uint32_t(baseTop + tris[t]), uint32_t(baseTop + tris[t + 2]),
490 uint32_t(baseTop + tris[t + 1]));
491 const int baseBottom = out.getVertexCount();
492 for (size_t i = 0; i < poly.size(); ++i) emitVert(poly[i], 0.f, 0.f, -1.f, 0.f);
493 for (size_t t = 0; t + 2 < tris.size(); t += 3)
494 out.addTriangle(uint32_t(baseBottom + tris[t]), uint32_t(baseBottom + tris[t + 1]),
495 uint32_t(baseBottom + tris[t + 2]));
496 const size_t m = poly.size();
497 for (size_t i = 0; i < m; ++i) {
498 const Vec2& a = poly[i];
499 const Vec2& b = poly[(i + 1) % m];
500 const Vec2 n = normalize(perpendicular(a - b));
501 const int base = out.getVertexCount();
502 emitVert(a, 0.f, float(n.x), 0.f, float(n.y));
503 emitVert(b, 0.f, float(n.x), 0.f, float(n.y));
504 emitVert(b, float(yTop), float(n.x), 0.f, float(n.y));
505 emitVert(a, float(yTop), float(n.x), 0.f, float(n.y));
506 out.addTriangle(uint32_t(base), uint32_t(base + 2), uint32_t(base + 1));
507 out.addTriangle(uint32_t(base), uint32_t(base + 3), uint32_t(base + 2));
508 }
509 }
510 if (vertexColors) {
511 const float warm = float(parcelHash % 3u) * 0.055f;
512 for (int v = firstVertex; v < out.getVertexCount(); ++v) {
513 const bool roof = out.getNormalY(v) > 0.5f;
514 if (details) {
515 const float palette[3][3] = {{.45f, .40f, .31f}, {.26f, .36f, .39f}, {.49f, .28f, .19f}};
516 const auto& wall = palette[parcelHash % 3];
517 colors.insert(colors.end(),
518 {roof ? .12f : wall[0], roof ? .16f : wall[1], roof ? .17f : wall[2], 1.f});
519 continue;
520 }
521 colors.insert(colors.end(), {roof ? 0.27f + warm : 0.62f + warm, roof ? 0.34f + warm : 0.64f,
522 roof ? 0.40f : 0.65f - warm, 1.f});
523 }
524 }
525 if (details) {
526 // Windows are inset within each actual facade edge, never projected onto unrelated parcels.
527 for (size_t edge = 0; edge < poly.size(); ++edge) {
528 Vec2 a = poly[edge], b = poly[(edge + 1) % poly.size()], delta = b - a;
529 double length = std::sqrt(dot(delta, delta));
531 int columns = int(length / 1.25), floors = int((parcelHeight - .65f) / 1.25f);
532 for (int floor = 0; floor < floors; ++floor)
533 for (int column = 0; column < columns; ++column) {
534 double u = (column + .5) / columns, half = .35 / length;
535 Vec2 left = a + delta * (u - half) + normal * .025,
536 right = a + delta * (u + half) + normal * .025;
537 bool lit = ((column + floor + int(parcelHash % 11)) % 11) == 0;
538 quad(left, right, .65f + floor * 1.25f, 1.35f + floor * 1.25f, float(normal.x), 0,
539 float(normal.y), lit ? .60f : .025f, lit ? .40f : .095f, lit ? .16f : .13f);
540 ++windowCount;
541 }
542 // A shallow cornice closes each roof edge.
543 quad(a + normal * .035, b + normal * .035, parcelHeight, parcelHeight + .18f, float(normal.x), 0,
544 float(normal.y), .22f, .25f, .24f);
545 if (edge == 0 && length > 2.) {
546 Vec2 mid = (a + b) * .5;
547 quad(mid - delta * (.4 / length) + normal * .035, mid + delta * (.4 / length) + normal * .035, .11f,
548 1.3f, float(normal.x), 0, float(normal.y), .035f, .055f, .06f);
549 }
550 }
551 Vec2 center{};
552 for (const auto& v : poly) center = center + v;
553 center = center * (1. / double(poly.size()));
554 // A roof service cap, scaled inside the convex building footprint.
555 std::vector<int> cap;
556 Polygon equipment;
557 for (const auto& v : poly) equipment.push_back(center * .75 + v * .25);
558 if (!triangulatePolygon(equipment, cap)) {
559 error = "mesh.urban: roof equipment triangulation failed";
560 return false;
561 }
562 int base = out.getVertexCount();
563 for (const auto& v : equipment) {
564 out.addVertex(float(v.x), parcelHeight + .4f, float(v.y), 0, 1, 0, 0, 0);
565 colors.insert(colors.end(), {.26f, .29f, .27f, 1.f});
566 }
567 for (size_t t = 0; t + 2 < cap.size(); t += 3)
568 out.addTriangle(base + cap[t], base + cap[t + 2], base + cap[t + 1]);
569 for (size_t i = 0; i < equipment.size(); ++i) {
570 Vec2 a = equipment[i], b = equipment[(i + 1) % equipment.size()], n = normalize(perpendicular(a - b));
571 quad(a, b, parcelHeight, parcelHeight + .4f, float(n.x), 0, float(n.y), .19f, .22f, .21f);
572 }
573 // Trees stand in the paved setback, outside the building edge.
574 if (p % 2 == 0 && !sidewalk.empty()) {
575 Vec2 site = sidewalk[0] * .65 + poly[0] * .35;
576 tree(site, .65f);
577 }
578 }
579 }
580
581 if (vertexColors) {
582 auto colored = out.setVertexColors(std::move(colors));
583 if (!colored) {
584 error = colored.status().describe();
585 return false;
586 }
587 }
588 out.setMeta("detail.crossings", std::to_string(crossingCount));
589 out.setMeta("detail.windows", std::to_string(windowCount));
590 out.setMeta("detail.trees", std::to_string(treeCount));
591 out.setMeta("detail.markings", std::to_string(markingCount));
592 out.setMeta("detail.parks", std::to_string(parkCount));
593 out.setMeta("omittedFootprints", std::to_string(omittedFootprints));
594 out.setMeta("parcelInset", std::to_string(inset));
595
596 out.setMeta("algorithm", "mesh.urban");
597 out.setMeta("seed", std::to_string(opts.seed));
598 out.setMeta("parcels", std::to_string(layout.parcels.size()));
599 out.setMeta("streets", std::to_string(layout.streets.size()));
600 out.setMeta("junctions", std::to_string(layout.streetJunctions));
601 out.setMeta("streetLength", std::to_string(layout.totalStreetLength));
602 out.setMeta("avgIrregularity", std::to_string(layout.avgIrregularity));
603 out.setMeta("extrude", std::to_string(extrude));
604 return true;
605}
606
607static RecipeDescriptor makeUrbanDescriptor(std::string id, std::string name,
608 std::string category) {
609 RecipeDescriptor descriptor{std::move(id), std::move(name), std::move(category), {}};
610 descriptor.params.push_back(ParamDescriptor::integer("seed", "Seed", 1, 0, 2147483647));
611 descriptor.params.push_back(ParamDescriptor::choice("land", "Land Shape", "rect",
612 {"rect", "triangle", "ellipse", "l", "hexagon"}));
613 descriptor.params.push_back(ParamDescriptor::floating("landWidth", "Land Width", 100.f, 1.f, 10000.f, 1.f));
614 descriptor.params.push_back(ParamDescriptor::floating("landHeight", "Land Height", 60.f, 1.f, 10000.f, 1.f));
615 descriptor.params.push_back(ParamDescriptor::text("landPoints", "Custom Land Points", ""));
616 descriptor.params.push_back(ParamDescriptor::integer("targetParcels", "Target Parcels", 120, 0, 10000));
617 descriptor.params.push_back(ParamDescriptor::floating("minParcelArea", "Minimum Parcel Area", 4.f, 0.01f,
618 10000.f, 0.1f));
619 descriptor.params.push_back(ParamDescriptor::integer("maxLevels", "Maximum Levels", 10, 1, 128));
620 descriptor.params.push_back(ParamDescriptor::choice("streetPattern", "Street Pattern", "default",
621 {"default", "loop", "culdesac", "tree"}));
622 descriptor.params.push_back(ParamDescriptor::floating("streetWidth", "Street Width", 1.f, 0.1f, 100.f,
623 0.1f));
624 descriptor.params.push_back(ParamDescriptor::choice("orientation", "Orientation", "none",
625 {"none", "east-west", "north-south"}));
626 descriptor.params.push_back(ParamDescriptor::choice("boundaryStreet", "Boundary Streets", "all",
627 {"all", "none", "random"}));
628 descriptor.params.push_back(ParamDescriptor::floating("cellSize", "Grid Cell Size", 1.f, 0.05f, 100.f,
629 0.05f));
630 descriptor.params.push_back(ParamDescriptor::boolean("optimize", "Optimize", true));
631 auto addAdvanced = [&](ParamDescriptor param) {
632 param.advanced = true;
633 descriptor.params.push_back(std::move(param));
634 };
635 addAdvanced(ParamDescriptor::floating("lambdaSize", "Size Weight", 0.3f, 0.f, 100.f, 0.01f));
636 addAdvanced(ParamDescriptor::floating("lambdaRegu", "Regularity Weight", 0.5f, 0.f, 100.f, 0.01f));
637 addAdvanced(ParamDescriptor::floating("lambdaAcce", "Access Weight", 0.2f, 0.f, 100.f, 0.01f));
638 addAdvanced(ParamDescriptor::floating("lambdaOrient", "Orientation Weight", 0.f, 0.f, 100.f, 0.01f));
639 addAdvanced(ParamDescriptor::floating("gammaAngle", "Angle Weight", 0.75f, 0.f, 100.f, 0.01f));
640 addAdvanced(ParamDescriptor::floating("gammaSide", "Side Weight", 0.25f, 0.f, 100.f, 0.01f));
641 addAdvanced(ParamDescriptor::floating("accessThreshold", "Access Threshold", 0.5f, 0.01f, 10.f, 0.01f));
642 addAdvanced(ParamDescriptor::floating("shortEdgeFactor", "Short Edge Factor", 0.2f, 0.f, 1.f, 0.01f));
643 addAdvanced(ParamDescriptor::floating("dijkstraJunctionWeight", "Junction Weight", 1.5f, 0.f, 100.f,
644 0.1f));
645 addAdvanced(ParamDescriptor::floating("boundaryStreetFraction", "Boundary Street Fraction", 0.5f, 0.f,
646 1.f, 0.01f));
647 addAdvanced(ParamDescriptor::integer("culDeSacAfterLevel", "Cul-de-sac Level", 4, 1, 128));
648 addAdvanced(ParamDescriptor::integer("optimizeIterations", "Optimize Iterations", 160, 0, 2000));
649 addAdvanced(ParamDescriptor::floating("optRegu", "Optimize Regularity", 0.2f, 0.f, 100.f, 0.01f));
650 addAdvanced(ParamDescriptor::floating("optSide", "Optimize Sides", 1.f, 0.f, 100.f, 0.01f));
651 addAdvanced(ParamDescriptor::floating("optStre", "Optimize Streets", 1.f, 0.f, 100.f, 0.01f));
652 addAdvanced(ParamDescriptor::floating("optJunc", "Optimize Junctions", 0.5f, 0.f, 100.f, 0.01f));
653 addAdvanced(ParamDescriptor::floating("optClose", "Optimize Closure", 0.3f, 0.f, 100.f, 0.01f));
654 return descriptor;
655}
656
658 registry.registerAlgorithm(
659 makeUrbanDescriptor("urban.parcels", "Urban Parcels", "Urban"), generateUrbanGrid);
660}
661
664 makeUrbanDescriptor("mesh.urban", "Urban Blocks", "Urban");
665 descriptor.params.push_back(
666 ParamDescriptor::floating("extrude", "Extrusion Height", 0.f, 0.f, 1000.f, 0.1f));
667 descriptor.params.push_back(
668 ParamDescriptor::floating("uvScale", "UV Scale", 0.1f, 0.f, 100.f, 0.01f));
669 descriptor.params.push_back(ParamDescriptor::floating("parcelInset", "Building Setback", 0.f, 0.f, 100.f, 0.1f));
670 descriptor.params.push_back(ParamDescriptor::floating("heightVariation", "Height Variation", 0.f, 0.f, 1.f, 0.05f));
671 descriptor.params.push_back(ParamDescriptor::boolean("vertexColors", "Surface Colors", false));
672 descriptor.params.push_back(ParamDescriptor::boolean("presentationDetails", "Facades, Parks and Markings", false));
673 registry.registerRecipe(std::move(descriptor), generateUrbanMesh);
674}
675
676} // namespace eve::procgen::urban
double y
double m[16]
Duration start
float w
Definition AnimClip.cpp:738
int tip
Definition AnimSmr.cpp:121
int mid
Definition AnimSmr.cpp:120
std::vector< eve::artifact::PartView > parts
std::string descriptor
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
std::string pattern
std::string palette
std::string layout
tensor::Graph g
Definition GpuGraph.cpp:7
std::uint32_t firstVertex
float u
Definition Grass.cpp:233
float area
Definition Grass.cpp:62
glm::vec3 n
Definition Grass.cpp:63
double r
float v
HexVec3 left
HexVec3 right
std::int32_t c
int h
float length
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Vec3 centroid
Texture * normal
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
const eve::script::BindingContractRegistry & registry
float d
float t
RoadLaneDirection direction
std::string text
ScriptStructure out
unsigned column
size_t end
double current
CommandLogBoundary boundary
Anchor rule, see above.
int columns
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
const char * category
double oy
double ox
float bottom
Registry for executable generators and their reflection metadata.
Intermediate 2D generation result. cells store semantic ids (see Semantic.h), not tile GIDs — convert...
Definition Grid2D.h:37
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
EVENGINE_API_DOMAINS public API.
Owning, typed generation parameters.
Definition Params.h:27
Hierarchical co-generation of parcels and streets (paper Section 4) plus the global geometric optimiz...
const UrbanLayout & layout() const
Layout.
bool generate(std::string *error=nullptr)
Run the pipeline. On failure error receives a human-readable reason.
SQInteger top
Definition Snapshot.cpp:115
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
constexpr uint32_t Floor
Definition Semantic.h:14
constexpr uint32_t Wall
Definition Semantic.h:13
constexpr uint32_t Road
Definition Semantic.h:23
void registerUrbanMeshRecipes(MeshRecipeRegistry &registry)
Registers urban mesh recipes.
Vec2 perpendicular(const Vec2 &a)
Perpendicular.
Definition UrbanTypes.h:50
bool pointInPolygon(const Vec2 &p, const Polygon &poly)
Point-in-polygon test (ray casting; boundary counts as inside).
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 parseUrbanOptions(const Params &params, UrbanOptions &opts, std::string &error)
Parse Procgen Params into urban generator options. Params: land/landPoints, minParcelArea,...
double distanceToSegment(const Vec2 &p, const Vec2 &a, const Vec2 &b)
Raster helper: does the pixel-center fall within eps of segment a-b?
bool generateUrbanMesh(const Params &params, MeshBuild &out, std::string &error)
MeshBuild of parcel blocks + street ribbons (flat or extruded, Y-up).
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
bool generateUrbanGrid(const Params &params, Grid2D &out, std::string &error)
Grid2D rasterization of the urban layout (Semantic::Road/Floor/Wall + parcel detail).
void cleanupRing(Polygon &poly, double eps)
Remove consecutive duplicate points (within eps) and points that create zero spikes.
void registerUrbanGenerators(GeneratorRegistry &registry)
Register "urban.parcels" (Grid2D) and "mesh.urban" (MeshBuild) builtins.
bool ensureCCW(Polygon &poly)
Ensure the ring is CCW (positive signed area); returns whether it was flipped.
static ParamDescriptor boolean(std::string key, std::string label, bool defaultValue)
Construct a Boolean descriptor stored as zero or one in Params.
static ParamDescriptor choice(std::string key, std::string label, std::string defaultValue, std::vector< std::string > choices)
Construct a finite-choice string descriptor.
static ParamDescriptor floating(std::string key, std::string label, float defaultValue, float minimum, float maximum, float step)
Construct a bounded floating-point descriptor.
static ParamDescriptor integer(std::string key, std::string label, int defaultValue, int minimum, int maximum, int step=1)
Construct a bounded integer descriptor.
static ParamDescriptor text(std::string key, std::string label, std::string defaultValue)
Construct a free-form string descriptor.
Complete metadata and parameter schema shared by every procgen recipe family.
Definition ParamSchema.h:52
std::vector< ParamDescriptor > params
Definition ParamSchema.h:56
A street decomposed from the street network graph: consecutive street edges whose included angle is l...
Definition UrbanTypes.h:63
Structured urban layout produced by the hierarchical co-generation (paper Section 4) plus the geometr...
Definition UrbanTypes.h:84
All user-facing controls for the urban generator. Defaults follow the paper (λ=0.3/0....
Definition UrbanTypes.h:117
Minimal 2D vector used by the urban layout algorithms (paper coordinates).
Definition UrbanTypes.h:15