198 lines
8.2 KiB
Python
198 lines
8.2 KiB
Python
"""Recursive shadowcasting field-of-view.
|
|
|
|
Implemented from scratch (no third-party deps, no pygame). The public entry
|
|
point :func:`compute_fov` is a pure function: it never mutates ``tiles`` and
|
|
keeps all of its bookkeeping in local structures.
|
|
|
|
Geometry contract (shared with the rest of the engine):
|
|
* tiles are indexed ``tiles[y][x]``; ``TILE_WALL=0``, ``TILE_FLOOR=1``.
|
|
* a tile is a *wall* iff ``tiles[y][x] == 0`` (everything else is see-through
|
|
floor for the purposes of sight).
|
|
|
|
Visibility rules:
|
|
* the origin tile is always visible to itself;
|
|
* a tile is visible when an unobstructed line of sight reaches it;
|
|
* walls block sight beyond them (a wall is hit first, then casts a shadow);
|
|
* as a rendering convenience, a wall tile is itself visible whenever it is
|
|
8-adjacent to a visible floor tile (so room boundaries always show up);
|
|
* every returned tile lies within ``radius`` (Euclidean, which is a strict
|
|
refinement of the Chebyshev bound requested by the caller).
|
|
|
|
The algorithm is Björn Bergström's classic recursive shadowcasting: the view
|
|
around the origin is split into 8 octants and each octant is scanned by a
|
|
recursive routine that tracks the current illuminated slope interval
|
|
``[start, end]``. When a wall is encountered the interval is split and the far
|
|
side is explored by a child scan; once a whole row in an octant sits in shadow
|
|
the scan for that octant stops.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
__all__ = ["compute_fov"]
|
|
|
|
# Octant transformation multipliers (Björn Bergström). Each column describes one
|
|
# octant; the four rows are xx, xy, yx, yy used to map local scan offsets
|
|
# (dx, dy) into world coordinates: X = ox + dx*xx + dy*xy, Y = oy + dx*yx + dy*yy.
|
|
_OCTANTS = (
|
|
(1, 0, 0, -1, -1, 0, 0, 1),
|
|
(0, 1, -1, 0, 0, -1, 1, 0),
|
|
(0, 1, 1, 0, 0, -1, -1, 0),
|
|
(1, 0, 0, 1, -1, 0, 0, -1),
|
|
)
|
|
|
|
|
|
def compute_fov(
|
|
width: int, height: int, tiles, ox: int, oy: int, radius: int = 8
|
|
) -> set[tuple[int, int]]:
|
|
"""Return the set of ``(x, y)`` visible from ``(ox, oy)`` within ``radius``.
|
|
|
|
``tiles`` is ``list[list[int]]`` indexed ``tiles[y][x]`` where a wall is any
|
|
tile equal to ``0``. ``tiles`` is never mutated. The result always includes
|
|
the origin; every tile is within Euclidean (and therefore Chebyshev)
|
|
distance ``radius`` of the origin.
|
|
"""
|
|
visible: set[tuple[int, int]] = set()
|
|
|
|
# An origin outside the map sees nothing (and we cannot safely index tiles).
|
|
if not (0 <= ox < width and 0 <= oy < height):
|
|
return visible
|
|
|
|
def is_wall(x: int, y: int) -> bool:
|
|
# In-bounds walls block sight; out-of-bounds behaves like solid rock so
|
|
# it casts a clean shadow at the map edge.
|
|
if 0 <= x < width and 0 <= y < height:
|
|
return tiles[y][x] == 0
|
|
return True
|
|
|
|
def light(x: int, y: int) -> None:
|
|
if 0 <= x < width and 0 <= y < height:
|
|
visible.add((x, y))
|
|
|
|
# The origin is always visible to itself.
|
|
light(ox, oy)
|
|
|
|
if radius <= 0:
|
|
return visible
|
|
|
|
radius_sq = radius * radius
|
|
|
|
def cast_light(row: int, start: float, end: float,
|
|
xx: int, xy: int, yx: int, yy: int) -> None:
|
|
"""Recursively illuminate one octant over the slope window [start, end].
|
|
|
|
``start`` is the upper (steeper) slope, ``end`` the lower one; the scan
|
|
terminates once the window collapses.
|
|
"""
|
|
if start < end:
|
|
return
|
|
for j in range(row, radius + 1):
|
|
dx = -j - 1
|
|
dy = -j
|
|
blocked = False
|
|
new_start = 0.0
|
|
while dx <= 0:
|
|
dx += 1
|
|
mx = ox + dx * xx + dy * xy
|
|
my = oy + dx * yx + dy * yy
|
|
# Slopes of the left and right edges of this tile cell.
|
|
l_slope = (dx - 0.5) / (dy + 0.5)
|
|
r_slope = (dx + 0.5) / (dy - 0.5)
|
|
if start < r_slope:
|
|
# Tile sits above the lit window; keep climbing slopes.
|
|
continue
|
|
elif end > l_slope:
|
|
# Tile sits below the lit window; nothing more in this row.
|
|
break
|
|
else:
|
|
# The beam touches this cell: illuminate it if in range.
|
|
if dx * dx + dy * dy <= radius_sq:
|
|
light(mx, my)
|
|
if blocked:
|
|
# We are traversing a run of wall cells.
|
|
if is_wall(mx, my):
|
|
new_start = r_slope
|
|
continue
|
|
else:
|
|
# End of the wall run: resume from its near edge.
|
|
blocked = False
|
|
start = new_start
|
|
else:
|
|
if is_wall(mx, my) and j < radius:
|
|
# Wall after open space: spawn a child scan for the
|
|
# slope band beyond it, then mark this run blocked.
|
|
cast_light(j + 1, start, l_slope, xx, xy, yx, yy)
|
|
blocked = True
|
|
new_start = r_slope
|
|
# A fully shadowed row means deeper rows are shadowed too: stop.
|
|
if blocked:
|
|
break
|
|
|
|
for oct in range(8):
|
|
cast_light(
|
|
1, 1.0, 0.0,
|
|
_OCTANTS[0][oct], _OCTANTS[1][oct], _OCTANTS[2][oct], _OCTANTS[3][oct],
|
|
)
|
|
|
|
# Wall-adjacency rule: a wall neighbouring a visible floor tile is itself
|
|
# visible. We expand only from the lit floor tiles captured above (a single
|
|
# additive pass, not a flood fill, since the rule keys off floor not wall).
|
|
floors = [
|
|
(x, y) for (x, y) in visible
|
|
if 0 <= x < width and 0 <= y < height and tiles[y][x] != 0
|
|
]
|
|
for fx, fy in floors:
|
|
for ny in (fy - 1, fy, fy + 1):
|
|
for nx in (fx - 1, fx, fx + 1):
|
|
if (nx, ny) == (fx, fy):
|
|
continue
|
|
if 0 <= nx < width and 0 <= ny < height and tiles[ny][nx] == 0:
|
|
visible.add((nx, ny))
|
|
|
|
return visible
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def _cheby(a, b):
|
|
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Lightweight self-check mirroring the smoke-suite FOV assertions.
|
|
TILE_WALL, TILE_FLOOR, SIGHT_RADIUS = 0, 1, 8
|
|
W = H = 21
|
|
cx = cy = 10
|
|
|
|
# 1) Player walled in on all 8 sides -> only the ring + origin are visible.
|
|
tiles = [[TILE_FLOOR] * W for _ in range(H)]
|
|
for dy in (-1, 0, 1):
|
|
for dx in (-1, 0, 1):
|
|
if (dx, dy) != (0, 0):
|
|
tiles[cy + dy][cx + dx] = TILE_WALL
|
|
vis = compute_fov(W, H, tiles, cx, cy, radius=SIGHT_RADIUS)
|
|
assert (cx, cy) in vis, "origin not visible"
|
|
leaked = [t for t in vis if _cheby(t, (cx, cy)) > 1]
|
|
assert not leaked, f"walls fail to occlude: {len(leaked)} tiles leaked"
|
|
# tiles must be untouched.
|
|
assert all(tiles[y][x] == (TILE_WALL if _cheby((x, y), (cx, cy)) == 1 and (x, y) != (cx, cy) else TILE_FLOOR)
|
|
for y in range(H) for x in range(W)), "tiles mutated"
|
|
print(f"OK walled-in: sees {len(vis)} tiles, none past the ring")
|
|
|
|
# 2) Open field -> a roughly circular disc within the radius.
|
|
tiles2 = [[TILE_FLOOR] * W for _ in range(H)]
|
|
vis2 = compute_fov(W, H, tiles2, cx, cy, radius=SIGHT_RADIUS)
|
|
assert len(vis2) > 50, f"open FOV too small: {len(vis2)}"
|
|
assert all(_cheby(t, (cx, cy)) <= SIGHT_RADIUS for t in vis2), "exceeds radius"
|
|
print(f"OK open field: sees {len(vis2)} tiles within radius")
|
|
|
|
# 3) A wall pillar should not hide the floor on its far side that is reached
|
|
# by light bending around it via neighbouring octants.
|
|
tiles3 = [[TILE_FLOOR] * W for _ in range(H)]
|
|
tiles3[cy][cx + 3] = TILE_WALL # pillar due east
|
|
vis3 = compute_fov(W, H, tiles3, cx, cy, radius=SIGHT_RADIUS)
|
|
assert (cx + 3, cy) in vis3, "pillar wall itself should be visible"
|
|
assert (cx + 4, cy) not in vis3, "floor directly behind pillar hidden"
|
|
assert (cx + 4, cy + 1) in vis3, "floor beside-behind pillar visible"
|
|
print(f"OK pillar: {len(vis3)} tiles; pillar visible, far-centre occluded")
|
|
|
|
print("All FOV self-checks passed.")
|