载入中...
搜索中...
未找到
HexSphereTopology.cpp
浏览该文件的文档.
1// eve-hot-path
3#include <algorithm>
4#include <cmath>
5#include <cstddef>
6#include <cstdint>
7#include <string>
8#include <string_view>
9#include <unordered_map>
10#include <utility>
11#include <vector>
12#include "common/Diagnostic.h"
13#include "hexmap/HexMapMesh.h"
14#include "hexmap/HexMeshData.h"
15#include "hexmap/HexMetrics.h"
16#include "hexmap/HexNoise.h"
18
19// HexSphereTopology.cpp
20namespace eve::hexmap {
21namespace {
22
23using Vec = HexVec3;
24
26constexpr float kGoldenRatio = 1.618033988749895f;
27
29[[nodiscard]] constexpr float dot(Vec a, Vec b) noexcept { return a.x * b.x + a.y * b.y + a.z * b.z; }
30
32[[nodiscard]] constexpr Vec cross(Vec a, Vec b) noexcept {
33 return Vec{a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
34}
35
37[[nodiscard]] float length(Vec a) noexcept { return std::sqrt(dot(a, a)); }
38
46[[nodiscard]] Vec normalize(Vec a) noexcept {
47 const float len = length(a);
48 if (len <= 1e-20f) return Vec{0.f, 1.f, 0.f};
49 return Vec{a.x / len, a.y / len, a.z / len};
50}
51
53constexpr float kIcosahedronVertices[12][3] = {
54 {-1.f, kGoldenRatio, 0.f}, {1.f, kGoldenRatio, 0.f}, {-1.f, -kGoldenRatio, 0.f}, {1.f, -kGoldenRatio, 0.f},
55 {0.f, -1.f, kGoldenRatio}, {0.f, 1.f, kGoldenRatio}, {0.f, -1.f, -kGoldenRatio}, {0.f, 1.f, -kGoldenRatio},
56 {kGoldenRatio, 0.f, -1.f}, {kGoldenRatio, 0.f, 1.f}, {-kGoldenRatio, 0.f, -1.f}, {-kGoldenRatio, 0.f, 1.f},
57};
58
66constexpr std::int32_t kIcosahedronFaces[20][3] = {
67 {0, 11, 5}, {0, 5, 1}, {0, 1, 7}, {0, 7, 10}, {0, 10, 11}, {1, 5, 9}, {5, 11, 4},
68 {11, 10, 2}, {10, 7, 6}, {7, 1, 8}, {3, 9, 4}, {3, 4, 2}, {3, 2, 6}, {3, 6, 8},
69 {3, 8, 9}, {4, 9, 5}, {2, 4, 11}, {6, 2, 10}, {8, 6, 7}, {9, 8, 1},
70};
71
73struct Triangle {
74 std::int32_t a = 0;
75 std::int32_t b = 0;
76 std::int32_t c = 0;
77};
78
80[[nodiscard]] std::uint64_t edgeKey(std::int32_t i, std::int32_t j) noexcept {
81 const std::uint32_t low = static_cast<std::uint32_t>(i < j ? i : j);
82 const std::uint32_t high = static_cast<std::uint32_t>(i < j ? j : i);
83 return (static_cast<std::uint64_t>(high) << 32u) | low;
84}
85
87struct EdgeFaces {
88 std::int32_t first = -1;
89 std::int32_t second = -1;
90};
91
93[[nodiscard]] Result<HexSphereTopology> sphereFailure(const char* message) {
96}
97
98} // namespace
99
101 if (subdivision < 0 || subdivision > kMaxHexSphereSubdivision) {
102 return sphereFailure("hex sphere subdivision out of range");
103 }
104
106 topology.subdivision_ = subdivision;
107 topology.frequency_ = std::int32_t{1} << subdivision;
108
109 // --- primal polyhedron --------------------------------------------------
110 std::vector<Vec> vertices;
111 vertices.reserve(12u);
112 for (const auto& vertex : kIcosahedronVertices) vertices.push_back(normalize(Vec{vertex[0], vertex[1], vertex[2]}));
113
114 std::vector<Triangle> triangles;
115 triangles.reserve(20u);
116 for (const auto& face : kIcosahedronFaces) triangles.push_back(Triangle{face[0], face[1], face[2]});
117 for (Triangle& triangle : triangles) {
118 const Vec normal =
120 const Vec outward = vertices[triangle.a] + vertices[triangle.b] + vertices[triangle.c];
121 if (dot(normal, outward) < 0.f) std::swap(triangle.b, triangle.c);
122 }
123
124 // --- midpoint subdivision, frequency 2^subdivision -----------------------
125 //
126 // Splitting every triangle into four and welding the shared midpoints by edge
127 // key keeps one vertex per physical point, so vertex ids are stable and the
128 // original twelve keep their ids 0..11 -- which is what makes the twelve
129 // pentagons addressable as cells [0, 12).
130 for (std::int32_t level = 0; level < subdivision; ++level) {
131 std::unordered_map<std::uint64_t, std::int32_t> midpoints;
132 midpoints.reserve(vertices.size() * 2u);
133 std::vector<Triangle> refined;
134 refined.reserve(triangles.size() * 4u);
135
136 const auto midpoint = [&](std::int32_t i, std::int32_t j) {
137 const std::uint64_t key = edgeKey(i, j);
138 const auto found = midpoints.find(key);
139 if (found != midpoints.end()) return found->second;
140 const std::int32_t index = static_cast<std::int32_t>(vertices.size());
141 vertices.push_back(normalize(vertices[i] + vertices[j]));
142 midpoints.emplace(key, index);
143 return index;
144 };
145
146 for (const Triangle& triangle : triangles) {
147 const std::int32_t ab = midpoint(triangle.a, triangle.b);
148 const std::int32_t bc = midpoint(triangle.b, triangle.c);
149 const std::int32_t ca = midpoint(triangle.c, triangle.a);
150 refined.push_back(Triangle{triangle.a, ab, ca});
151 refined.push_back(Triangle{ab, triangle.b, bc});
152 refined.push_back(Triangle{ca, bc, triangle.c});
153 refined.push_back(Triangle{ab, bc, ca});
154 }
155 triangles.swap(refined);
156 }
157
158 const std::int32_t cellCount = static_cast<std::int32_t>(vertices.size());
159 topology.directions_ = std::move(vertices);
160
161 // --- dual corners: one per primal face ----------------------------------
162 std::vector<Vec> cornerDirections(triangles.size());
163 for (std::size_t i = 0; i < triangles.size(); ++i) {
164 const Triangle& triangle = triangles[i];
165 cornerDirections[i] = normalize(topology.directions_[triangle.a] + topology.directions_[triangle.b] +
166 topology.directions_[triangle.c]);
167 }
168
169 // --- vertex -> incident face incidence, in CSR form ----------------------
170 const std::int32_t faceCount = static_cast<std::int32_t>(triangles.size());
171 std::vector<std::int32_t> incidenceCount(static_cast<std::size_t>(cellCount), 0);
172 for (const Triangle& triangle : triangles) {
173 ++incidenceCount[triangle.a];
174 ++incidenceCount[triangle.b];
175 ++incidenceCount[triangle.c];
176 }
177 std::vector<std::int32_t> incidenceOffset(static_cast<std::size_t>(cellCount) + 1u, 0);
178 for (std::int32_t cell = 0; cell < cellCount; ++cell) {
179 incidenceOffset[cell + 1] = incidenceOffset[cell] + incidenceCount[cell];
180 }
181 std::vector<std::int32_t> incidence(static_cast<std::size_t>(incidenceOffset[cellCount]), -1);
182 {
183 std::vector<std::int32_t> cursor(incidenceOffset.begin(), incidenceOffset.end() - 1);
184 for (std::int32_t face = 0; face < faceCount; ++face) {
185 const Triangle& triangle = triangles[face];
186 incidence[cursor[triangle.a]++] = face;
187 incidence[cursor[triangle.b]++] = face;
188 incidence[cursor[triangle.c]++] = face;
189 }
190 }
191
192 // --- edge -> its one or two faces ---------------------------------------
193 std::unordered_map<std::uint64_t, EdgeFaces> edgeFaces;
194 edgeFaces.reserve(triangles.size() * 3u);
195 for (std::int32_t face = 0; face < faceCount; ++face) {
196 const Triangle& triangle = triangles[face];
197 const std::int32_t pairs[3][2] = {{triangle.a, triangle.b}, {triangle.b, triangle.c}, {triangle.c, triangle.a}};
198 for (const auto& pair : pairs) {
199 EdgeFaces& entry = edgeFaces[edgeKey(pair[0], pair[1])];
200 if (entry.first < 0)
201 entry.first = face;
202 else if (entry.second < 0)
203 entry.second = face;
204 }
205 }
206
207 const auto slotOf = [&](std::int32_t face, std::int32_t vertex) {
208 const Triangle& triangle = triangles[face];
209 if (triangle.a == vertex) return 0;
210 if (triangle.b == vertex) return 1;
211 return 2;
212 };
213 const auto vertexAt = [&](std::int32_t face, std::int32_t slot) {
214 const Triangle& triangle = triangles[face];
215 if (slot == 0) return triangle.a;
216 if (slot == 1) return triangle.b;
217 return triangle.c;
218 };
219 const auto nextVertexInFace = [&](std::int32_t face, std::int32_t vertex) {
220 return vertexAt(face, (slotOf(face, vertex) + 1) % 3);
221 };
222 const auto otherFaceOfEdge = [&](std::int32_t face, std::int32_t i, std::int32_t j) {
223 const auto found = edgeFaces.find(edgeKey(i, j));
224 if (found == edgeFaces.end()) return -1;
225 if (found->second.first == face) return found->second.second;
226 if (found->second.second == face) return found->second.first;
227 return -1;
228 };
229
230 // --- rotate around every vertex to get its cyclic corner and edge order ---
231 topology.cellOffsets_.assign(static_cast<std::size_t>(cellCount) + 1u, 0);
232 topology.neighbors_.assign(static_cast<std::size_t>(incidenceOffset[cellCount]), 0);
233 topology.corners_.assign(topology.neighbors_.size(), 0);
234
235 std::vector<std::int32_t> orderedFaces(6, -1);
236 for (std::int32_t cell = 0; cell < cellCount; ++cell) {
237 const std::int32_t begin = incidenceOffset[cell];
238 const std::int32_t degree = incidenceOffset[cell + 1] - begin;
239 if (degree < 5 || degree > 6) return sphereFailure("hex sphere cell has an unsupported edge count");
240 topology.cellOffsets_[cell] = begin;
241
242 const std::int32_t firstFace = incidence[begin];
243 std::int32_t current = firstFace;
244 for (std::int32_t direction = 0; direction < degree; ++direction) {
245 orderedFaces[direction] = current;
246 const std::int32_t nextFace = otherFaceOfEdge(current, cell, nextVertexInFace(current, cell));
247 if (nextFace < 0) return sphereFailure("hex sphere half-edge walk left the surface");
248 current = nextFace;
249 }
250 if (current != firstFace) return sphereFailure("hex sphere half-edge walk did not close");
251
252 for (std::int32_t direction = 0; direction < degree; ++direction) {
253 topology.corners_[begin + direction] = orderedFaces[direction];
254 topology.neighbors_[begin + direction] = nextVertexInFace(orderedFaces[direction], cell);
255 }
256 }
257 topology.cellOffsets_[cellCount] = static_cast<std::int32_t>(topology.neighbors_.size());
258 topology.cornerDirections_ = std::move(cornerDirections);
259
260 // --- handedness ---------------------------------------------------------
261 //
262 // Walking "the other face of the edge to the next vertex" is a uniform rule,
263 // so every cell comes out with the same handedness and the only question is
264 // which one. The shared edge of two adjacent cells must expose the same two
265 // corners from both sides, in reversed order; if it does not, reversing every
266 // cell's cyclic order flips the handedness of all of them at once.
267 const auto cornersAgree = [&topology]() {
268 for (std::int32_t cell = 0; cell < topology.cellCount(); ++cell) {
269 const std::int32_t degree = topology.neighborCount(cell);
270 for (std::int32_t direction = 0; direction < degree; ++direction) {
271 const HexSphereCell other = topology.neighbor(cell, direction);
272 const std::int32_t back = topology.directionOf(other, cell);
273 if (back < 0) return false;
274 const std::int32_t otherDegree = topology.neighborCount(other);
275 const std::int32_t here = topology.corners_[topology.cellOffsets_[cell] + direction];
276 const std::int32_t hereNext = topology.corners_[topology.cellOffsets_[cell] + (direction + 1) % degree];
277 const std::int32_t there = topology.corners_[topology.cellOffsets_[other] + back];
278 const std::int32_t thereNext =
279 topology.corners_[topology.cellOffsets_[other] + (back + 1) % otherDegree];
280 if (here != thereNext || hereNext != there) return false;
281 }
282 }
283 return true;
284 };
285
286 if (!cornersAgree()) {
287 for (std::int32_t cell = 0; cell < cellCount; ++cell) {
288 const auto begin = topology.neighbors_.begin() + topology.cellOffsets_[cell];
289 const auto end = topology.neighbors_.begin() + topology.cellOffsets_[cell + 1];
290 const auto cornerBegin = topology.corners_.begin() + topology.cellOffsets_[cell];
291 const auto cornerEnd = topology.corners_.begin() + topology.cellOffsets_[cell + 1];
292 std::reverse(begin, end);
293 std::reverse(cornerBegin, cornerEnd);
294 }
295 if (!cornersAgree()) return sphereFailure("hex sphere winding is inconsistent");
296 }
297
298 // --- Euler characteristic ------------------------------------------------
299 if (topology.cellCount() - topology.edgeCount() + topology.cornerCount() != 2) {
300 return sphereFailure("hex sphere does not close into a sphere");
301 }
302
304}
305
306std::int32_t HexSphereTopology::neighborCount(HexSphereCell cell) const noexcept {
307 if (!contains(cell)) return 0;
308 return cellOffsets_[static_cast<std::size_t>(cell) + 1u] - cellOffsets_[static_cast<std::size_t>(cell)];
309}
310
311HexSphereCell HexSphereTopology::neighbor(HexSphereCell cell, std::int32_t direction) const noexcept {
312 if (direction < 0 || direction >= neighborCount(cell)) return kNoHexSphereCell;
313 return neighbors_[static_cast<std::size_t>(cellOffsets_[static_cast<std::size_t>(cell)] + direction)];
314}
315
316std::int32_t HexSphereTopology::directionOf(HexSphereCell cell, HexSphereCell other) const noexcept {
317 if (!contains(cell) || !contains(other)) return kNoHexSphereCell;
318 const std::int32_t begin = cellOffsets_[static_cast<std::size_t>(cell)];
319 const std::int32_t degree = neighborCount(cell);
320 for (std::int32_t direction = 0; direction < degree; ++direction) {
321 if (neighbors_[static_cast<std::size_t>(begin + direction)] == other) return direction;
322 }
323 return kNoHexSphereCell;
324}
325
326std::int32_t HexSphereTopology::oppositeDirection(HexSphereCell cell, std::int32_t direction) const noexcept {
327 const HexSphereCell other = neighbor(cell, direction);
328 if (other == kNoHexSphereCell) return kNoHexSphereCell;
329 return directionOf(other, cell);
330}
331
332HexVec3 HexSphereTopology::direction(HexSphereCell cell) const noexcept {
333 if (!contains(cell)) return HexVec3{0.f, 1.f, 0.f};
334 return directions_[static_cast<std::size_t>(cell)];
335}
336
337std::int32_t HexSphereTopology::cornerCountOf(HexSphereCell cell) const noexcept { return neighborCount(cell); }
338
339HexVec3 HexSphereTopology::corner(HexSphereCell cell, std::int32_t cornerIndex) const noexcept {
340 if (cornerIndex < 0 || cornerIndex >= neighborCount(cell)) return HexVec3{0.f, 1.f, 0.f};
341 const std::int32_t id =
342 corners_[static_cast<std::size_t>(cellOffsets_[static_cast<std::size_t>(cell)] + cornerIndex)];
343 if (id < 0 || id >= cornerCount()) return HexVec3{0.f, 1.f, 0.f};
344 return cornerDirections_[static_cast<std::size_t>(id)];
345}
346
347HexSphereCell HexSphereTopology::cellAt(HexVec3 unitDirection) const noexcept {
348 if (empty()) return kNoHexSphereCell;
349 const Vec target = normalize(unitDirection);
350
352 float best = dot(directions_[0], target);
353 const std::int32_t seeds = cellCount() < 12 ? cellCount() : 12;
354 for (std::int32_t cell = 1; cell < seeds; ++cell) {
355 const float score = dot(directions_[static_cast<std::size_t>(cell)], target);
356 if (score > best) {
357 best = score;
358 current = cell;
359 }
360 }
361
362 for (;;) {
363 bool improved = false;
364 const std::int32_t degree = neighborCount(current);
365 for (std::int32_t direction = 0; direction < degree; ++direction) {
366 const HexSphereCell candidate =
367 neighbors_[static_cast<std::size_t>(cellOffsets_[static_cast<std::size_t>(current)] + direction)];
368 const float score = dot(directions_[static_cast<std::size_t>(candidate)], target);
369 if (score > best + 1e-7f) {
370 best = score;
371 current = candidate;
372 improved = true;
373 }
374 }
375 if (!improved) break;
376 }
377 return current;
378}
379
380float HexSphereTopology::angularDistance(HexVec3 a, HexVec3 b) noexcept {
381 const float cosine = dot(normalize(a), normalize(b));
382 return std::acos(std::clamp(cosine, -1.f, 1.f));
383}
384
385} // namespace eve::hexmap
386
387// HexTerrainBake.cpp
394namespace eve::hexmap {
395namespace {
396
397[[nodiscard]] [[nodiscard]] Result<HexTerrainBake> invalidBake(std::string message) {
400}
401
402void writeU32LE(unsigned char* bytes, std::uint32_t value) noexcept {
403 bytes[0] = static_cast<unsigned char>(value & 0xffu);
404 bytes[1] = static_cast<unsigned char>((value >> 8) & 0xffu);
405 bytes[2] = static_cast<unsigned char>((value >> 16) & 0xffu);
406 bytes[3] = static_cast<unsigned char>((value >> 24) & 0xffu);
407}
408
409[[nodiscard]] std::uint32_t readU32LE(const unsigned char* bytes) noexcept {
410 return static_cast<std::uint32_t>(bytes[0]) | (static_cast<std::uint32_t>(bytes[1]) << 8) |
411 (static_cast<std::uint32_t>(bytes[2]) << 16) | (static_cast<std::uint32_t>(bytes[3]) << 24);
412}
413
414[[nodiscard]] std::string packCells(const std::vector<HexCellData>& cells) {
415 std::string packed(cells.size() * 8u, '\0');
416 auto* bytes = reinterpret_cast<unsigned char*>(packed.data());
417 for (std::size_t i = 0; i < cells.size(); ++i) {
418 writeU32LE(bytes + i * 8u, cells[i].values.raw());
419 writeU32LE(bytes + i * 8u + 4u, cells[i].flags.raw());
420 }
421 return packed;
422}
423
424[[nodiscard]] Result<std::vector<HexCellData>> unpackCells(std::string_view packed, std::size_t expected) {
425 if (packed.size() != expected * 8u)
426 return Result<std::vector<HexCellData>>::failure(
428 "hex terrain bake cell payload length does not match the cell count", "hexmap"));
429 std::vector<HexCellData> cells(expected);
430 const auto* bytes = reinterpret_cast<const unsigned char*>(packed.data());
431 for (std::size_t i = 0; i < expected; ++i) {
432 cells[i].values = HexValues{readU32LE(bytes + i * 8u)};
433 cells[i].flags = HexFlags{readU32LE(bytes + i * 8u + 4u)};
434 }
435 return Result<std::vector<HexCellData>>::success(std::move(cells));
436}
437
438[[nodiscard]] Result<std::int32_t> readInt32(const Value& object, const char* key) {
439 const Value* field = object.find(key);
440 if (field == nullptr || !field->isNumeric())
443 std::string("hex terrain bake is missing numeric '") + key + "'", "hexmap"));
444 if (field->isInt64()) return Result<std::int32_t>::success(static_cast<std::int32_t>(field->asInt()));
445 return Result<std::int32_t>::success(static_cast<std::int32_t>(field->asDouble()));
446}
447
448[[nodiscard]] Result<std::uint32_t> readUInt32(const Value& object, const char* key) {
449 auto parsed = readInt32(object, key);
450 if (!parsed) return Result<std::uint32_t>::failure(parsed.status());
451 if (parsed.value() < 0)
454 std::string("hex terrain bake '") + key + "' must not be negative", "hexmap"));
455 return Result<std::uint32_t>::success(static_cast<std::uint32_t>(parsed.value()));
456}
457
458} // namespace
459
461 HexTerrainBake bake;
463 bake.cellCountX = map.cellCountX();
464 bake.cellCountZ = map.cellCountZ();
465 bake.cellCount = map.cellCount();
466 bake.seed = map.seed();
467 bake.cells.resize(static_cast<std::size_t>(bake.cellCount));
468 for (std::int32_t index = 0; index < bake.cellCount; ++index) {
469 const HexCellData* cell = map.cellAt(index);
470 if (cell != nullptr) bake.cells[static_cast<std::size_t>(index)] = *cell;
471 }
472 return bake;
473}
474
476 HexTerrainBake bake;
478 bake.cellCount = map.cellCount();
479 bake.subdivision = map.subdivision();
480 bake.radius = map.sphereRadius();
481 bake.seed = map.seed();
482 bake.cells.resize(static_cast<std::size_t>(bake.cellCount));
483 for (std::int32_t cell = 0; cell < bake.cellCount; ++cell) {
484 const HexCellData* record = map.cellAt(cell);
485 if (record != nullptr) bake.cells[static_cast<std::size_t>(cell)] = *record;
486 }
487 return bake;
488}
489
493 payload.set("kind", Value("hex.sphere"));
494 payload.set("subdivision", Value(static_cast<std::int64_t>(bake.subdivision)));
495 payload.set("radius", Value(static_cast<double>(bake.radius)));
496 payload.set("cellCount", Value(static_cast<std::int64_t>(bake.cellCount)));
497 } else {
498 payload.set("kind", Value("hex.terrain"));
499 payload.set("cellCountX", Value(static_cast<std::int64_t>(bake.cellCountX)));
500 payload.set("cellCountZ", Value(static_cast<std::int64_t>(bake.cellCountZ)));
501 }
502 payload.set("seed", Value(static_cast<std::int64_t>(bake.seed)));
503 payload.set("cells", Value(packCells(bake.cells)));
504 return payload;
505}
506
508 if (!value.isObject()) return invalidBake("hex terrain bake must be an object");
509 const Value* kindField = value.find("kind");
510 if (kindField == nullptr || !kindField->isString()) return invalidBake("hex terrain bake is missing string 'kind'");
511 const std::string& kind = kindField->asString();
512
513 HexTerrainBake bake;
514 if (kind == "hex.sphere") {
516 auto subdivision = readInt32(value, "subdivision");
517 if (!subdivision) return Result<HexTerrainBake>::failure(subdivision.status());
518 bake.subdivision = subdivision.value();
519 const Value* radiusField = value.find("radius");
520 if (radiusField == nullptr || !radiusField->isNumeric())
521 return invalidBake("hex sphere bake is missing numeric 'radius'");
522 bake.radius = radiusField->isDouble() ? static_cast<float>(radiusField->asDouble())
523 : static_cast<float>(radiusField->asInt());
524 auto cellCount = readInt32(value, "cellCount");
525 if (!cellCount) return Result<HexTerrainBake>::failure(cellCount.status());
526 bake.cellCount = cellCount.value();
527 } else if (kind == "hex.terrain") {
529 auto cellCountX = readInt32(value, "cellCountX");
530 auto cellCountZ = readInt32(value, "cellCountZ");
531 if (!cellCountX) return Result<HexTerrainBake>::failure(cellCountX.status());
532 if (!cellCountZ) return Result<HexTerrainBake>::failure(cellCountZ.status());
533 bake.cellCountX = cellCountX.value();
534 bake.cellCountZ = cellCountZ.value();
535 bake.cellCount = bake.cellCountX * bake.cellCountZ;
536 } else {
537 return invalidBake("hex terrain bake kind must be 'hex.terrain' or 'hex.sphere'");
538 }
539
540 auto seed = readUInt32(value, "seed");
541 if (!seed) return Result<HexTerrainBake>::failure(seed.status());
542 bake.seed = seed.value();
543
544 const Value* cellsField = value.find("cells");
545 if (cellsField == nullptr || !cellsField->isString())
546 return invalidBake("hex terrain bake is missing packed 'cells'");
547 if (bake.cellCount < 0) return invalidBake("hex terrain bake cell count must not be negative");
548 auto cells = unpackCells(cellsField->asString(), static_cast<std::size_t>(bake.cellCount));
549 if (!cells) return Result<HexTerrainBake>::failure(cells.status());
550 bake.cells = std::move(cells).takeValue();
551 return Result<HexTerrainBake>::success(std::move(bake));
552}
553
557 Diagnostic::error(DiagnosticCode::InvalidArgument, "applyHexTerrain requires a planar bake", "hexmap"));
558 if (bake.cellCountX <= 0 || bake.cellCountZ <= 0)
560 Diagnostic::error(DiagnosticCode::InvalidArgument, "planar bake size must be positive", "hexmap"));
561 if (static_cast<std::int32_t>(bake.cells.size()) != bake.cellCountX * bake.cellCountZ)
563 DiagnosticCode::InvalidArgument, "planar bake cell count does not match width and height", "hexmap"));
564
565 auto reset = map.reset(bake.cellCountX, bake.cellCountZ, bake.seed);
566 if (!reset) return reset;
567 for (std::int32_t index = 0; index < map.cellCount(); ++index) {
568 const HexCellData& cell = bake.cells[static_cast<std::size_t>(index)];
569 auto written = map.setCellState(map.coordinatesAt(index), cell.values, cell.flags);
570 if (!written) return written;
571 }
572 map.markAllChunksDirty();
573 return Result<void>::success();
574}
575
579 "applyHexSphereTerrain requires a sphere bake", "hexmap"));
580 if (map.empty())
582 DiagnosticCode::InvalidArgument, "applyHexSphereTerrain requires an existing sphere topology", "hexmap"));
583 if (bake.cellCount <= 0 || static_cast<std::int32_t>(bake.cells.size()) != bake.cellCount)
585 Diagnostic::error(DiagnosticCode::InvalidArgument, "sphere bake cell count is inconsistent", "hexmap"));
586 if (map.cellCount() != bake.cellCount || map.subdivision() != bake.subdivision)
589 "sphere bake does not match the live topology; call newSphere with the same subdivision", "hexmap"));
590
591 for (std::int32_t cell = 0; cell < bake.cellCount; ++cell) {
592 const HexCellData& record = bake.cells[static_cast<std::size_t>(cell)];
593 auto written = map.setCellState(cell, record.values, record.flags);
594 if (!written) return written;
595 }
596 map.markAllDirty();
597 return Result<void>::success();
598}
599
600} // namespace eve::hexmap
601
602// HexWaterMesh.cpp
603namespace eve::hexmap {
604namespace {
605
607struct SurfaceVertex {
608 HexVec3 position;
609 float u = 0.f;
610 float v = 0.f;
611};
612
619[[nodiscard]] bool isDegenerate(HexVec3 a, HexVec3 b, HexVec3 c) noexcept {
620 const HexVec3 ab = b - a;
621 const HexVec3 ac = c - a;
622 const HexVec3 normal{ab.y * ac.z - ab.z * ac.y, ab.z * ac.x - ab.x * ac.z, ab.x * ac.y - ab.y * ac.x};
623 return (normal.x * normal.x + normal.y * normal.y + normal.z * normal.z) <= 1e-8f;
624}
625
636void emitTriangle(HexMeshData& out, const SurfaceVertex& a, const SurfaceVertex& b, const SurfaceVertex& c,
637 const HexNoise& noise) {
638 const HexVec3 pa = noise.perturb(a.position);
639 const HexVec3 pb = noise.perturb(b.position);
640 const HexVec3 pc = noise.perturb(c.position);
641 if (isDegenerate(pa, pb, pc)) return;
642 out.addTriangle(out.addVertex(pa, a.u, a.v), out.addVertex(pb, b.u, b.v), out.addVertex(pc, c.u, c.v));
643}
644
653void emitQuad(HexMeshData& out, const SurfaceVertex& r0, const SurfaceVertex& r1, const SurfaceVertex& r2,
654 const SurfaceVertex& r3, const HexNoise& noise) {
655 emitTriangle(out, r0, r3, r1, noise);
656 emitTriangle(out, r1, r3, r2, noise);
657}
658
660[[nodiscard]] float waterHeightOf(const HexMap& map, HexCoordinates coordinates, float offGridHeight) noexcept {
661 return map.contains(coordinates) ? HexMetrics::waterSurfaceY(map.waterLevel(coordinates)) : offGridHeight;
662}
663
670[[nodiscard]] bool isWater(const HexMap& map, HexCoordinates coordinates) noexcept {
671 return map.contains(coordinates) && map.isUnderwater(coordinates);
672}
673
689void appendOpenWater(const HexMap& map, HexCoordinates coordinates, HexDirection direction, HexVec3 centre,
690 const HexNoise& noise, HexMeshData& out) {
691 const SurfaceVertex c1{centre + HexMetrics::firstWaterCorner(direction), 0.f, 0.f};
692 const SurfaceVertex c2{centre + HexMetrics::secondWaterCorner(direction), 0.f, 0.f};
693 emitTriangle(out, SurfaceVertex{centre, 0.f, 0.f}, c1, c2, noise);
694
695 HexCoordinates neighbour{};
696 if (static_cast<std::int32_t>(direction) > static_cast<std::int32_t>(HexDirection::SE) ||
697 !map.getNeighbor(coordinates, direction, neighbour)) {
698 // Only the NE, E and SE edges bridge outward: for a water/water boundary the
699 // other side would emit the same quad, so exactly one chunk owns it. An
700 // off-grid neighbour has nothing to bridge to.
701 return;
702 }
703
705 const float farY = waterHeightOf(map, neighbour, centre.y);
706 const SurfaceVertex e1{{c1.position.x + offset.x, farY, c1.position.z + offset.z}, 0.f, 0.f};
707 const SurfaceVertex e2{{c2.position.x + offset.x, farY, c2.position.z + offset.z}, 0.f, 0.f};
708 emitQuad(out, c1, c2, e2, e1, noise);
709
710 if (static_cast<std::int32_t>(direction) > static_cast<std::int32_t>(HexDirection::E)) return;
711 HexCoordinates nextNeighbour{};
712 if (!map.getNeighbor(coordinates, next(direction), nextNeighbour) || !isWater(map, nextNeighbour)) return;
713
714 // The third cell of the junction is water too, so its own wedge stops at the
715 // water corner and this triangle fills the gap between the two bridges.
716 HexVec3 corner = map.cellGroundPosition(nextNeighbour) + HexMetrics::firstWaterCorner(previous(direction));
717 corner.y = farY;
718 emitTriangle(out, c2, e2, SurfaceVertex{corner, 0.f, 0.f}, noise);
719}
720
742void appendWaterShore(const HexMap& map, HexCoordinates coordinates, HexDirection direction, HexVec3 centre,
743 const HexNoise& noise, HexMeshData& out) {
744 const EdgeVertices near{centre + HexMetrics::firstWaterCorner(direction),
746
747 const SurfaceVertex nearSamples[5] = {SurfaceVertex{near.v1, 0.f, 0.f}, SurfaceVertex{near.v2, 0.f, 0.f},
748 SurfaceVertex{near.v3, 0.f, 0.f}, SurfaceVertex{near.v4, 0.f, 0.f},
749 SurfaceVertex{near.v5, 0.f, 0.f}};
750 const SurfaceVertex wedgeCentre{centre, 0.f, 0.f};
751 for (std::int32_t i = 0; i < 4; ++i) {
752 emitTriangle(out, wedgeCentre, nearSamples[i], nearSamples[i + 1], noise);
753 }
754
755 const HexCoordinates neighbour = coordinates.step(direction);
756 const HexVec3 neighbourGround = map.cellGroundPosition(neighbour);
757 const HexVec3 bank{neighbourGround.x, centre.y, neighbourGround.z};
758 // Second corner first, so sample `i` of the far edge lines up with sample `i` of
759 // the near edge across the strip - the reference orders them the same way.
760 const EdgeVertices far{bank + HexMetrics::secondSolidCorner(opposite(direction)),
762
763 const SurfaceVertex farSamples[5] = {SurfaceVertex{far.v1, 1.f, 0.f}, SurfaceVertex{far.v2, 1.f, 0.f},
764 SurfaceVertex{far.v3, 1.f, 0.f}, SurfaceVertex{far.v4, 1.f, 0.f},
765 SurfaceVertex{far.v5, 1.f, 0.f}};
766 for (std::int32_t i = 0; i < 4; ++i) {
767 emitQuad(out, nearSamples[i], nearSamples[i + 1], farSamples[i + 1], farSamples[i], noise);
768 }
769
770 // Close the junction with the next cell around: its water edge when it is flooded,
771 // its bank corner when it is land. Either way the vertex stays at the water height.
772 HexCoordinates nextNeighbour{};
773 if (!map.getNeighbor(coordinates, next(direction), nextNeighbour)) return;
774 const HexVec3 corner =
775 isWater(map, nextNeighbour)
776 ? map.cellGroundPosition(nextNeighbour) + HexMetrics::firstWaterCorner(previous(direction))
777 : map.cellGroundPosition(nextNeighbour) + HexMetrics::firstSolidCorner(previous(direction));
778 HexVec3 capped = corner;
779 capped.y = centre.y;
780 emitTriangle(out, nearSamples[4], farSamples[4], SurfaceVertex{capped, 0.f, 0.f}, noise);
781}
782
783} // namespace
784
785void buildWaterMesh(const HexMap& map, std::int32_t chunkIndex, HexMeshData& out) {
786 out.clear();
787 if (chunkIndex < 0 || chunkIndex >= map.chunkCount()) {
788 out.finalize();
789 return;
790 }
791
792 const HexNoise& noise = map.noise();
793
794 for (std::int32_t row = 0; row < HexMetrics::kChunkSizeZ; ++row) {
795 for (std::int32_t column = 0; column < HexMetrics::kChunkSizeX; ++column) {
796 const HexCoordinates coordinates = map.chunkCell(chunkIndex, column, row);
797 if (map.cell(coordinates) == nullptr || !map.isUnderwater(coordinates)) continue;
798
799 const HexVec3 ground = map.cellGroundPosition(coordinates);
800 const HexVec3 centre{ground.x, HexMetrics::waterSurfaceY(map.waterLevel(coordinates)), ground.z};
801
802 // Dispatch per direction, exactly like the reference: a flooded direction
803 // gets the open-water wedge, a land direction gets the shore wedge and its
804 // strip. Emitting a full-cell fan up front instead would double the centre
805 // triangles of every shoreline direction and leave the strip to fight it.
806 for (std::int32_t i = 0; i < kHexDirectionCount; ++i) {
807 const auto direction = static_cast<HexDirection>(i);
808 HexCoordinates neighbour{};
809 const bool hasNeighbour = map.getNeighbor(coordinates, direction, neighbour);
810 const bool neighbourWater = hasNeighbour && isWater(map, neighbour);
811 if (hasNeighbour && !neighbourWater) {
812 appendWaterShore(map, coordinates, direction, centre, noise, out);
813 } else {
814 appendOpenWater(map, coordinates, direction, centre, noise, out);
815 }
816 }
817 }
818 }
819
820 out.finalize();
821}
822
823} // namespace eve::hexmap
LogicalId target
Value::Object payload
double score
Definition Agent.cpp:51
std::size_t cursor
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
int triangle
Definition FluidSdf.cpp:554
std::string message
float u
Definition Grass.cpp:233
std::uint32_t ab
std::uint32_t ac
Per-chunk mesh generation for every hex map surface.
CPU vertex/index container shared by the hex surface builders.
Pointy-top hex metrics, directions and vertex helpers.
Deterministic asset-free noise for hex perturbation and generation.
float v
std::int32_t second
std::int32_t c
std::int32_t first
Icosahedral hex topology: twelve pentagons and hexagons on a sphere.
Terrain bake hexmap applies; procgen produces the payload.
float length
size_t offset
std::array< float, 3 > position
std::string id
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
Texture * normal
int level
std::shared_ptr< const OceanSprayFrame > previous
Topology topology
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::set< std::string > values
Object::Ptr value
std::string slot
Heightmap ground
RoadLaneDirection direction
bool found
ScriptStructure out
size_t begin
std::map< size_t, size_t > pairs
unsigned column
size_t end
std::string kind
double current
Cell cell
std::map< Cell, int > best
std::array< double, 2 > vertices[3]
uint32_t seed
Definition TreeMesh.cpp:276
uint32_t index
int neighbor
uint32_t flags
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
bool isNumeric() const noexcept
Return whether this value is an integer or finite number.
Definition Value.h:188
double asDouble() const
Return the Double payload; the caller must have checked the kind.
Definition Value.cpp:195
void set(const std::string &key, Value value)
Insert or replace an object member.
Definition Value.cpp:238
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
std::int64_t asInt() const
Return the Int64 payload; the caller must have checked the kind.
Definition Value.cpp:189
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
bool isDouble() const noexcept
Return true when this value is a Double.
Definition Value.h:104
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
An editable, chunked, pointy-top hex map.
Definition HexMap.h:72
std::int32_t chunkCount() const noexcept
Total number of chunks.
Definition HexMap.h:102
std::int32_t waterLevel(HexCoordinates c) const noexcept
Definition HexMap.cpp:304
HexCoordinates coordinatesAt(std::int32_t index) const noexcept
Coordinates of a linear cell index; out-of-range indices return (0, 0).
Definition HexMap.cpp:69
std::uint32_t seed() const noexcept
The seed this map was built with.
Definition HexMap.h:106
std::int32_t cellCountX() const noexcept
Number of columns.
Definition HexMap.h:94
void markAllChunksDirty() noexcept
Marks every chunk dirty.
Definition HexMap.cpp:152
Result< void > setCellState(HexCoordinates c, HexValues values, HexFlags flags)
Writes a complete cell record verbatim.
Definition HexMap.cpp:505
const HexNoise & noise() const noexcept
Deterministic noise field shared by this map's mesh builders.
Definition HexMap.h:110
std::int32_t cellCount() const noexcept
Total number of cells.
Definition HexMap.h:104
bool getNeighbor(HexCoordinates coordinates, HexDirection direction, HexCoordinates &out) const noexcept
Neighbour of coordinates in direction; false when it is off-grid.
Definition HexMap.cpp:87
bool isUnderwater(HexCoordinates c) const noexcept
Definition HexMap.cpp:328
Result< void > reset(std::int32_t cellCountX, std::int32_t cellCountZ, std::uint32_t seed)
Replaces the grid with a new cellCountX * cellCountZ map.
Definition HexMap.cpp:37
std::int32_t cellCountZ() const noexcept
Number of rows.
Definition HexMap.h:96
const HexCellData * cell(HexCoordinates coordinates) const noexcept
Cell record, or null when outside the grid. @ownership Borrowed; the map owns the record....
Definition HexMap.cpp:79
const HexCellData * cellAt(std::int32_t index) const noexcept
Cell record by linear index, or null when out of range. @ownership Borrowed; the map owns the record....
Definition HexMap.cpp:74
HexVec3 cellGroundPosition(HexCoordinates coordinates) const noexcept
Cell centre at y = 0 (no elevation, no perturbation).
Definition HexMap.h:198
HexCoordinates chunkCell(std::int32_t chunkIndex, std::int32_t column, std::int32_t row) const noexcept
Coordinates of the cell at (column, row) inside a chunk.
Definition HexMap.cpp:115
CPU-side triangle soup for one hex chunk surface.
Definition HexMeshData.h:24
static HexVec3 firstSolidCorner(HexDirection d) noexcept
First solid corner of direction.
Definition HexMetrics.h:202
static HexVec3 secondSolidCorner(HexDirection d) noexcept
Second solid corner of direction.
Definition HexMetrics.h:204
static HexVec3 secondWaterCorner(HexDirection d) noexcept
Second water corner of direction.
Definition HexMetrics.h:212
static float waterSurfaceY(int waterLevel) noexcept
Y coordinate of a water surface at waterLevel.
Definition HexMetrics.h:273
static HexVec3 firstWaterCorner(HexDirection d) noexcept
First water corner of direction.
Definition HexMetrics.h:210
static HexVec3 waterBridge(HexDirection d) noexcept
Bridge vector from the water edge of direction to the neighbour.
Definition HexMetrics.h:218
static constexpr int kChunkSizeZ
Chunk size in the Z dimension.
Definition HexMetrics.h:158
static constexpr int kChunkSizeX
Chunk size in the X dimension.
Definition HexMetrics.h:156
Deterministic four-channel value noise over the XZ plane.
Definition HexNoise.h:23
An editable hex map wrapped onto a sphere.
std::int32_t subdivision() const noexcept
The subdivision level this map was built at.
std::uint32_t seed() const noexcept
The seed this map was built with.
void markAllDirty() noexcept
Marks every cell dirty.
bool empty() const noexcept
Whether the map holds any cell.
float sphereRadius() const noexcept
Sphere radius in world units.
const HexCellData * cellAt(HexSphereCell cell) const noexcept
Cell record by id, or null when out of range. @ownership Borrowed; the map owns the record....
std::int32_t cellCount() const noexcept
Number of cells (10 * f^2 + 2).
Result< void > setCellState(HexSphereCell c, HexValues values, HexFlags flags)
Writes a complete cell record verbatim.
Icosahedral (Goldberg) hex topology for a spherical hex map.
std::int32_t subdivision() const noexcept
The subdivision level this topology was built at.
static Result< HexSphereTopology > build(std::int32_t subdivision)
Builds the topology of one subdivision level.
double asDouble(double fallback=0.0) const
As double.
Definition Json.cpp:378
int asInt(int fallback=0) const
As int.
Definition Json.cpp:393
bool isInt64() const
True when the JSON number was an integer literal that fits Int64.
Definition Json.cpp:329
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
HexTerrainBake snapshotHexSphereTerrain(const HexSphereMap &map)
Snapshot every cell of a spherical map into a bake.
constexpr HexDirection opposite(HexDirection d) noexcept
The direction opposite to d.
Definition HexMetrics.h:65
Result< void > applyHexTerrain(HexMap &map, const HexTerrainBake &bake)
Replace a planar map's cells with a bake.
Result< HexTerrainBake > hexTerrainBakeFromValue(const Value &value)
Parse a script bake payload produced by hexTerrainBakeToValue.
HexTerrainBake snapshotHexTerrain(const HexMap &map)
Snapshot every cell of a planar map into a bake.
constexpr std::int32_t kHexDirectionCount
Number of hex edges / facing directions.
Definition HexMetrics.h:62
constexpr std::int32_t kMaxHexSphereSubdivision
Largest supported subdivision level; 10 * 4^7 + 2 = 163842 cells.
EVENGINE_API_WORLD void buildWaterMesh(const HexMap &map, std::int32_t chunkIndex, HexMeshData &out)
Builds the water surface and shore band of one chunk.
constexpr HexSphereCell kNoHexSphereCell
Returned by a spherical cell query that has no answer.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Result< void > applyHexSphereTerrain(HexSphereMap &map, const HexTerrainBake &bake)
Replace a spherical map's cells with a bake.
std::int32_t HexSphereCell
Dense identifier of one cell of a spherical hex topology.
HexDirection
Hex facing directions, counter-clockwise from north-east.
Definition HexMetrics.h:59
Value hexTerrainBakeToValue(const HexTerrainBake &bake)
Project a bake into the script Result payload.
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
V3 normalize(V3 a)
Module-private road bake implementation helper.
Definition RoadBake.cpp:31
One cell of the hex map: packed values plus packed flags.
Definition HexCell.h:244
Axial coordinates of one hex cell.
Packed terrain produced by a generator and applied onto a hex map.
std::vector< HexCellData > cells
Minimal 3-component float vector used by the hex mesh builders.
Definition HexMetrics.h:18