载入中...
搜索中...
未找到
Fov.cpp
浏览该文件的文档.
1#include "map/Fov.h"
2#include "common/Profile.h"
3
4#include "graphics/Graphics.h"
5#include "graphics/Texture.h"
7
8#include <algorithm>
9#include <cmath>
10#include <cstdint>
11#include <string>
12#include <unordered_map>
13#include <unordered_set>
14#include <utility>
15#include <vector>
16
17namespace eve::map {
18namespace {
19
20constexpr float kPi = 3.14159265358979323846f;
21constexpr float kExploredMask = 0.35f;
22
23enum class Algorithm : uint8_t { Shadowcast, Raycast, Permissive, Rectangle };
24enum class RadiusMetric : uint8_t { Euclidean, Chebyshev, Manhattan };
25enum class Mode : uint8_t { Grid2D, Heightmap, Volume };
26enum class Topology : uint8_t { Ortho, Hex };
27enum class CellState : uint8_t { Unknown = 0, Explored = 1, Visible = 2 };
28
29Algorithm parseAlgorithm(const std::string &name, Algorithm fallback) {
30 if (name == "shadowcast") return Algorithm::Shadowcast;
31 if (name == "raycast") return Algorithm::Raycast;
32 if (name == "permissive") return Algorithm::Permissive;
33 if (name == "rectangle") return Algorithm::Rectangle;
34 return fallback;
35}
36
37std::string algorithmName(Algorithm a) {
38 switch (a) {
39 case Algorithm::Raycast:
40 return "raycast";
41 case Algorithm::Permissive:
42 return "permissive";
43 case Algorithm::Rectangle:
44 return "rectangle";
45 case Algorithm::Shadowcast:
46 default:
47 return "shadowcast";
48 }
49}
50
51Mode parseMode(const std::string &name, Mode fallback) {
52 if (name == "grid2d") return Mode::Grid2D;
53 if (name == "heightmap") return Mode::Heightmap;
54 if (name == "volume") return Mode::Volume;
55 return fallback;
56}
57
58std::string modeName(Mode m) {
59 switch (m) {
60 case Mode::Heightmap:
61 return "heightmap";
62 case Mode::Volume:
63 return "volume";
64 case Mode::Grid2D:
65 default:
66 return "grid2d";
67 }
68}
69
70RadiusMetric parseMetric(const std::string &name, RadiusMetric fallback) {
71 if (name == "euclidean") return RadiusMetric::Euclidean;
72 if (name == "chebyshev") return RadiusMetric::Chebyshev;
73 if (name == "manhattan") return RadiusMetric::Manhattan;
74 return fallback;
75}
76
77std::string metricName(RadiusMetric m) {
78 switch (m) {
79 case RadiusMetric::Euclidean:
80 return "euclidean";
81 case RadiusMetric::Chebyshev:
82 return "chebyshev";
83 case RadiusMetric::Manhattan:
84 return "manhattan";
85 }
86 return "euclidean";
87}
88
89std::string topologyName(Topology t) { return t == Topology::Hex ? "hex" : "ortho"; }
90
91void offsetToCube(int x, int y, int &q, int &r, int &s) {
92 // odd-r staggered (matches Pathfinder hex)
93 q = x - (y - (y & 1)) / 2;
94 r = y;
95 s = -q - r;
96}
97
98void cubeToOffset(int q, int r, int &x, int &y) {
99 y = r;
100 x = q + (r - (r & 1)) / 2;
101}
102
103int cubeDistance(int q0, int r0, int s0, int q1, int r1, int s1) {
104 return std::max({std::abs(q0 - q1), std::abs(r0 - r1), std::abs(s0 - s1)});
105}
106
107int hexDistance(int x0, int y0, int x1, int y1) {
108 int q0, r0, s0, q1, r1, s1;
109 offsetToCube(x0, y0, q0, r0, s0);
110 offsetToCube(x1, y1, q1, r1, s1);
111 return cubeDistance(q0, r0, s0, q1, r1, s1);
112}
113
114bool inRadiusOrtho(RadiusMetric metric, int dx, int dy, int radius) {
115 if (radius < 0) return false;
116 const int adx = std::abs(dx);
117 const int ady = std::abs(dy);
118 switch (metric) {
119 case RadiusMetric::Chebyshev:
120 return std::max(adx, ady) <= radius;
121 case RadiusMetric::Manhattan:
122 return adx + ady <= radius;
123 case RadiusMetric::Euclidean:
124 default:
125 return adx * adx + ady * ady <= radius * radius;
126 }
127}
128
129bool inRadius3Ortho(RadiusMetric metric, int dx, int dy, int dz, int radius) {
130 if (radius < 0) return false;
131 const int adx = std::abs(dx);
132 const int ady = std::abs(dy);
133 const int adz = std::abs(dz);
134 switch (metric) {
135 case RadiusMetric::Chebyshev:
136 return std::max({adx, ady, adz}) <= radius;
137 case RadiusMetric::Manhattan:
138 return adx + ady + adz <= radius;
139 case RadiusMetric::Euclidean:
140 default:
141 return adx * adx + ady * ady + adz * adz <= radius * radius;
142 }
143}
144
145float angleDiffDeg(float a, float b) {
146 float d = a - b;
147 while (d > 180.f) d -= 360.f;
148 while (d < -180.f) d += 360.f;
149 return d;
150}
151
152bool inCone(int ox, int oy, int x, int y, bool useCone, float facingDeg, float halfAngleDeg) {
153 if (!useCone || halfAngleDeg >= 180.f) return true;
154 if (x == ox && y == oy) return true;
155 const float ang = std::atan2(float(y - oy), float(x - ox)) * (180.f / kPi);
156 return std::fabs(angleDiffDeg(ang, facingDeg)) <= halfAngleDeg;
157}
158
159uint8_t stateToMaskByte(CellState s) {
160 switch (s) {
161 case CellState::Visible:
162 return 255;
163 case CellState::Explored:
164 return uint8_t(kExploredMask * 255.f + 0.5f);
165 case CellState::Unknown:
166 default:
167 return 0;
168 }
169}
170
171float stateToMaskValue(CellState s) {
172 switch (s) {
173 case CellState::Visible:
174 return 1.f;
175 case CellState::Explored:
176 return kExploredMask;
177 case CellState::Unknown:
178 default:
179 return 0.f;
180 }
181}
182
183float normalizeAngle(float a) {
184 while (a <= -kPi) a += 2.f * kPi;
185 while (a > kPi) a -= 2.f * kPi;
186 return a;
187}
188
189constexpr int kMultXX[8] = {1, 0, 0, -1, -1, 0, 0, 1};
190constexpr int kMultXY[8] = {0, 1, -1, 0, 0, -1, 1, 0};
191constexpr int kMultYX[8] = {0, 1, 1, 0, 0, -1, -1, 0};
192constexpr int kMultYY[8] = {1, 0, 0, 1, -1, 0, 0, -1};
193
194constexpr int kCubeDirs[6][3] = {{1, -1, 0}, {1, 0, -1}, {0, 1, -1}, {-1, 1, 0}, {-1, 0, 1}, {0, -1, 1}};
195
196} // namespace
197
198struct Fov::Impl {
199 struct Revealer {
200 int id = 0;
201 int x = 0;
202 int y = 0;
203 int z = 0;
204 int radius = 0;
205 bool enabled = true;
206 bool useCone = false;
207 float facingDeg = 0.f;
208 float halfAngleDeg = 180.f;
209 float perception = 0.f;
210 };
211
212 struct Rect {
213 int x0, y0, x1, y1;
214 };
215
216 struct AngleShadow {
217 float start;
218 float end;
219 };
220
221 int width = 0;
222 int height = 0;
223 int depth = 1;
224 TileLayer *layer = nullptr;
225 uint64_t layerRevision = 0;
226 Algorithm algorithm = Algorithm::Shadowcast;
227 RadiusMetric metric = RadiusMetric::Euclidean;
228 Mode mode = Mode::Grid2D;
229 Topology topology = Topology::Ortho;
230 bool topologyManual = false;
231 bool cornerPeek = false;
232 bool blockEmpty = true;
233 bool dirty = true;
234 float cliffBlock = 1.f;
235 float eyeOffset = 0.f;
238 float detectionMargin = 0.f;
239
240 std::vector<uint8_t> opaque;
241 std::vector<float> elevation;
243 std::vector<CellState> state;
244 std::vector<int> visibleList;
245 std::unordered_set<uint32_t> opaqueGids;
246 std::vector<Revealer> revealers;
247 std::unordered_map<int, std::size_t> revealerIndices;
249
250 int index2(int x, int y) const { return y * width + x; }
251 int index3(int x, int y, int z) const { return (z * height + y) * width + x; }
252 bool inBounds2(int x, int y) const { return x >= 0 && y >= 0 && x < width && y < height; }
253 bool inBounds3(int x, int y, int z) const {
254 return inBounds2(x, y) && z >= 0 && z < depth;
255 }
256
258 if (verticalRange < 0) return std::max(0, depth);
259 return verticalRange;
260 }
261
262 int effectiveRadiusOf(const Revealer &r) const {
263 const int bonus = int(std::floor(r.perception * perceptionRadiusScale));
264 return std::max(0, r.radius + bonus);
265 }
266
267 bool inRadius2(int ox, int oy, int x, int y, int radius) const {
268 if (topology == Topology::Hex) return hexDistance(ox, oy, x, y) <= radius;
269 return inRadiusOrtho(metric, x - ox, y - oy, radius);
270 }
271
272 bool inRadius3(int ox, int oy, int oz, int x, int y, int z, int radius) const {
273 if (topology == Topology::Hex) {
274 return hexDistance(ox, oy, x, y) + std::abs(z - oz) <= radius;
275 }
276 return inRadius3Ortho(metric, x - ox, y - oy, z - oz, radius);
277 }
278
280 if (!layer || topologyManual) return;
281 const auto o = layer->config()->orientation;
282 topology = (o == MapOrientation::Hexagonal || o == MapOrientation::Staggered) ? Topology::Hex
283 : Topology::Ortho;
284 }
285
286 void resize(int w, int h, int d) {
287 width = w > 0 ? w : 0;
288 height = h > 0 ? h : 0;
289 depth = d > 0 ? d : 1;
290 const size_t n = size_t(width * height * depth);
291 opaque.assign(n, 0);
292 state.assign(n, CellState::Unknown);
293 elevation.assign(size_t(width * height), 0.f);
294 visibleList.clear();
295 dirty = true;
296 }
297
299 layer = l;
300 if (!layer) return;
301 auto cfg = layer->config();
302 resize(cfg->mapW, cfg->mapH, 1);
303 if (mode == Mode::Volume) mode = Mode::Grid2D;
306 }
307
309 if (!layer) return;
310 auto cfg = layer->config();
311 auto tiles = layer->tiles();
312 auto tileset = layer->tileset();
313 if (cfg->mapW != width || cfg->mapH != height || depth != 1) {
314 resize(cfg->mapW, cfg->mapH, 1);
315 }
317 const int n = width * height;
318 for (int i = 0; i < n; ++i) {
319 const uint32_t gid = (i < int(tiles->gids.size())) ? tileGid(tiles->gids[size_t(i)]) : 0u;
320 bool isOpaque = false;
321 if (blockEmpty && gid == 0u) isOpaque = true;
322 if (opaqueGids.count(gid)) isOpaque = true;
323 const auto visual =
324 std::find_if(tileset->visuals.begin(), tileset->visuals.end(),
325 [gid](const TileLayer::Tileset::Visual &candidate) { return candidate.gid == int(gid); });
326 if (visual != tileset->visuals.end()) isOpaque = isOpaque || visual->opaque;
327 opaque[size_t(i)] = isOpaque ? 1u : 0u;
328 }
329 layerRevision = tiles->revision;
330 dirty = true;
331 }
332
333 bool cellOpaque2(int x, int y) const {
334 if (!inBounds2(x, y)) return true;
335 return opaque[size_t(index2(x, y))] != 0;
336 }
337
338 bool cellOpaque3(int x, int y, int z) const {
339 if (!inBounds3(x, y, z)) return true;
340 return opaque[size_t(index3(x, y, z))] != 0;
341 }
342
343 bool cellOpaqueOnSlice(int x, int y, int zSlice) const {
344 if (mode == Mode::Volume) return cellOpaque3(x, y, zSlice);
345 return cellOpaque2(x, y);
346 }
347
348 float elevAt(int x, int y) const {
349 if (!inBounds2(x, y)) return 0.f;
350 return elevation[size_t(index2(x, y))];
351 }
352
353 void markVisibleIdx(int idx) {
354 if (idx < 0 || idx >= int(state.size())) return;
355 if (state[size_t(idx)] != CellState::Visible) {
356 state[size_t(idx)] = CellState::Visible;
357 visibleList.push_back(idx);
358 }
359 }
360
361 void markVisible2(int x, int y) {
362 if (!inBounds2(x, y)) return;
364 }
365
366 void markVisible3(int x, int y, int z) {
367 if (!inBounds3(x, y, z)) return;
369 }
370
372 for (int idx : visibleList) {
373 if (idx >= 0 && idx < int(state.size()) && state[size_t(idx)] == CellState::Visible) {
374 state[size_t(idx)] = CellState::Explored;
375 }
376 }
377 visibleList.clear();
378 }
379
381 std::fill(state.begin(), state.end(), CellState::Unknown);
382 visibleList.clear();
383 dirty = true;
384 }
385
387 const auto found = revealerIndices.find(id);
388 return found == revealerIndices.end() ? nullptr : &revealers[found->second];
389 }
390
391 const Revealer *findRevealerConst(int id) const {
392 const auto found = revealerIndices.find(id);
393 return found == revealerIndices.end() ? nullptr : &revealers[found->second];
394 }
395
396 bool losBresenham2(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const {
397 int dx = std::abs(x1 - x0);
398 int dy = std::abs(y1 - y0);
399 const int sx = x0 < x1 ? 1 : -1;
400 const int sy = y0 < y1 ? 1 : -1;
401 int err = dx - dy;
402 int x = x0;
403 int y = y0;
404 const float viewerElev = elevAt(x0, y0) + eyeOffset;
405
406 while (true) {
407 if (x == x1 && y == y1) return true;
408 const int e2 = 2 * err;
409 int nx = x;
410 int ny = y;
411 if (e2 > -dy) {
412 err -= dy;
413 nx += sx;
414 }
415 if (e2 < dx) {
416 err += dx;
417 ny += sy;
418 }
419 const bool atEnd = (nx == x1 && ny == y1);
420 if (!atEnd && cellOpaqueOnSlice(nx, ny, zSlice)) return false;
421 if (applyHeight && mode == Mode::Heightmap && !atEnd) {
422 if (elevAt(nx, ny) >= viewerElev + cliffBlock) return false;
423 }
424 if (!cornerPeek && nx != x && ny != y) {
425 if (cellOpaqueOnSlice(nx, y, zSlice) && cellOpaqueOnSlice(x, ny, zSlice)) {
426 return false;
427 }
428 }
429 x = nx;
430 y = ny;
431 }
432 }
433
434 bool losHexCube(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const {
435 int q0, r0, s0, q1, r1, s1;
436 offsetToCube(x0, y0, q0, r0, s0);
437 offsetToCube(x1, y1, q1, r1, s1);
438 const int n = cubeDistance(q0, r0, s0, q1, r1, s1);
439 if (n == 0) return true;
440 const float viewerElev = elevAt(x0, y0) + eyeOffset;
441 for (int i = 1; i <= n; ++i) {
442 const float t = float(i) / float(n);
443 const float qf = float(q0) + (float(q1) - float(q0)) * t;
444 const float rf = float(r0) + (float(r1) - float(r0)) * t;
445 const float sf = float(s0) + (float(s1) - float(s0)) * t;
446 // cube round
447 int rq = int(std::lround(qf));
448 int rr = int(std::lround(rf));
449 int rs = int(std::lround(sf));
450 const float qdiff = std::fabs(rq - qf);
451 const float rdiff = std::fabs(rr - rf);
452 const float sdiff = std::fabs(rs - sf);
453 if (qdiff > rdiff && qdiff > sdiff) rq = -rr - rs;
454 else if (rdiff > sdiff) rr = -rq - rs;
455 else rs = -rq - rr;
456 (void)rs;
457 int x, y;
458 cubeToOffset(rq, rr, x, y);
459 const bool atEnd = (i == n);
460 if (!atEnd && cellOpaqueOnSlice(x, y, zSlice)) return false;
461 if (applyHeight && mode == Mode::Heightmap && !atEnd) {
462 if (elevAt(x, y) >= viewerElev + cliffBlock) return false;
463 }
464 }
465 return true;
466 }
467
468 bool los2(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const {
469 if (topology == Topology::Hex) return losHexCube(x0, y0, x1, y1, zSlice, applyHeight);
470 return losBresenham2(x0, y0, x1, y1, zSlice, applyHeight);
471 }
472
473 bool passesHeightToTarget(int ox, int oy, int tx, int ty) const {
474 if (mode != Mode::Heightmap || unobstructedHeightmap) return true;
475 return los2(ox, oy, tx, ty, 0, true);
476 }
477
478 void tryMark2(int ox, int oy, int x, int y, int zSlice, bool useCone, float facingDeg,
479 float halfAngleDeg, int radius) {
480 if (!inBounds2(x, y)) return;
481 if (!inRadius2(ox, oy, x, y, radius)) return;
482 if (!inCone(ox, oy, x, y, useCone, facingDeg, halfAngleDeg)) return;
483 if (!passesHeightToTarget(ox, oy, x, y)) return;
484 if (mode == Mode::Volume) markVisible3(x, y, zSlice);
485 else markVisible2(x, y);
486 }
487
488 void castLight(int ox, int oy, int radius, int row, float startSlope, float endSlope, int xx,
489 int xy, int yx, int yy, int zSlice, bool useCone, float facingDeg,
490 float halfAngleDeg) {
491 if (startSlope < endSlope) return;
492 float newStart = 0.f;
493 for (int j = row; j <= radius; ++j) {
494 int dx = -j - 1;
495 int dy = -j;
496 bool blocked = false;
497 while (dx <= 0) {
498 ++dx;
499 const int mapX = ox + dx * xx + dy * xy;
500 const int mapY = oy + dx * yx + dy * yy;
501 const float leftSlope = (float(dx) - 0.5f) / (float(dy) + 0.5f);
502 const float rightSlope = (float(dx) + 0.5f) / (float(dy) - 0.5f);
503 if (startSlope < rightSlope) continue;
504 if (endSlope > leftSlope) break;
505 tryMark2(ox, oy, mapX, mapY, zSlice, useCone, facingDeg, halfAngleDeg, radius);
506 if (blocked) {
507 if (cellOpaqueOnSlice(mapX, mapY, zSlice)) {
508 newStart = rightSlope;
509 continue;
510 }
511 blocked = false;
512 startSlope = newStart;
513 } else if (cellOpaqueOnSlice(mapX, mapY, zSlice) && j < radius) {
514 blocked = true;
515 castLight(ox, oy, radius, j + 1, startSlope, leftSlope, xx, xy, yx, yy, zSlice,
516 useCone, facingDeg, halfAngleDeg);
517 newStart = rightSlope;
518 }
519 }
520 if (blocked) break;
521 }
522 }
523
524 void computeOrthoShadowcast(const Revealer &r, int zSlice, int radius) {
525 tryMark2(r.x, r.y, r.x, r.y, zSlice, r.useCone, r.facingDeg, r.halfAngleDeg, radius);
526 if (radius == 0) return;
527 for (int oct = 0; oct < 8; ++oct) {
528 castLight(r.x, r.y, radius, 1, 1.f, 0.f, kMultXX[oct], kMultXY[oct], kMultYX[oct],
529 kMultYY[oct], zSlice, r.useCone, r.facingDeg, r.halfAngleDeg);
530 }
531 }
532
533 float hexCellAngle(int ox, int oy, int x, int y) const {
534 const float px = float(x) + ((y & 1) ? 0.5f : 0.f);
535 const float py = float(y) * 0.86602540378f; // ≈ √3/2
536 const float opx = float(ox) + ((oy & 1) ? 0.5f : 0.f);
537 const float opy = float(oy) * 0.86602540378f;
538 return std::atan2(py - opy, px - opx);
539 }
540
541 bool angleFullyCovered(float a0, float a1, const std::vector<AngleShadow> &shadows) const {
542 // Conservative: sample mid angle; for small cells this is enough for FOV.
543 float mid = normalizeAngle(0.5f * (a0 + a1));
544 // handle wrap when a0/a1 straddle ±π
545 if (std::fabs(a1 - a0) > kPi) mid = normalizeAngle(mid + kPi);
546 for (const auto &sh : shadows) {
547 float s = sh.start, e = sh.end;
548 if (s <= e) {
549 if (mid >= s && mid <= e) return true;
550 } else {
551 if (mid >= s || mid <= e) return true;
552 }
553 }
554 return false;
555 }
556
557 void addAngleShadow(std::vector<AngleShadow> &shadows, float a0, float a1) const {
558 a0 = normalizeAngle(a0);
559 a1 = normalizeAngle(a1);
560 // Ensure [start,end] covers the short arc from a0 to a1 going the opaque wedge way:
561 // use unordered span expanded slightly.
562 float start = a0;
563 float end = a1;
564 float diff = normalizeAngle(end - start);
565 if (diff < 0.f) std::swap(start, end);
566 shadows.push_back(AngleShadow{normalizeAngle(start), normalizeAngle(end)});
567 }
568
569 void computeHexShadowcast(const Revealer &r, int zSlice, int radius) {
570 tryMark2(r.x, r.y, r.x, r.y, zSlice, r.useCone, r.facingDeg, r.halfAngleDeg, radius);
571 if (radius == 0) return;
572 std::vector<AngleShadow> shadows;
573 shadows.reserve(64);
574
575 int cq, cr, cs;
576 offsetToCube(r.x, r.y, cq, cr, cs);
577
578 for (int ring = 1; ring <= radius; ++ring) {
579 // Start at cube +dir0 * ring, walk 6 edges
580 int q = cq + kCubeDirs[4][0] * ring;
581 int rr = cr + kCubeDirs[4][1] * ring;
582 int s = cs + kCubeDirs[4][2] * ring;
583 for (int side = 0; side < 6; ++side) {
584 for (int step = 0; step < ring; ++step) {
585 int x, y;
586 cubeToOffset(q, rr, x, y);
587 if (inBounds2(x, y) && inRadius2(r.x, r.y, x, y, radius) &&
588 inCone(r.x, r.y, x, y, r.useCone, r.facingDeg, r.halfAngleDeg)) {
589 const float ang = hexCellAngle(r.x, r.y, x, y);
590 const float half =
591 (ring <= 0) ? kPi : (0.55f / float(ring)); // angular half-width
592 const float a0 = normalizeAngle(ang - half);
593 const float a1 = normalizeAngle(ang + half);
594 if (!angleFullyCovered(a0, a1, shadows) &&
595 passesHeightToTarget(r.x, r.y, x, y)) {
596 tryMark2(r.x, r.y, x, y, zSlice, false, 0.f, 180.f, radius);
597 }
598 if (cellOpaqueOnSlice(x, y, zSlice)) {
599 addAngleShadow(shadows, a0, a1);
600 }
601 }
602 q += kCubeDirs[side][0];
603 rr += kCubeDirs[side][1];
604 s += kCubeDirs[side][2];
605 (void)s;
606 }
607 }
608 }
609 }
610
611 void computeShadowcast(const Revealer &r, int zSlice, int radius) {
612 if (topology == Topology::Hex) computeHexShadowcast(r, zSlice, radius);
613 else computeOrthoShadowcast(r, zSlice, radius);
614 }
615
616 void castRayLine(int ox, int oy, int tx, int ty, int zSlice, bool useCone, float facingDeg,
617 float halfAngleDeg, int radius) {
618 if (topology == Topology::Hex) {
619 // Follow cube line, marking until blocked.
620 int q0, r0, s0, q1, r1, s1;
621 offsetToCube(ox, oy, q0, r0, s0);
622 offsetToCube(tx, ty, q1, r1, s1);
623 const int n = std::max(1, cubeDistance(q0, r0, s0, q1, r1, s1));
624 for (int i = 0; i <= n; ++i) {
625 const float t = float(i) / float(n);
626 int rq = int(std::lround(float(q0) + (float(q1) - float(q0)) * t));
627 int rr = int(std::lround(float(r0) + (float(r1) - float(r0)) * t));
628 int rs = -rq - rr;
629 (void)rs;
630 int x, y;
631 cubeToOffset(rq, rr, x, y);
632 tryMark2(ox, oy, x, y, zSlice, useCone, facingDeg, halfAngleDeg, radius);
633 if (i > 0 && cellOpaqueOnSlice(x, y, zSlice)) break;
634 }
635 return;
636 }
637 int dx = std::abs(tx - ox);
638 int dy = std::abs(ty - oy);
639 const int sx = ox < tx ? 1 : -1;
640 const int sy = oy < ty ? 1 : -1;
641 int err = dx - dy;
642 int x = ox;
643 int y = oy;
644 while (true) {
645 tryMark2(ox, oy, x, y, zSlice, useCone, facingDeg, halfAngleDeg, radius);
646 if (x == tx && y == ty) break;
647 if (!(x == ox && y == oy) && cellOpaqueOnSlice(x, y, zSlice)) break;
648 const int e2 = 2 * err;
649 if (e2 > -dy) {
650 err -= dy;
651 x += sx;
652 }
653 if (e2 < dx) {
654 err += dx;
655 y += sy;
656 }
657 }
658 }
659
660 void computeRaycast(const Revealer &r, int zSlice, int radius) {
661 tryMark2(r.x, r.y, r.x, r.y, zSlice, r.useCone, r.facingDeg, r.halfAngleDeg, radius);
662 if (radius == 0) return;
663 if (topology == Topology::Hex) {
664 int cq, cr, cs;
665 offsetToCube(r.x, r.y, cq, cr, cs);
666 for (int ring = 1; ring <= radius; ++ring) {
667 int q = cq + kCubeDirs[4][0] * ring;
668 int rr = cr + kCubeDirs[4][1] * ring;
669 for (int side = 0; side < 6; ++side) {
670 for (int step = 0; step < ring; ++step) {
671 int x, y;
672 cubeToOffset(q, rr, x, y);
673 castRayLine(r.x, r.y, x, y, zSlice, r.useCone, r.facingDeg, r.halfAngleDeg,
674 radius);
675 q += kCubeDirs[side][0];
676 rr += kCubeDirs[side][1];
677 }
678 }
679 }
680 return;
681 }
682 for (int i = -radius; i <= radius; ++i) {
683 castRayLine(r.x, r.y, r.x + i, r.y - radius, zSlice, r.useCone, r.facingDeg,
684 r.halfAngleDeg, radius);
685 castRayLine(r.x, r.y, r.x + i, r.y + radius, zSlice, r.useCone, r.facingDeg,
686 r.halfAngleDeg, radius);
687 castRayLine(r.x, r.y, r.x - radius, r.y + i, zSlice, r.useCone, r.facingDeg,
688 r.halfAngleDeg, radius);
689 castRayLine(r.x, r.y, r.x + radius, r.y + i, zSlice, r.useCone, r.facingDeg,
690 r.halfAngleDeg, radius);
691 }
692 }
693
694 void computePermissive(const Revealer &r, int zSlice, int radius) {
695 tryMark2(r.x, r.y, r.x, r.y, zSlice, r.useCone, r.facingDeg, r.halfAngleDeg, radius);
696 if (radius == 0) return;
697 for (int dy = -radius; dy <= radius; ++dy) {
698 for (int dx = -radius; dx <= radius; ++dx) {
699 if (dx == 0 && dy == 0) continue;
700 const int tx = r.x + dx;
701 const int ty = r.y + dy;
702 if (!inBounds2(tx, ty)) continue;
703 if (!inRadius2(r.x, r.y, tx, ty, radius)) continue;
704 if (!inCone(r.x, r.y, tx, ty, r.useCone, r.facingDeg, r.halfAngleDeg)) continue;
705 bool see = los2(r.x, r.y, tx, ty, zSlice, mode == Mode::Heightmap);
706 if (!see) {
707 const int sx = (dx > 0) ? -1 : (dx < 0 ? 1 : 0);
708 const int sy = (dy > 0) ? -1 : (dy < 0 ? 1 : 0);
709 const int cands[3][2] = {{tx + sx, ty}, {tx, ty + sy}, {tx + sx, ty + sy}};
710 for (auto &c : cands) {
711 const int ax = c[0];
712 const int ay = c[1];
713 if (ax == tx && ay == ty) continue;
714 if (!inBounds2(ax, ay)) continue;
715 if (cellOpaqueOnSlice(ax, ay, zSlice)) continue;
716 if (!inRadius2(r.x, r.y, ax, ay, radius)) continue;
717 if (los2(r.x, r.y, ax, ay, zSlice, mode == Mode::Heightmap)) {
718 see = true;
719 break;
720 }
721 }
722 }
723 if (see) tryMark2(r.x, r.y, tx, ty, zSlice, false, 0.f, 180.f, radius);
724 }
725 }
726 }
727
728 std::vector<Rect> buildOpaqueRects(int ox, int oy, int radius, int zSlice) const {
729 const int xMin = std::max(0, ox - radius);
730 const int xMax = std::min(width - 1, ox + radius);
731 const int yMin = std::max(0, oy - radius);
732 const int yMax = std::min(height - 1, oy + radius);
733 const int bw = xMax - xMin + 1;
734 const int bh = yMax - yMin + 1;
735 std::vector<uint8_t> used(size_t(bw * bh), 0);
736 auto usedAt = [&](int x, int y) -> uint8_t & {
737 return used[size_t((y - yMin) * bw + (x - xMin))];
738 };
739
740 std::vector<Rect> rects;
741 for (int y = yMin; y <= yMax; ++y) {
742 for (int x = xMin; x <= xMax; ++x) {
743 if (usedAt(x, y)) continue;
744 if (!cellOpaqueOnSlice(x, y, zSlice)) continue;
745 if (!inRadius2(ox, oy, x, y, radius)) continue;
746 int x1 = x;
747 while (x1 + 1 <= xMax && !usedAt(x1 + 1, y) && cellOpaqueOnSlice(x1 + 1, y, zSlice) &&
748 inRadius2(ox, oy, x1 + 1, y, radius)) {
749 ++x1;
750 }
751 int y1 = y;
752 bool grow = true;
753 while (grow && y1 + 1 <= yMax) {
754 for (int xx = x; xx <= x1; ++xx) {
755 if (usedAt(xx, y1 + 1) || !cellOpaqueOnSlice(xx, y1 + 1, zSlice) ||
756 !inRadius2(ox, oy, xx, y1 + 1, radius)) {
757 grow = false;
758 break;
759 }
760 }
761 if (grow) ++y1;
762 }
763 for (int yy = y; yy <= y1; ++yy)
764 for (int xx = x; xx <= x1; ++xx) usedAt(xx, yy) = 1;
765 rects.push_back(Rect{x, y, x1, y1});
766 }
767 }
768 return rects;
769 }
770
771 void computeRectangle(const Revealer &r, int zSlice, int radius) {
772 // Mark all in-radius cells, then carve umbras behind opaque rectangles.
773 std::vector<uint8_t> lit(size_t(width * height), 0);
774 auto litAt = [&](int x, int y) -> uint8_t & { return lit[size_t(index2(x, y))]; };
775
776 for (int y = std::max(0, r.y - radius); y <= std::min(height - 1, r.y + radius); ++y) {
777 for (int x = std::max(0, r.x - radius); x <= std::min(width - 1, r.x + radius); ++x) {
778 if (!inRadius2(r.x, r.y, x, y, radius)) continue;
779 if (!inCone(r.x, r.y, x, y, r.useCone, r.facingDeg, r.halfAngleDeg)) continue;
780 if (!passesHeightToTarget(r.x, r.y, x, y)) continue;
781 litAt(x, y) = 1;
782 }
783 }
784
785 auto rects = buildOpaqueRects(r.x, r.y, radius, zSlice);
786 const float ox = float(r.x) + 0.5f;
787 const float oy = float(r.y) + 0.5f;
788 std::sort(rects.begin(), rects.end(), [&](const Rect &a, const Rect &b) {
789 const int acx = (a.x0 + a.x1) / 2;
790 const int acy = (a.y0 + a.y1) / 2;
791 const int bcx = (b.x0 + b.x1) / 2;
792 const int bcy = (b.y0 + b.y1) / 2;
793 return inRadius2(r.x, r.y, acx, acy, radius) &&
794 (std::abs(acx - r.x) + std::abs(acy - r.y)) <
795 (std::abs(bcx - r.x) + std::abs(bcy - r.y));
796 });
797
798 for (const auto &rc : rects) {
799 // Tangents from origin to rectangle corners → umbra angles.
800 const float corners[4][2] = {
801 {float(rc.x0), float(rc.y0)},
802 {float(rc.x1) + 1.f, float(rc.y0)},
803 {float(rc.x0), float(rc.y1) + 1.f},
804 {float(rc.x1) + 1.f, float(rc.y1) + 1.f},
805 };
806 float angles[4];
807 for (int i = 0; i < 4; ++i) {
808 angles[i] = std::atan2(corners[i][1] - oy, corners[i][0] - ox);
809 }
810 float aMin = angles[0], aMax = angles[0];
811 for (int i = 1; i < 4; ++i) {
812 const float dMin = normalizeAngle(angles[i] - aMin);
813 const float dMax = normalizeAngle(angles[i] - aMax);
814 if (dMin < 0.f) aMin = angles[i];
815 if (dMax > 0.f) aMax = angles[i];
816 }
817 const float nearest2 =
818 float(std::min({(rc.x0 - r.x) * (rc.x0 - r.x) + (rc.y0 - r.y) * (rc.y0 - r.y),
819 (rc.x1 - r.x) * (rc.x1 - r.x) + (rc.y0 - r.y) * (rc.y0 - r.y),
820 (rc.x0 - r.x) * (rc.x0 - r.x) + (rc.y1 - r.y) * (rc.y1 - r.y),
821 (rc.x1 - r.x) * (rc.x1 - r.x) + (rc.y1 - r.y) * (rc.y1 - r.y)}));
822
823 for (int y = std::max(0, r.y - radius); y <= std::min(height - 1, r.y + radius); ++y) {
824 for (int x = std::max(0, r.x - radius); x <= std::min(width - 1, r.x + radius); ++x) {
825 if (!litAt(x, y)) continue;
826 // Keep the blocking rectangle itself lit.
827 if (x >= rc.x0 && x <= rc.x1 && y >= rc.y0 && y <= rc.y1) continue;
828 const float d2 = float((x - r.x) * (x - r.x) + (y - r.y) * (y - r.y));
829 if (d2 <= nearest2 + 0.01f) continue;
830 const float ang = std::atan2(float(y) + 0.5f - oy, float(x) + 0.5f - ox);
831 bool inside = false;
832 if (aMin <= aMax) inside = (ang >= aMin && ang <= aMax);
833 else inside = (ang >= aMin || ang <= aMax);
834 // Use normalized compare for wrapped wedges.
835 if (normalizeAngle(aMax - aMin) < 0.f) {
836 inside = normalizeAngle(ang - aMin) >= 0.f ||
837 normalizeAngle(aMax - ang) >= 0.f;
838 } else {
839 const float da = normalizeAngle(ang - aMin);
840 const float span = normalizeAngle(aMax - aMin);
841 inside = da >= 0.f && da <= span;
842 }
843 if (inside) litAt(x, y) = 0;
844 }
845 }
846 }
847
848 for (int y = 0; y < height; ++y) {
849 for (int x = 0; x < width; ++x) {
850 if (litAt(x, y)) tryMark2(r.x, r.y, x, y, zSlice, false, 0.f, 180.f, radius);
851 }
852 }
853 }
854
855 void extendVertical(const Revealer &r, int zSlice, int radius) {
856 if (mode != Mode::Volume) return;
857 const int vRange = effectiveVerticalRange();
858 for (int y = std::max(0, r.y - radius); y <= std::min(height - 1, r.y + radius); ++y) {
859 for (int x = std::max(0, r.x - radius); x <= std::min(width - 1, r.x + radius); ++x) {
860 const int idx = index3(x, y, zSlice);
861 if (state[size_t(idx)] != CellState::Visible) continue;
862 for (int dir = -1; dir <= 1; dir += 2) {
863 for (int step = 1; step <= vRange; ++step) {
864 const int z = zSlice + dir * step;
865 if (z < 0 || z >= depth) break;
866 if (!inRadius3(r.x, r.y, r.z, x, y, z, radius)) break;
867 markVisible3(x, y, z);
868 if (cellOpaque3(x, y, z)) break;
869 }
870 }
871 }
872 }
873 }
874
876 if (!r.enabled) return;
877 if (!inBounds2(r.x, r.y)) return;
878 int zSlice = 0;
879 if (mode == Mode::Volume) {
880 if (!inBounds3(r.x, r.y, r.z)) return;
881 zSlice = r.z;
882 }
883 const int radius = effectiveRadiusOf(r);
884
885 switch (algorithm) {
886 case Algorithm::Raycast:
887 computeRaycast(r, zSlice, radius);
888 break;
889 case Algorithm::Permissive:
890 computePermissive(r, zSlice, radius);
891 break;
892 case Algorithm::Rectangle:
893 computeRectangle(r, zSlice, radius);
894 break;
895 case Algorithm::Shadowcast:
896 default:
897 computeShadowcast(r, zSlice, radius);
898 break;
899 }
900 extendVertical(r, zSlice, radius);
901 }
902
903 void compute() {
904 if (layer && layerRevision != layer->tiles()->revision) syncFromLayer();
905 if (!dirty) return;
906 // Prove that no terrain or opaque cell can block a height ray before bypassing it.
907 // Recomputed from authoritative cells on every dirty compute, including terrain edits.
908 unobstructedHeightmap = false;
909 if (mode == Mode::Heightmap && topology == Topology::Ortho && !elevation.empty() &&
910 std::none_of(opaque.begin(), opaque.end(), [](auto value) { return value != 0; })) {
911 const auto bounds = std::minmax_element(elevation.begin(), elevation.end());
913 }
915 for (const auto &r : revealers) computeRevealer(r);
916 dirty = false;
917 }
918};
919
920Fov::Fov() : impl_(std::make_unique<Impl>()) {}
924Fov::~Fov() = default;
925Fov::Fov(Fov &&) noexcept = default;
926Fov &Fov::operator=(Fov &&) noexcept = default;
927
928void Fov::bindLayer(TileLayer *layer) {
929 if (!layer) return;
930 impl_->bindLayer(layer);
931}
932
933void Fov::setSize(int width, int height) {
934 impl_->layer = nullptr;
935 if (impl_->mode == Mode::Volume) impl_->mode = Mode::Grid2D;
936 impl_->resize(width, height, 1);
937}
938
940 impl_->layer = nullptr;
941 impl_->mode = Mode::Volume;
942 impl_->resize(width, height, depth);
943}
944
945int Fov::getWidth() const { return impl_->width; }
946int Fov::getHeight() const { return impl_->height; }
947int Fov::getDepth() const { return impl_->depth; }
948
949void Fov::setMode(const std::string &name) {
950 const Mode next = parseMode(name, impl_->mode);
951 impl_->mode = next;
952 if (next != Mode::Volume && impl_->depth != 1) {
953 impl_->resize(impl_->width, impl_->height, 1);
954 }
955 impl_->dirty = true;
956}
957
958std::string Fov::getMode() const { return modeName(impl_->mode); }
959
960void Fov::setAlgorithm(const std::string &name) {
961 impl_->algorithm = parseAlgorithm(name, impl_->algorithm);
962 impl_->dirty = true;
963}
964
965std::string Fov::getAlgorithm() const { return algorithmName(impl_->algorithm); }
966
967void Fov::setRadiusMetric(const std::string &name) {
968 impl_->metric = parseMetric(name, impl_->metric);
969 impl_->dirty = true;
970}
971
972std::string Fov::getRadiusMetric() const { return metricName(impl_->metric); }
973
974void Fov::setTopology(const std::string &name) {
975 if (name == "auto") {
976 impl_->topologyManual = false;
977 impl_->applyAutoTopologyFromLayer();
978 if (!impl_->layer) impl_->topology = Topology::Ortho;
979 } else if (name == "hex" || name == "hexagonal" || name == "staggered") {
980 impl_->topologyManual = true;
981 impl_->topology = Topology::Hex;
982 } else if (name == "ortho" || name == "orthogonal") {
983 impl_->topologyManual = true;
984 impl_->topology = Topology::Ortho;
985 }
986 impl_->dirty = true;
987}
988
989std::string Fov::getTopology() const { return topologyName(impl_->topology); }
990
991void Fov::setCornerPeek(bool enable) {
992 impl_->cornerPeek = enable;
993 impl_->dirty = true;
994}
995bool Fov::getCornerPeek() const { return impl_->cornerPeek; }
996
997void Fov::blockOpaqueGid(int gid) {
998 if (gid < 0) return;
999 impl_->opaqueGids.insert(uint32_t(gid));
1000 if (impl_->layer) impl_->syncFromLayer();
1001 else impl_->dirty = true;
1002}
1003
1005 if (gid < 0) return;
1006 impl_->opaqueGids.erase(uint32_t(gid));
1007 if (impl_->layer) impl_->syncFromLayer();
1008 else impl_->dirty = true;
1009}
1010
1012 impl_->opaqueGids.clear();
1013 if (impl_->layer) impl_->syncFromLayer();
1014 else impl_->dirty = true;
1015}
1016
1017void Fov::setBlockEmpty(bool enable) {
1018 impl_->blockEmpty = enable;
1019 if (impl_->layer) impl_->syncFromLayer();
1020 else impl_->dirty = true;
1021}
1022
1023bool Fov::getBlockEmpty() const { return impl_->blockEmpty; }
1024
1025void Fov::setOpaque(int x, int y, bool opaque) {
1026 if (!impl_->inBounds2(x, y)) return;
1027 if (impl_->mode == Mode::Volume) {
1028 if (!impl_->inBounds3(x, y, 0)) return;
1029 impl_->opaque[size_t(impl_->index3(x, y, 0))] = opaque ? 1u : 0u;
1030 } else {
1031 impl_->opaque[size_t(impl_->index2(x, y))] = opaque ? 1u : 0u;
1032 }
1033 impl_->dirty = true;
1034}
1035
1036bool Fov::isOpaque(int x, int y) const {
1037 if (impl_->mode == Mode::Volume) return impl_->cellOpaque3(x, y, 0);
1038 return impl_->cellOpaque2(x, y);
1039}
1040
1041void Fov::setOpaque3(int x, int y, int z, bool opaque) {
1042 if (!impl_->inBounds3(x, y, z)) return;
1043 impl_->opaque[size_t(impl_->index3(x, y, z))] = opaque ? 1u : 0u;
1044 impl_->dirty = true;
1045}
1046
1047bool Fov::isOpaque3(int x, int y, int z) const { return impl_->cellOpaque3(x, y, z); }
1048
1049void Fov::syncFromLayer() { impl_->syncFromLayer(); }
1050
1051void Fov::setElevation(int x, int y, float elev) {
1052 if (!impl_->inBounds2(x, y)) return;
1053 impl_->elevation[size_t(impl_->index2(x, y))] = elev;
1054 impl_->dirty = true;
1055}
1056
1057float Fov::getElevation(int x, int y) const { return impl_->elevAt(x, y); }
1058
1059void Fov::setCliffBlock(float delta) {
1060 impl_->cliffBlock = delta;
1061 impl_->dirty = true;
1062}
1063float Fov::getCliffBlock() const { return impl_->cliffBlock; }
1064
1066 impl_->eyeOffset = offset;
1067 impl_->dirty = true;
1068}
1069float Fov::getEyeOffset() const { return impl_->eyeOffset; }
1070
1072 impl_->verticalRange = range;
1073 impl_->dirty = true;
1074}
1075int Fov::getVerticalRange() const { return impl_->effectiveVerticalRange(); }
1076
1077int Fov::addRevealer(int x, int y, int radius) { return addRevealer3(x, y, 0, radius); }
1078
1079int Fov::addRevealer3(int x, int y, int z, int radius) {
1081 r.id = impl_->nextRevealerId;
1082 r.x = x;
1083 r.y = y;
1084 r.z = z;
1085 r.radius = radius;
1086 const auto index = impl_->revealers.size();
1087 impl_->revealers.push_back(r);
1088 try {
1089 impl_->revealerIndices.emplace(r.id, index);
1090 } catch (...) {
1091 impl_->revealers.pop_back();
1092 throw;
1093 }
1094 ++impl_->nextRevealerId;
1095 impl_->dirty = true;
1096 return r.id;
1097}
1098
1100 const auto found = impl_->revealerIndices.find(id);
1101 if (found != impl_->revealerIndices.end()) {
1102 const auto index = found->second;
1103 impl_->revealers.erase(impl_->revealers.begin() + static_cast<std::ptrdiff_t>(index));
1104 impl_->revealerIndices.erase(found);
1105 for (std::size_t i = index; i < impl_->revealers.size(); ++i)
1106 impl_->revealerIndices[impl_->revealers[i].id] = i;
1107 }
1108 impl_->dirty = true;
1109}
1110
1112 impl_->revealers.clear();
1113 impl_->revealerIndices.clear();
1114 impl_->dirty = true;
1115}
1116
1117void Fov::setRevealerPosition(int id, int x, int y) {
1118 if (auto *r = impl_->findRevealer(id)) setRevealerPosition3(id, x, y, r->z);
1119}
1120
1121void Fov::setRevealerPosition3(int id, int x, int y, int z) {
1122 if (auto *r = impl_->findRevealer(id)) {
1123 if (r->x == x && r->y == y && r->z == z) return;
1124 r->x = x;
1125 r->y = y;
1126 r->z = z;
1127 impl_->dirty = true;
1128 }
1129}
1130
1132 if (auto *r = impl_->findRevealer(id)) {
1133 if (r->radius == radius) return;
1134 r->radius = radius;
1135 impl_->dirty = true;
1136 }
1137}
1138
1139void Fov::setRevealerFacing(int id, float facingDeg, float halfAngleDeg) {
1140 if (auto *r = impl_->findRevealer(id)) {
1141 r->useCone = true;
1142 r->facingDeg = facingDeg;
1143 r->halfAngleDeg = std::max(0.f, halfAngleDeg);
1144 impl_->dirty = true;
1145 }
1146}
1147
1149 if (auto *r = impl_->findRevealer(id)) {
1150 r->useCone = false;
1151 r->halfAngleDeg = 180.f;
1152 impl_->dirty = true;
1153 }
1154}
1155
1157 if (auto *r = impl_->findRevealer(id)) {
1158 r->enabled = enabled;
1159 impl_->dirty = true;
1160 }
1161}
1162
1163int Fov::getRevealerCount() const { return int(impl_->revealers.size()); }
1164
1165void Fov::setRevealerPerception(int id, float perception) {
1166 if (auto *r = impl_->findRevealer(id)) {
1167 r->perception = perception;
1168 impl_->dirty = true;
1169 }
1170}
1171
1172float Fov::getRevealerPerception(int id) const {
1173 if (const auto *r = impl_->findRevealerConst(id)) return r->perception;
1174 return 0.f;
1175}
1176
1178 impl_->perceptionRadiusScale = scale;
1179 impl_->dirty = true;
1180}
1181float Fov::getPerceptionRadiusScale() const { return impl_->perceptionRadiusScale; }
1182
1183void Fov::setDetectionMargin(float margin) { impl_->detectionMargin = margin; }
1184float Fov::getDetectionMargin() const { return impl_->detectionMargin; }
1185
1186int Fov::getEffectiveRadius(int id) const {
1187 if (const auto *r = impl_->findRevealerConst(id)) return impl_->effectiveRadiusOf(*r);
1188 return 0;
1189}
1190
1191bool Fov::canDetect(int revealerId, int x, int y, float targetStealth) const {
1192 if (impl_->mode == Mode::Volume) return canDetect3(revealerId, x, y, 0, targetStealth);
1193 const auto *r = impl_->findRevealerConst(revealerId);
1194 if (!r || !r->enabled) return false;
1195 if (!isVisible(x, y)) return false;
1196 return (r->perception + impl_->detectionMargin) >= targetStealth;
1197}
1198
1199bool Fov::canDetect3(int revealerId, int x, int y, int z, float targetStealth) const {
1200 const auto *r = impl_->findRevealerConst(revealerId);
1201 if (!r || !r->enabled) return false;
1202 if (!isVisible3(x, y, z)) return false;
1203 return (r->perception + impl_->detectionMargin) >= targetStealth;
1204}
1205
1206void Fov::markDirty() { impl_->dirty = true; }
1207bool Fov::isDirty() const { return impl_->dirty; }
1209 EV_PROFILE_MODULE("map", "Fov::compute");
1210 impl_->compute();
1211}
1212
1213bool Fov::isVisible(int x, int y) const {
1214 if (impl_->mode == Mode::Volume) return isVisible3(x, y, 0);
1215 if (!impl_->inBounds2(x, y)) return false;
1216 return impl_->state[size_t(impl_->index2(x, y))] == CellState::Visible;
1217}
1218
1219bool Fov::isExplored(int x, int y) const {
1220 if (impl_->mode == Mode::Volume) return isExplored3(x, y, 0);
1221 if (!impl_->inBounds2(x, y)) return false;
1222 const auto s = impl_->state[size_t(impl_->index2(x, y))];
1223 return s == CellState::Explored || s == CellState::Visible;
1224}
1225
1226bool Fov::isVisible3(int x, int y, int z) const {
1227 if (!impl_->inBounds3(x, y, z)) return false;
1228 return impl_->state[size_t(impl_->index3(x, y, z))] == CellState::Visible;
1229}
1230
1231bool Fov::isExplored3(int x, int y, int z) const {
1232 if (!impl_->inBounds3(x, y, z)) return false;
1233 const auto s = impl_->state[size_t(impl_->index3(x, y, z))];
1234 return s == CellState::Explored || s == CellState::Visible;
1235}
1236
1237std::string Fov::getState(int x, int y) const {
1238 if (impl_->mode == Mode::Volume) return getState3(x, y, 0);
1239 if (!impl_->inBounds2(x, y)) return "unknown";
1240 switch (impl_->state[size_t(impl_->index2(x, y))]) {
1241 case CellState::Visible:
1242 return "visible";
1243 case CellState::Explored:
1244 return "explored";
1245 default:
1246 return "unknown";
1247 }
1248}
1249
1250std::string Fov::getState3(int x, int y, int z) const {
1251 if (!impl_->inBounds3(x, y, z)) return "unknown";
1252 switch (impl_->state[size_t(impl_->index3(x, y, z))]) {
1253 case CellState::Visible:
1254 return "visible";
1255 case CellState::Explored:
1256 return "explored";
1257 default:
1258 return "unknown";
1259 }
1260}
1261
1262void Fov::clearMemory() { impl_->clearAllMemory(); }
1263
1265 impl_->resetVisibleKeepExplored();
1266 impl_->dirty = true;
1267}
1268
1271 result.width = impl_->width;
1272 result.height = impl_->height;
1273 result.depth = impl_->depth;
1274 result.states.reserve(impl_->state.size());
1275 for (const auto state : impl_->state) result.states.push_back(stateToMaskByte(state));
1276 return result;
1277}
1278
1279Result<void> Fov::restore(const Snapshot& snapshotValue) {
1280 if (snapshotValue.width != impl_->width || snapshotValue.height != impl_->height ||
1281 snapshotValue.depth != impl_->depth || snapshotValue.states.size() != impl_->state.size())
1283 DiagnosticCode::InvalidArgument, "Fov snapshot dimensions or payload size do not match", "snapshot"));
1284 for (std::size_t index = 0; index < snapshotValue.states.size(); ++index) {
1285 const auto value = snapshotValue.states[index];
1286 impl_->state[index] = value == 0 ? CellState::Unknown :
1287 value >= 192 ? CellState::Visible : CellState::Explored;
1288 }
1289 impl_->visibleList.clear();
1290 for (std::size_t index = 0; index < impl_->state.size(); ++index)
1291 if (impl_->state[index] == CellState::Visible) impl_->visibleList.push_back(static_cast<int>(index));
1292 impl_->dirty = true;
1294}
1295
1296float Fov::getMaskValue(int x, int y) const {
1297 if (impl_->mode == Mode::Volume) return getMaskValue3(x, y, 0);
1298 if (!impl_->inBounds2(x, y)) return 0.f;
1299 return stateToMaskValue(impl_->state[size_t(impl_->index2(x, y))]);
1300}
1301
1302int Fov::getMaskByte(int x, int y) const {
1303 if (impl_->mode == Mode::Volume) return getMaskByte3(x, y, 0);
1304 if (!impl_->inBounds2(x, y)) return 0;
1305 return int(stateToMaskByte(impl_->state[size_t(impl_->index2(x, y))]));
1306}
1307
1308float Fov::getMaskValue3(int x, int y, int z) const {
1309 if (!impl_->inBounds3(x, y, z)) return 0.f;
1310 return stateToMaskValue(impl_->state[size_t(impl_->index3(x, y, z))]);
1311}
1312
1313int Fov::getMaskByte3(int x, int y, int z) const {
1314 if (!impl_->inBounds3(x, y, z)) return 0;
1315 return int(stateToMaskByte(impl_->state[size_t(impl_->index3(x, y, z))]));
1316}
1317
1318bool Fov::fillMaskR8(std::vector<uint8_t> &out) const { return fillMaskR8Slice(out, 0); }
1319
1320bool Fov::fillMaskR8Slice(std::vector<uint8_t> &out, int sliceZ) const {
1321 if (impl_->width <= 0 || impl_->height <= 0) {
1322 out.clear();
1323 return false;
1324 }
1325 if (impl_->mode == Mode::Volume) {
1326 if (sliceZ < 0 || sliceZ >= impl_->depth) return false;
1327 } else {
1328 sliceZ = 0;
1329 }
1330 out.resize(size_t(impl_->width * impl_->height));
1331 for (int y = 0; y < impl_->height; ++y) {
1332 for (int x = 0; x < impl_->width; ++x) {
1333 CellState s = (impl_->mode == Mode::Volume)
1334 ? impl_->state[size_t(impl_->index3(x, y, sliceZ))]
1335 : impl_->state[size_t(impl_->index2(x, y))];
1336 out[size_t(impl_->index2(x, y))] = stateToMaskByte(s);
1337 }
1338 }
1339 return true;
1340}
1341
1345
1347 if (!gfx) return nullptr;
1348 std::vector<uint8_t> r8;
1349 if (!fillMaskR8Slice(r8, sliceZ)) return nullptr;
1350 std::vector<uint8_t> rgba(size_t(impl_->width * impl_->height * 4));
1351 for (size_t i = 0; i < r8.size(); ++i) {
1352 const uint8_t v = r8[i];
1353 rgba[i * 4 + 0] = v;
1354 rgba[i * 4 + 1] = v;
1355 rgba[i * 4 + 2] = v;
1356 rgba[i * 4 + 3] = v;
1357 }
1358 return gfx->newTexture(impl_->width, impl_->height, rgba.data());
1359}
1360
1361} // namespace eve::map
double z
double y
double m[16]
double x
Duration start
float w
Definition AnimClip.cpp:738
int mid
Definition AnimSmr.cpp:120
const std::string & s
float ang
std::string name
Definition ECS.cpp:154
std::vector< double > angles
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
std::int32_t xMin
std::int32_t xMax
float v
std::int32_t c
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
size_t offset
Range range
std::array< float, 3 > scale
Poco::JSON::Object::Ptr result
uint64_t used
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
glm::dvec3 dx
glm::dvec3 dz
TileLayer * layer
int idx
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
float d
float t
std::vector< WfcTile > tiles
bool found
Value::Array corners
ScriptStructure out
size_t end
float dy
Definition Shadow.cpp:151
int margin
float step
Definition TreeMesh.cpp:451
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
uint32_t index
double oy
std::vector< char > inside
double ox
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Dynamic field-of-view / fog-of-war facade. Phase A: 2D shadowcast + multi-revealer + explored memory....
Definition Fov.h:27
void blockOpaqueGid(int gid)
Definition Fov.cpp:997
bool canDetect(int revealerId, int x, int y, float targetStealth) const
Definition Fov.cpp:1191
float getElevation(int x, int y) const
Definition Fov.cpp:1057
bool isExplored(int x, int y) const
Definition Fov.cpp:1219
bool isOpaque(int x, int y) const
Definition Fov.cpp:1036
int getVerticalRange() const
Definition Fov.cpp:1075
int getHeight() const
Definition Fov.cpp:946
void bindLayer(TileLayer *layer)
Definition Fov.cpp:928
std::string getRadiusMetric() const
Definition Fov.cpp:972
void setAlgorithm(const std::string &name)
"shadowcast" | "raycast" | "permissive" | "rectangle"
Definition Fov.cpp:960
float getDetectionMargin() const
Definition Fov.cpp:1184
float getEyeOffset() const
Definition Fov.cpp:1069
void setRadiusMetric(const std::string &name)
"euclidean" | "chebyshev" | "manhattan" — ignored when topology is hex (cube distance).
Definition Fov.cpp:967
float getCliffBlock() const
Definition Fov.cpp:1063
void setRevealerEnabled(int id, bool enabled)
Definition Fov.cpp:1156
void setOpaque3(int x, int y, int z, bool opaque)
Definition Fov.cpp:1041
bool isVisible3(int x, int y, int z) const
Definition Fov.cpp:1226
void setDetectionMargin(float margin)
Definition Fov.cpp:1183
void setEyeOffset(float offset)
Definition Fov.cpp:1065
bool isVisible(int x, int y) const
Definition Fov.cpp:1213
int getEffectiveRadius(int id) const
Definition Fov.cpp:1186
void setSize(int width, int height)
Definition Fov.cpp:933
bool fillMaskR8(std::vector< uint8_t > &out) const
Definition Fov.cpp:1318
int getWidth() const
Definition Fov.cpp:945
Result< void > restore(const Snapshot &snapshot)
Restore exact cell states atomically.
Definition Fov.cpp:1279
void setRevealerPosition(int id, int x, int y)
Definition Fov.cpp:1117
float getRevealerPerception(int id) const
Definition Fov.cpp:1172
float getMaskValue3(int x, int y, int z) const
Definition Fov.cpp:1308
int getDepth() const
Definition Fov.cpp:947
void setBlockEmpty(bool enable)
Definition Fov.cpp:1017
std::string getMode() const
Definition Fov.cpp:958
int addRevealer(int x, int y, int radius)
Definition Fov.cpp:1077
void clearMemory()
Definition Fov.cpp:1262
std::string getState3(int x, int y, int z) const
Definition Fov.cpp:1250
float getMaskValue(int x, int y) const
Definition Fov.cpp:1296
void clearOpaqueGids()
Definition Fov.cpp:1011
bool isExplored3(int x, int y, int z) const
Definition Fov.cpp:1231
int getRevealerCount() const
Definition Fov.cpp:1163
graphics::Texture * buildMaskTextureSlice(graphics::Graphics *gfx, int sliceZ) const
Definition Fov.cpp:1346
void setCliffBlock(float delta)
Definition Fov.cpp:1059
void setElevation(int x, int y, float elev)
Definition Fov.cpp:1051
Snapshot snapshot() const
Capture exact unknown/explored/visible cell states without revealers.
Definition Fov.cpp:1269
std::string getTopology() const
Definition Fov.cpp:989
bool fillMaskR8Slice(std::vector< uint8_t > &out, int sliceZ) const
Definition Fov.cpp:1320
int addRevealer3(int x, int y, int z, int radius)
Definition Fov.cpp:1079
std::string getAlgorithm() const
Definition Fov.cpp:965
void setRevealerRadius(int id, int radius)
Definition Fov.cpp:1131
void setRevealerPosition3(int id, int x, int y, int z)
Definition Fov.cpp:1121
void setRevealerPerception(int id, float perception)
Soft RPG hooks (no hard dependency on rpg module). effectiveRadius = radius + floor(perception * perc...
Definition Fov.cpp:1165
void setRevealerFacing(int id, float facingDeg, float halfAngleDeg)
Definition Fov.cpp:1139
void removeRevealer(int id)
Definition Fov.cpp:1099
bool getCornerPeek() const
Definition Fov.cpp:995
void clearRevealers()
Definition Fov.cpp:1111
void clearRevealerFacing(int id)
Definition Fov.cpp:1148
bool isDirty() const
Definition Fov.cpp:1207
void compute()
Definition Fov.cpp:1208
void setPerceptionRadiusScale(float scale)
Definition Fov.cpp:1177
void setMode(const std::string &name)
"grid2d" (default) | "heightmap" | "volume"
Definition Fov.cpp:949
void unblockOpaqueGid(int gid)
Definition Fov.cpp:1004
void markDirty()
Definition Fov.cpp:1206
int getMaskByte(int x, int y) const
Definition Fov.cpp:1302
void setVerticalRange(int range)
Definition Fov.cpp:1071
bool canDetect3(int revealerId, int x, int y, int z, float targetStealth) const
Definition Fov.cpp:1199
float getPerceptionRadiusScale() const
Definition Fov.cpp:1181
bool isOpaque3(int x, int y, int z) const
Definition Fov.cpp:1047
bool getBlockEmpty() const
Definition Fov.cpp:1023
std::string getState(int x, int y) const
Definition Fov.cpp:1237
void setCornerPeek(bool enable)
Definition Fov.cpp:991
void setOpaque(int x, int y, bool opaque)
Definition Fov.cpp:1025
graphics::Texture * buildMaskTexture(graphics::Graphics *gfx) const
Upload current 2D / slice mask as RGBA8 Texture (R=G=B=A=mask byte). Caller owns the returned Texture...
Definition Fov.cpp:1342
void resetVisibleOnly()
Definition Fov.cpp:1264
void setTopology(const std::string &name)
"ortho" (default) | "hex" | "auto" (hex if bound layer is hex/staggered).
Definition Fov.cpp:974
void syncFromLayer()
Definition Fov.cpp:1049
void setVolumeSize(int width, int height, int depth)
Definition Fov.cpp:939
int getMaskByte3(int x, int y, int z) const
Definition Fov.cpp:1313
ECS tile layer entity. Script mutates tile GIDs / tileset / draw; TileRenderSystem batch-draws atlas ...
Definition TileLayer.h:33
放置世界:格子占用(多通道)+ 地形语义 + 已放置建筑实例。 行为由 PlacementSystem 提供;本类暴露便于脚本绑定的薄封装方法。 坐标换算统一走 eve::grid(支持 rectang...
uint32_t tileGid(uint32_t raw)
Strip Tiled flip / rotate flags; keep low 28 bits.
Definition TileLayer.h:392
bool enabled
Topology topology
Definition Fov.cpp:229
float hexCellAngle(int ox, int oy, int x, int y) const
Definition Fov.cpp:533
void computeShadowcast(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:611
void computeRaycast(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:660
std::vector< uint8_t > opaque
Definition Fov.cpp:240
void computePermissive(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:694
void computeOrthoShadowcast(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:524
void computeRectangle(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:771
RadiusMetric metric
Definition Fov.cpp:227
const Revealer * findRevealerConst(int id) const
Definition Fov.cpp:391
void markVisibleIdx(int idx)
Definition Fov.cpp:353
std::vector< CellState > state
Definition Fov.cpp:243
void markVisible2(int x, int y)
Definition Fov.cpp:361
int index2(int x, int y) const
Definition Fov.cpp:250
void castRayLine(int ox, int oy, int tx, int ty, int zSlice, bool useCone, float facingDeg, float halfAngleDeg, int radius)
Definition Fov.cpp:616
float detectionMargin
Definition Fov.cpp:238
bool unobstructedHeightmap
Definition Fov.cpp:242
bool inBounds3(int x, int y, int z) const
Definition Fov.cpp:253
bool passesHeightToTarget(int ox, int oy, int tx, int ty) const
Definition Fov.cpp:473
void syncFromLayer()
Definition Fov.cpp:308
bool cellOpaque3(int x, int y, int z) const
Definition Fov.cpp:338
void markVisible3(int x, int y, int z)
Definition Fov.cpp:366
std::unordered_map< int, std::size_t > revealerIndices
Definition Fov.cpp:247
int effectiveVerticalRange() const
Definition Fov.cpp:257
void resetVisibleKeepExplored()
Definition Fov.cpp:371
std::vector< float > elevation
Definition Fov.cpp:241
float perceptionRadiusScale
Definition Fov.cpp:237
void castLight(int ox, int oy, int radius, int row, float startSlope, float endSlope, int xx, int xy, int yx, int yy, int zSlice, bool useCone, float facingDeg, float halfAngleDeg)
Definition Fov.cpp:488
std::vector< Revealer > revealers
Definition Fov.cpp:246
bool cellOpaque2(int x, int y) const
Definition Fov.cpp:333
std::vector< Rect > buildOpaqueRects(int ox, int oy, int radius, int zSlice) const
Definition Fov.cpp:728
bool inRadius3(int ox, int oy, int oz, int x, int y, int z, int radius) const
Definition Fov.cpp:272
void resize(int w, int h, int d)
Definition Fov.cpp:286
bool angleFullyCovered(float a0, float a1, const std::vector< AngleShadow > &shadows) const
Definition Fov.cpp:541
uint64_t layerRevision
Definition Fov.cpp:225
void computeHexShadowcast(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:569
void applyAutoTopologyFromLayer()
Definition Fov.cpp:279
void addAngleShadow(std::vector< AngleShadow > &shadows, float a0, float a1) const
Definition Fov.cpp:557
void clearAllMemory()
Definition Fov.cpp:380
Revealer * findRevealer(int id)
Definition Fov.cpp:386
std::unordered_set< uint32_t > opaqueGids
Definition Fov.cpp:245
bool los2(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const
Definition Fov.cpp:468
void bindLayer(TileLayer *l)
Definition Fov.cpp:298
bool losBresenham2(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const
Definition Fov.cpp:396
std::vector< int > visibleList
Definition Fov.cpp:244
bool losHexCube(int x0, int y0, int x1, int y1, int zSlice, bool applyHeight) const
Definition Fov.cpp:434
float elevAt(int x, int y) const
Definition Fov.cpp:348
void tryMark2(int ox, int oy, int x, int y, int zSlice, bool useCone, float facingDeg, float halfAngleDeg, int radius)
Definition Fov.cpp:478
int index3(int x, int y, int z) const
Definition Fov.cpp:251
bool inBounds2(int x, int y) const
Definition Fov.cpp:252
int effectiveRadiusOf(const Revealer &r) const
Definition Fov.cpp:262
TileLayer * layer
Definition Fov.cpp:224
bool inRadius2(int ox, int oy, int x, int y, int radius) const
Definition Fov.cpp:267
void computeRevealer(const Revealer &r)
Definition Fov.cpp:875
Algorithm algorithm
Definition Fov.cpp:226
void extendVertical(const Revealer &r, int zSlice, int radius)
Definition Fov.cpp:855
bool cellOpaqueOnSlice(int x, int y, int zSlice) const
Definition Fov.cpp:343
Owning visibility-memory snapshot for the current grid/volume dimensions.
Definition Fov.h:30
std::vector< uint8_t > states
Definition Fov.h:34
Per-GID visual metadata emitted by a project-defined asset pipeline.
Definition TileLayer.h:118
glm::vec4 bounds