## 2D vision geometry. Pure, stdlib only. Ported from docs/archive/prototypes/server-vision/src/geometry.nim (M1), revised in M2. ## Move rules (swept circle, token-on-wall escape, step cap, `blocked`) live in server/moverules.nim, not here. ## Fixed in M2 (DESIGN 5.5): token exactly on a wall can move off it (moverules escape rule); the move check is the ## swept circle, not centre path + destination only; `moveBlocked` is gone from this module; cellsTouched is a scanline ## (prototype per-cell version kept test-only in tests/refold.nim, differential-tested). ## One-way sight (DESIGN 5.8, #58): `Wall.sightDir` names the blind side of `a -> b` (`left` = the `(-dy, dx)` normal) ## and `visibilityPolygon` blocks such a wall only for a viewer on that side; the other side casts rays past it. ## Movement never reads it: `moverules` gets the same wall and blocks both ways. ## Radial walls (#26): a wall lying along a sight ray (radial to the viewer) is hit by that ray at the ## nearest point of the overlap, so it contributes a vertex and the line beyond it is outside the ## polygon. Its own +-RayEps rays meet the wall's line at the viewer, so they never covered it. ## Known limitations (DESIGN 5.4 / 12): ## - boundary epsilon ambiguity: RayEps 1e-4 rad, inclusive tests; token on a vision boundary is ambiguous ## (leak checker and explored oracle use a 0.5 px neighbourhood). ## - cellsTouched keeps a prototype quirk on purpose: a cell touching the polygon only along its bbox minimum x / y line ## is not marked (every other touch is). The regression corpus has such polygons (walls on x = 256). ## - vision is O(rays x walls in bbox): bbox cull, no spatial grid (H3: not built, 5k bench met target; results/bench.log). ## Each ray tests only its own 64-gon chord (#64), not all 64; the polygon is bit-identical to the ## all-segments fan. A dense 5k layout (4096 px world, ~200 walls per vision box) costs ~0.7 ms per polygon. ## - circle range limit is an inscribed 64-gon: error <= ~0.12% of R. import std/[math, algorithm] type Vec* = tuple[x, y: float] WallDir* = enum ## Which side of the drawn `a -> b` order cannot see across (DESIGN 5.8, #47/#58). `left` is ## the `(-dy, dx)` side, the same formula as `position` (5.10) and the door-push side (5.5). ## This is a sight-only field: movement is always two-way and never reads it. wdBoth = "both" wdLeft = "left" wdRight = "right" Wall* = object ## The wall as geometry sees it. The two barrier fields are the stored switches (#57): a ## `window` stores `sightBarrier:false, movementBarrier:true`, so sight passes along its whole ## drawn length while movement and the status rules still treat it as a barrier. An open door ## passes both ways whatever the switches say (DESIGN 5.8). Both default to `true` so a wall ## built without switches (tests, fixtures) keeps the historic solid-wall behaviour. a*, b*: Vec door*, open*: bool sightDir*: WallDir sightBarrier*: bool = true movementBarrier*: bool = true const Eps* = 1e-9 # geometric tolerance (px) RayEps = 1e-4 # angular nudge past endpoints (rad) SectorEps = 1e-9 # sector-fraction tolerance for "the ray is on a 64-gon vertex" (#64) proc blocks*(w: Wall): bool = ## The movement rule: a wall blocks movement unless it is an open door or its switch is off. w.movementBarrier and not (w.door and w.open) proc blocksSight*(w: Wall): bool = ## The sight rule: a wall blocks sight unless it is an open door or its switch is off. w.sightBarrier and not (w.door and w.open) proc cross*(a, b: Vec): float = a.x * b.y - a.y * b.x proc `-`*(a, b: Vec): Vec = (a.x - b.x, a.y - b.y) proc blindTo*(w: Wall, o: Vec): bool = ## DESIGN 5.8: true when `o` stands on the side the wall's `sight_dir` names blind. One sign test ## of the viewer against the `a -> b` left normal: cross(a->b, o - a) is the signed distance along ## `(-dy, dx)`, so positive is the left side. A viewer exactly on the drawn line (|s| <= Eps) is ## blind to either direction: the predicate is never ambiguous, even though the fan's own rays ## start on the segment and a token standing on a wall already sees along it (5.5). if w.sightDir == wdBoth: return false let s = cross(w.b - w.a, o - w.a) case w.sightDir of wdBoth: false of wdLeft: s >= -Eps of wdRight: s <= Eps proc rayHit(o, d: Vec, a, b: Vec): float {.inline.} = ## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf let e = b - a let den = cross(d, e) if abs(den) < 1e-12: # Parallel. A wall on another line never meets the ray. A wall *on* the ray's line (radial to the # viewer, #26) is hit at the nearest point of the overlap: skipping the collinear case left such a # wall without a vertex and without a shadow, so the line beyond it stayed inside the polygon (a # player-view fog leak, DESIGN 3.1). Its own +-RayEps rays cannot cover it: they meet the wall's # line at the viewer (t = 0) and `t > Eps` rejects them. if abs(cross(a - o, d)) > Eps: return Inf let ta = (a.x - o.x) * d.x + (a.y - o.y) * d.y let tb = (b.x - o.x) * d.x + (b.y - o.y) * d.y let t0 = min(ta, tb) return (if t0 > Eps: t0 else: Inf) # viewer on or inside the wall: on-wall sight is ambiguous (5.5) let ao = a - o let t = cross(ao, e) / den let u = cross(ao, d) / den if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf proc visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float, circleSegs = 64): seq[Vec] = ## CCW polygon of what `o` sees, bounded by an inscribed circleSegs-gon of `radius`. var segs: seq[(Vec, Vec)] var angles: seq[float] for i in 0 ..< circleSegs: let a0 = 2 * PI * i.float / circleSegs.float let a1 = 2 * PI * (i + 1).float / circleSegs.float segs.add(((o.x + radius * cos a0, o.y + radius * sin a0), (o.x + radius * cos a1, o.y + radius * sin a1))) angles.add arctan2(sin a0, cos a0) # same (-pi,pi] range as the wall angles, else the sort scrambles the fan for w in walls: if not w.blocksSight: continue # shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid if max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue # Per-viewer one-way filter (5.8, #58), inline and after the radius cull so the hoisted wall # list stays viewer-independent: a sight-blocking one-way wall blocks only a viewer on its # blind side; the other side sees across it. Two-way walls skip the test entirely. if w.sightDir != wdBoth and not w.blindTo(o): continue segs.add((w.a, w.b)) for p in [w.a, w.b]: if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue # token on endpoint let ang = arctan2(p.y - o.y, p.x - o.x) angles.add ang angles.add ang - RayEps angles.add ang + RayEps angles.sort # Sector-limited fan (#64): a ray crosses only the chord of its own 64-gon sector, so test that # chord instead of all of them. The min is still taken over exactly the segs the old fan could # hit: at a sector boundary both meeting chords are tested (they share the vertex), and wall segs # are tested as before. `d` is built from the stored angle so every `rayHit` value, and therefore # every polygon vertex, is bit-identical to the all-segments fan (including the #26 radial case). let step = 2 * PI / circleSegs.float for ang in angles: let d: Vec = (cos ang, sin ang) var best = Inf var pos = ang while pos < 0: pos += 2 * PI while pos >= 2 * PI: pos -= 2 * PI let rpos = pos / step var sector = int(rpos) if sector >= circleSegs: sector = circleSegs - 1 best = min(best, rayHit(o, d, segs[sector][0], segs[sector][1])) let frac = rpos - sector.float if frac < SectorEps: let prev = (sector + circleSegs - 1) mod circleSegs best = min(best, rayHit(o, d, segs[prev][0], segs[prev][1])) elif frac > 1 - SectorEps: let next = (sector + 1) mod circleSegs best = min(best, rayHit(o, d, segs[next][0], segs[next][1])) for j in circleSegs ..< segs.len: best = min(best, rayHit(o, d, segs[j][0], segs[j][1])) if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best)) proc segsCross*(p, q, a, b: Vec): bool = ## inclusive segment intersection (touching and collinear overlap count) proc orient(a, b, c: Vec): int = let v = cross(b - a, c - a) if v > Eps: 1 elif v < -Eps: -1 else: 0 proc onSeg(a, b, c: Vec): bool = # c collinear with ab: within bbox? c.x >= min(a.x, b.x) - Eps and c.x <= max(a.x, b.x) + Eps and c.y >= min(a.y, b.y) - Eps and c.y <= max(a.y, b.y) + Eps let o1 = orient(p, q, a); let o2 = orient(p, q, b) let o3 = orient(a, b, p); let o4 = orient(a, b, q) if o1 != o2 and o3 != o4: return true (o1 == 0 and onSeg(p, q, a)) or (o2 == 0 and onSeg(p, q, b)) or (o3 == 0 and onSeg(a, b, p)) or (o4 == 0 and onSeg(a, b, q)) proc segDist*(p, a, b: Vec): float = let e = b - a let l2 = e.x * e.x + e.y * e.y let t = if l2 < Eps: 0.0 else: clamp(((p.x - a.x) * e.x + (p.y - a.y) * e.y) / l2, 0.0, 1.0) hypot(p.x - a.x - t * e.x, p.y - a.y - t * e.y) proc inside*(poly: openArray[Vec], p: Vec): bool = ## even-odd point-in-polygon (boundary ambiguous) var j = poly.len - 1 for i in 0 ..< poly.len: if (poly[i].y > p.y) != (poly[j].y > p.y) and p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x: result = not result j = i proc cellsTouched*(poly: openArray[Vec], cell: float): seq[(int, int)] = ## grid cells (ix, iy) overlapped by the polygon (area overlap; boundary touch within Eps included, except along the bbox minimum lines, see below), sorted by (iy, ix). ## Scanline over the cell rows, O(edges x rows spanned + cells). Per row band [by0, by1] the part of the polygon in ## the band projects on x as (a) the clipped extent of every edge plus (b) the even-odd fill spans at the band's ## lower line (a vertical line in the band that meets no edge is wholly inside or wholly outside, and inside iff ## inside at by0). Differential-tested against the prototype per-cell version (tests/refold.nim). if poly.len < 3: return var x0, y0 = Inf var x1, y1 = -Inf for p in poly: x0 = min(x0, p.x); x1 = max(x1, p.x); y0 = min(y0, p.y); y1 = max(y1, p.y) # closed touch: a value exactly on (or within Eps of) a cell line belongs to both neighbours proc lo(v, cell: float): int = int(ceil((v - Eps) / cell)) - 1 proc hi(v, cell: float): int = int(floor((v + Eps) / cell)) # prototype-compatible quirk: the grid starts at floor(bbox min), so a cell touching only the bbox minimum line is # not marked (the regression corpus has such polygons: walls on x = 256). Every other touch is inclusive. let (ix0, ix1, iy0, iy1) = (int(floor(x0 / cell)), hi(x1, cell), int(floor(y0 / cell)), hi(y1, cell)) let nx = ix1 - ix0 + 1 var hit = newSeq[bool](nx * (iy1 - iy0 + 1)) var xs = newSeq[seq[float]](iy1 - iy0 + 1) # fill crossings per row at the row's lower line proc mark(row: int, xa, xb: float) = for ix in max(lo(xa, cell), ix0) .. min(hi(xb, cell), ix1): hit[row * nx + ix - ix0] = true for i in 0 ..< poly.len: let p = poly[i]; let q = poly[(i + 1) mod poly.len] let (ylo, yhi) = (min(p.y, q.y), max(p.y, q.y)) let (exlo, exhi) = (min(p.x, q.x), max(p.x, q.x)) proc xAt(y: float): float = if p.y == q.y: exlo else: clamp(p.x + (y - p.y) * (q.x - p.x) / (q.y - p.y), exlo, exhi) for iy in max(lo(ylo, cell), iy0) .. min(hi(yhi, cell), iy1): let by0 = iy.float * cell let row = iy - iy0 if p.y == q.y: mark(row, exlo, exhi) else: let (a, b) = (xAt(max(ylo, by0)), xAt(min(yhi, by0 + cell))) mark(row, min(a, b), max(a, b)) if (p.y > by0) != (q.y > by0): xs[row].add xAt(by0) for row in 0 ..< xs.len: xs[row].sort for k in countup(0, xs[row].len - 2, 2): mark(row, xs[row][k], xs[row][k + 1]) for row in 0 ..< xs.len: for c in 0 ..< nx: if hit[row * nx + c]: result.add (ix0 + c, iy0 + row)