#!/usr/bin/env python3
"""Generate the dungeon-view diagrams of docs/view/.

The figures are original schematic drawings. They use only numbers read from
the DOS START.EXE (see docs/view/ and docs/executable/), directly or through the tables of
the pages of docs/view/: the view offsets at
data-segment offset 0x22c4 and the wall drawing calls of the view setup
routine at overlay physical offsets 0x3db9a-0x3e1e8. No game graphics are
used.

Usage:
    python3 scripts/view/make_view_figures.py [output_directory]

The default output directory is docs/view/img/.
"""

import sys
from pathlib import Path

# Visible-block offsets per direction (data-segment offset 0x22c4).
OFFSETS = {
    0: [-99, -98, -97, -96, -95, -94, -93, -66, -65, -64, -63, -62, -33, -32, -31, -1, 0, 1],
    1: [-93, -61, -29, 3, 35, 67, 99, -62, -30, 2, 34, 66, -31, 1, 33, -32, 0, 32],
    2: [99, 98, 97, 96, 95, 94, 93, 66, 65, 64, 63, 62, 33, 32, 31, 1, 0, -1],
    3: [93, 61, 29, -3, -35, -67, -99, 62, 30, -2, -34, -66, 31, -1, -33, 32, 0, -32],
}

# Depth row of each visible block: 3 = three steps ahead ... 0 = party's row.
def depth(i):
    return 3 if i <= 6 else 2 if i <= 11 else 1 if i <= 14 else 0

# Wall drawing calls of the view setup, in call order:
# (block, face, x, y, width, height, mirrored); x, y, width and height are in
# 8 x 8 tiles of the 22 x 15 view. Face F = side turned towards the party,
# R = the facing + 1 side (seen on the left), L = the facing - 1 side.
REGIONS = [
    (0, 'R', -2, 3, 3, 5, False), (6, 'L', 21, 3, 3, 5, True),
    (1, 'R', 2, 3, 3, 5, False), (5, 'L', 17, 3, 3, 5, True),
    (2, 'R', 8, 3, 1, 5, False), (4, 'L', 13, 3, 1, 5, True),
    (1, 'F', -4, 3, 6, 5, False), (5, 'F', 20, 3, 6, 5, False),
    (2, 'F', 2, 3, 6, 5, False), (4, 'F', 14, 3, 6, 5, False),
    (3, 'F', 8, 3, 6, 5, False),
    (7, 'R', 0, 3, 2, 6, False), (11, 'L', 20, 3, 2, 6, True),
    (8, 'R', 6, 2, 2, 8, False), (10, 'L', 14, 2, 2, 8, True),
    (8, 'F', -4, 2, 10, 8, False), (10, 'F', 16, 2, 10, 8, False),
    (9, 'F', 6, 2, 10, 8, False),
    (12, 'R', 3, 1, 3, 12, False), (14, 'L', 16, 1, 3, 12, True),
    (12, 'F', -13, 1, 16, 12, False), (14, 'F', 19, 1, 16, 12, False),
    (13, 'F', 3, 1, 16, 12, False),
    (15, 'R', 0, 0, 3, 15, False), (17, 'L', 19, 0, 3, 15, True),
]

VIEW_W, VIEW_H = 22, 15  # tiles

# Object anchor offsets per (view block, spot), data-segment offset 0x23ec:
# (x, y) added to (88, 124) for floor items and (88, 127) for monsters.
# Spots: 0 far left, 1 far right, 2 near left, 3 near right, 4 centre.
SPOTS = [
    [(-111, -63), (-95, -63), (-139, -59), (-117, -59), (-120, -61)],
    [(-76, -63), (-60, -63), (-95, -59), (-74, -59), (-80, -61)],
    [(-43, -63), (-27, -63), (-53, -59), (-31, -59), (-40, -61)],
    [(-8, -63), (8, -63), (-10, -59), (10, -59), (0, -61)],
    [(27, -63), (43, -63), (31, -59), (53, -59), (40, -61)],
    [(60, -63), (76, -63), (74, -59), (95, -59), (80, -61)],
    [(95, -63), (111, -63), (117, -59), (139, -59), (120, -61)],
    [(-118, -53), (-92, -53), (-152, -45), (-120, -45), (-118, -50)],
    [(-66, -53), (-40, -53), (-84, -45), (-51, -45), (-59, -50)],
    [(-13, -53), (13, -53), (-16, -45), (16, -45), (0, -50)],
    [(40, -53), (66, -53), (51, -45), (84, -45), (59, -50)],
    [(92, -53), (118, -53), (120, -45), (152, -45), (118, -50)],
    [(-110, -35), (-67, -35), (-140, -22), (-83, -22), (-98, -30)],
    [(-22, -35), (22, -35), (-27, -22), (27, -22), (0, -30)],
    [(67, -35), (110, -35), (83, -22), (140, -22), (98, -30)],
    [(-128, -4), (128, -4), (-128, -66), (128, -66), (128, 0)],
    [(-38, -4), (38, -4), (-38, -66), (38, -66), (0, 0)],
    [(-128, -4), (128, -4), (-128, -66), (128, -66), (128, 0)],
]
# Item scale steps by depth class (0 = three steps ahead ... 3 = party's row)
# and spot 0-3 (data-segment offset 0x478); -1 = not drawn.
ITEM_SCALE = [[-1, -1, 3, 3], [2, 2, 2, 2], [1, 1, 1, 1], [0, 0, -1, -1]]

# Reference palette (dataviz skill): ordinal blue ramp for depth, steps
# 250/400/550/700, far to near; two categorical slots for face kinds.
SURFACE = '#fcfcfb'
INK = '#0b0b0b'
INK2 = '#52514e'
MUTED = '#8a8984'
GRID = '#dddcd7'
DEPTH_FILL = {3: '#86b6ef', 2: '#3987e5', 1: '#1c5cab', 0: '#0d366b'}
DEPTH_INK = {3: INK, 2: INK, 1: '#ffffff', 0: '#ffffff'}
DEPTH_NAME = {3: 'three steps ahead', 2: 'two steps ahead',
              1: 'one step ahead', 0: "party's row"}
FRONT = '#2a78d6'
SIDE = '#eb6834'
FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
MINUS = '−'


def num(v):
    return ('+' if v > 0 else MINUS if v < 0 else '') + str(abs(v))


class Svg:
    def __init__(self, w, h, title, desc):
        self.w, self.h = w, h
        self.parts = [
            f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" '
            f'width="{w}" height="{h}" role="img" font-family="{FONT}">',
            f'<title>{title}</title>', f'<desc>{desc}</desc>',
            f'<rect x="0.5" y="0.5" width="{w - 1}" height="{h - 1}" rx="10" '
            f'fill="{SURFACE}" stroke="{GRID}"/>',
        ]

    def add(self, s):
        self.parts.append(s)

    def text(self, x, y, s, size=12, fill=INK, weight='normal', anchor='middle', halo=False):
        h = f' stroke="{SURFACE}" stroke-width="3" paint-order="stroke"' if halo else ''
        self.add(f'<text x="{x:g}" y="{y:g}" font-size="{size}" fill="{fill}" '
                 f'font-weight="{weight}" text-anchor="{anchor}" '
                 f'dominant-baseline="central"{h}>{s}</text>')

    def rect(self, x, y, w, h, fill='none', stroke='none', sw=1, dash=None, extra=''):
        d = f' stroke-dasharray="{dash}"' if dash else ''
        self.add(f'<rect x="{x:g}" y="{y:g}" width="{w:g}" height="{h:g}" fill="{fill}" '
                 f'stroke="{stroke}" stroke-width="{sw}"{d} {extra}/>')

    def line(self, x1, y1, x2, y2, stroke, sw=1, dash=None, cap='butt'):
        d = f' stroke-dasharray="{dash}"' if dash else ''
        self.add(f'<line x1="{x1:g}" y1="{y1:g}" x2="{x2:g}" y2="{y2:g}" stroke="{stroke}" '
                 f'stroke-width="{sw}" stroke-linecap="{cap}"{d}/>')

    def poly(self, pts, fill, stroke='none', sw=1):
        p = ' '.join(f'{x:g},{y:g}' for x, y in pts)
        self.add(f'<polygon points="{p}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>')

    def save(self, path):
        self.add('</svg>')
        Path(path).write_text('\n'.join(self.parts) + '\n', encoding='utf-8')


def arrow(svg, cx, cy, direction, size, color):
    # Triangle pointing in a map direction (0 north/up, 1 east/right, ...).
    pts = {0: [(0, -1), (0.8, 0.7), (-0.8, 0.7)], 1: [(1, 0), (-0.7, 0.8), (-0.7, -0.8)],
           2: [(0, 1), (-0.8, -0.7), (0.8, -0.7)], 3: [(-1, 0), (0.7, -0.8), (0.7, 0.8)]}[direction]
    svg.poly([(cx + px * size, cy + py * size) for px, py in pts], color)


def map_panel(svg, ox, oy, direction, cell, title):
    """Top-down map, north up, of the 18 blocks visible for a direction."""
    pos = {}
    for i, o in enumerate(OFFSETS[direction]):
        dr = round(o / 32)
        pos[(o - 32 * dr, dr)] = i
    cols = sorted({c for c, _ in pos})
    rows = sorted({r for _, r in pos})
    svg.text(ox + len(cols) * cell / 2, oy - 22, title, 14, INK, 'bold')
    for r_i, r in enumerate(rows):
        for c_i, c in enumerate(cols):
            x, y = ox + c_i * cell, oy + r_i * cell
            i = pos.get((c, r))
            if i is None:
                svg.rect(x + 1, y + 1, cell - 2, cell - 2, 'none', GRID, 1, '3 3')
                continue
            d = depth(i)
            svg.rect(x + 1, y + 1, cell - 2, cell - 2, DEPTH_FILL[d], SURFACE, 2)
            ink = DEPTH_INK[d]
            if i == 16:
                svg.text(x + cell / 2, y + cell * 0.30, '16', 15, ink, 'bold')
                arrow(svg, x + cell / 2, y + cell * 0.66, direction, cell * 0.14, ink)
            else:
                svg.text(x + cell / 2, y + cell * 0.40, f'{i:02d}', 16, ink, 'bold')
                svg.text(x + cell / 2, y + cell * 0.70, num(OFFSETS[direction][i]), 11, ink)
    # compass
    cx, cy = ox + len(cols) * cell + 22, oy + 14
    arrow(svg, cx, cy, 0, 8, INK2)
    svg.text(cx, cy + 18, 'N', 12, INK2, 'bold')
    return len(cols) * cell, len(rows) * cell


def figure_visible_blocks(out):
    cell = 46
    ox, oy = 130, 70
    svg = Svg(700, 470, 'The 18 visible blocks',
              'Top-down maps, north up. Left: party facing north; right: party facing east. '
              'Each visible block shows its number in the view and its block-index offset '
              'from the party; colors give the distance ahead.')
    w, h = map_panel(svg, ox, oy, 0, cell, 'Facing north (direction 0)')
    for r_i, d in enumerate((3, 2, 1, 0)):
        svg.text(ox - 10, oy + r_i * cell + cell / 2, DEPTH_NAME[d], 12, INK2, anchor='end')
    # left / right of the party
    ly = oy + h + 16
    svg.text(ox + 2 * cell, ly, '\u2190 left: facing \u2212 1', 12, INK2, anchor='end')
    svg.text(ox + 5 * cell, ly, 'right: facing + 1 \u2192', 12, INK2, anchor='start')
    map_panel(svg, 520, oy, 1, 34, 'Facing east (direction 1)')
    y = oy + 7 * 34 + 40
    for k, line in enumerate((
            'Large numbers: index in the view (00 = far left, 16 = party).',
            'Small numbers: offset added to the party\u2019s block index (one row = 32 blocks).',
            'The numbering turns with the party: 00 is always the farthest block on its left.',
            'Dashed squares: not drawn in the view.')):
        svg.text(40, y + 20 * k, line, 12, INK2, anchor='start')
    ly = 445
    for k, d in enumerate((3, 2, 1, 0)):
        xx = 40 + k * 160
        svg.rect(xx, ly - 8, 16, 16, DEPTH_FILL[d])
        svg.text(xx + 22, ly, DEPTH_NAME[d], 12, INK2, anchor='start')
    svg.save(out / 'view-visible-blocks.svg')


def figure_faces(out):
    cell = 64
    ox, oy = 40, 70
    svg = Svg(700, 470, 'Which face of each visible block is drawn',
              'Top-down map, party facing north. Thick solid lines: faces drawn as seen '
              'from the front. Thick dashed lines: faces drawn on the left or right of the view.')
    svg.text(ox + 3.5 * cell, oy - 30, 'Faces drawn, party facing north', 14, INK, 'bold')
    pos = {}
    for i, o in enumerate(OFFSETS[0]):
        dr = round(o / 32)
        pos[i] = (o - 32 * dr + 3, dr + 3)
    for c in range(7):
        for r in range(4):
            x, y = ox + c * cell, oy + r * cell
            i = next((k for k, p in pos.items() if p == (c, r)), None)
            if i is None:
                svg.rect(x + 1, y + 1, cell - 2, cell - 2, 'none', GRID, 1, '3 3')
            else:
                svg.rect(x + 1, y + 1, cell - 2, cell - 2, '#f1f0ec', GRID, 1)
                svg.text(x + cell / 2, y + cell / 2 - (8 if i == 16 else 0), f'{i:02d}', 15, INK, 'bold')
                if i == 16:
                    arrow(svg, x + cell / 2, y + cell / 2 + 16, 0, 8, INK2)
    drawn = {(b, f) for b, f, *_ in REGIONS}
    for (b, f) in sorted(drawn):
        c, r = pos[b]
        x, y = ox + c * cell, oy + r * cell
        # each line sits just inside the block it belongs to
        if f == 'F':
            svg.line(x + 10, y + cell - 9, x + cell - 10, y + cell - 9, FRONT, 6, cap='round')
        elif f == 'R':
            svg.line(x + cell - 9, y + 10, x + cell - 9, y + cell - 10, SIDE, 6, '9 6', 'round')
        else:
            svg.line(x + 9, y + 10, x + 9, y + cell - 10, SIDE, 6, '9 6', 'round')
    # compass
    arrow(svg, ox + 7 * cell + 26, oy + 10, 0, 8, INK2)
    svg.text(ox + 7 * cell + 26, oy + 28, 'N', 12, INK2, 'bold')
    y = oy + 4 * cell + 34
    svg.line(ox, y, ox + 40, y, FRONT, 6, cap='round')
    svg.text(ox + 52, y, 'front face: the side turned towards the party', 12, INK2, anchor='start')
    svg.line(ox, y + 26, ox + 40, y + 26, SIDE, 6, '9 6', 'round')
    svg.text(ox + 52, y + 26, 'side face: a block on the left shows its right-hand face, and the reverse',
             12, INK2, anchor='start')
    svg.text(ox, y + 52, 'Nothing is drawn for the party’s own block (16);', 12, INK2, anchor='start')
    svg.text(ox, y + 70, 'blocks 00, 06, 07, 11, 15 and 17 show only a side face.', 12, INK2, anchor='start')
    svg.save(out / 'view-faces.svg')


def figure_screen(out):
    t = 12                      # pixels per tile in the figure
    vw, vh = VIEW_W * t, VIEW_H * t
    margin = 2 * t
    pw, ph = vw + 2 * margin, vh + 46
    groups = [
        ('Three steps ahead: side faces', 3, 'RL'), ('Three steps ahead: front faces', 3, 'F'),
        ('Two steps ahead: side faces', 2, 'RL'), ('Two steps ahead: front faces', 2, 'F'),
        ('One step ahead: side faces', 1, 'RL'), ('One step ahead: front faces', 1, 'F'),
        ("Party's row: side faces", 0, 'RL'), ('Floor and ceiling backdrop', None, ''),
    ]
    W = 2 * pw + 60
    H = 4 * (ph + 18) + 110
    svg = Svg(W, H, 'Where each visible block is drawn in the view',
              'Eight panels, each the 22 by 15 tile view. Rectangles mark the tile areas filled '
              'for each block face, grouped by distance; parts outside the view are dashed.')
    svg.add('<defs>' + ''.join(
        f'<clipPath id="v{k}"><rect x="{20 + (k % 2) * (pw + 20) + margin}" '
        f'y="{40 + (k // 2) * (ph + 18) + 30}" width="{vw}" height="{vh}"/></clipPath>'
        f'<clipPath id="m{k}"><rect x="{20 + (k % 2) * (pw + 20)}" '
        f'y="{40 + (k // 2) * (ph + 18) + 30}" width="{pw}" height="{vh}"/></clipPath>'
        for k in range(8)) + '</defs>')
    for k, (title, d, faces) in enumerate(groups):
        px = 20 + (k % 2) * (pw + 20)
        py = 40 + (k // 2) * (ph + 18)
        vx, vy = px + margin, py + 30
        svg.text(px + pw / 2, py + 12, title, 13, INK, 'bold')
        for c in range(1, VIEW_W):
            svg.line(vx + c * t, vy, vx + c * t, vy + vh, '#eeede9', 1)
        for r in range(1, VIEW_H):
            svg.line(vx, vy + r * t, vx + vw, vy + r * t, '#eeede9', 1)
        if d is None:
            svg.rect(vx, vy, vw, vh, '#cfcec9')
            svg.text(vx + vw / 2, vy + vh / 2 - 9, 'whole view, 22 × 15 tiles', 12, INK, 'bold')
            svg.text(vx + vw / 2, vy + vh / 2 + 9, 'mirrored on every other block', 11, INK2)
        for (b, f, x, y, w, h, m) in REGIONS:
            if d is None or depth(b) != d or f not in faces:
                continue
            rx, ry, rw, rh = vx + x * t, vy + y * t, w * t, h * t
            svg.add(f'<g clip-path="url(#v{k})">')
            svg.rect(rx, ry, rw, rh, DEPTH_FILL[d], SURFACE, 1.5)
            svg.add('</g>')
            svg.add(f'<g clip-path="url(#m{k})">')
            svg.rect(rx, ry, rw, rh, 'none', INK2, 1, '4 3')
            svg.add('</g>')
            # label in the visible part, or below it when that part is narrow
            x0, x1 = max(x, 0), min(x + w, VIEW_W)
            cx = vx + (x0 + x1) / 2 * t
            label = f'{b:02d} {f}' + ('↔' if m else '')
            if x1 - x0 >= 3:
                svg.text(cx, ry + rh / 2, label, 11, DEPTH_INK[d], 'bold')
            else:
                svg.line(cx, ry + rh, cx, ry + rh + 14, INK2, 1)
                svg.text(min(max(cx, vx + 16), vx + vw - 16), ry + rh + 22, label, 10, INK, 'bold')
        svg.rect(vx, vy, vw, vh, 'none', INK2, 1.5)
    y = H - 56
    svg.text(20, y, 'Tiles are 8 × 8 pixels: the view is 176 × 120 pixels. '
             'F = front face, R = right-hand face (blocks on the left),', 12, INK2, anchor='start')
    svg.text(20, y + 18, 'L = left-hand face (blocks on the right), ↔ = drawn mirrored. '
             'Dashed outlines: the full area, partly outside the view.', 12, INK2, anchor='start')
    svg.text(20, y + 36, 'Walls are drawn far to near, so nearer areas cover farther ones '
             'wherever their tiles are not empty.', 12, INK2, anchor='start')
    svg.save(out / 'view-screen-regions.svg')


def figure_corridor(out):
    s = 2.5                      # figure pixels per view pixel
    ox, oy = 30, 60
    W, H = 700, int(120 * s) + oy + 96
    svg = Svg(W, H, 'Sketch: a corridor ending in a wall',
              'Sketch of the view when the party stands in a corridor three blocks long that '
              'ends in a wall. Each face is labeled with the visible block it belongs to.')
    svg.text(ox + 88 * s, oy - 30, 'Sketch: a corridor three blocks long, ending in a wall', 14, INK, 'bold')
    P = lambda pts: [(ox + x * s, oy + y * s) for x, y in pts]
    # planes from the front-face areas: x0, x1, ytop, ybottom
    D = [(0, 176, 0, 120), (24, 152, 8, 104), (48, 128, 16, 80), (64, 112, 24, 64)]
    svg.poly(P([(0, 0), (176, 0), (112, 24), (64, 24)]), '#e9e8e4')            # ceiling
    floors = [(16, 0), (13, 1), (9, 2)]
    for b, k in floors:
        a, z = D[k], D[k + 1]
        svg.poly(P([(a[0], a[3]), (a[1], a[3]), (z[1], z[3]), (z[0], z[3])]),
                 '#dedcd6' if k % 2 == 0 else '#d3d1cb', SURFACE, 1.5)
        cy = (a[3] + z[3]) / 2
        svg.text(ox + 88 * s, oy + cy * s, f'{b:02d}' + (' (party)' if b == 16 else '') + ' floor',
                 12, INK, 'bold')
    sides = [(15, 'R', 0, 0), (17, 'L', 0, 0), (12, 'R', 1, 1), (14, 'L', 1, 1),
             (8, 'R', 2, 2), (10, 'L', 2, 2)]
    for b, f, k, dd in sides:
        a, z = D[k], D[k + 1]
        if f == 'R':
            pts = [(a[0], a[2]), (z[0], z[2]), (z[0], z[3]), (a[0], a[3])]
        else:
            pts = [(a[1], a[2]), (z[1], z[2]), (z[1], z[3]), (a[1], a[3])]
        d = depth(b)
        svg.poly(P(pts), DEPTH_FILL[d], SURFACE, 1.5)
        cx = sum(p[0] for p in pts) / 4
        svg.text(ox + cx * s, oy + 60 * s - 8, f'{b:02d}', 14, DEPTH_INK[d], 'bold')
        svg.text(ox + cx * s, oy + 60 * s + 10, f, 12, DEPTH_INK[d], 'bold')
    a = D[3]
    svg.rect(ox + a[0] * s, oy + a[2] * s, (a[1] - a[0]) * s, (a[3] - a[2]) * s, DEPTH_FILL[3], SURFACE, 1.5)
    svg.text(ox + 88 * s, oy + 44 * s - 8, '03', 14, INK, 'bold')
    svg.text(ox + 88 * s, oy + 44 * s + 10, 'F', 12, INK, 'bold')
    svg.rect(ox, oy, 176 * s, 120 * s, 'none', INK2, 1.5)
    # small top-down key on the right
    kx, ky, c = ox + 176 * s + 36, oy + 20, 34
    svg.text(kx + 1.5 * c, ky - 14, 'Seen from above', 12, INK, 'bold')
    layout = {(0, 1): 3, (1, 0): 8, (1, 1): 9, (1, 2): 10, (2, 0): 12, (2, 1): 13, (2, 2): 14,
              (3, 0): 15, (3, 1): 16, (3, 2): 17}
    for (r, cc), b in layout.items():
        d = depth(b)
        fill = DEPTH_FILL[d] if b in (3, 8, 10, 12, 14, 15, 17) else '#e9e8e4'
        ink = DEPTH_INK[d] if fill != '#e9e8e4' else INK
        svg.rect(kx + cc * c + 1, ky + r * c + 1, c - 2, c - 2, fill, GRID, 1)
        svg.text(kx + cc * c + c / 2, ky + r * c + c / 2, f'{b:02d}', 11, ink, 'bold')
    arrow(svg, kx + 1.5 * c, ky + 3 * c + c * 0.80, 0, 5, INK2)
    svg.text(kx, ky + 4 * c + 22, 'Colored: blocks whose', 11, INK2, anchor='start')
    svg.text(kx, ky + 4 * c + 38, 'faces are visible here.', 11, INK2, anchor='start')
    svg.text(kx, ky + 4 * c + 58, 'Gray: open blocks of', 11, INK2, anchor='start')
    svg.text(kx, ky + 4 * c + 74, 'the corridor.', 11, INK2, anchor='start')
    svg.text(ox, H - 58, 'Sketch: each face is a plain shape inside the tile area the game uses for it;', 12, INK2, anchor='start')
    svg.text(ox, H - 40, 'the game fills that area from the level’s wall graphics. Floor labels only show', 12, INK2, anchor='start')
    svg.text(ox, H - 22, 'where each block lies: the floor and ceiling are one backdrop image.', 12, INK2, anchor='start')
    svg.save(out / 'view-corridor.svg')


def figure_object_spots(out):
    s = 2.15
    x0, x1, y0, y1 = -60, 236, 0, 132       # view pixels shown
    ox, oy = 32, 60
    W, H = 700, int((y1 - y0) * s) + oy + 150
    svg = Svg(W, H, 'Where floor items are placed',
              'The 176 by 120 view with the five floor spots of each visible block: four corners '
              'and a centre. Dots are the bottom-centre points where floor items are anchored; '
              'colors give the distance; hollow dots are spots where items are not drawn.')
    svg.text(W / 2, 28, 'Floor spots of the 18 visible blocks (item anchor points)', 14, INK, 'bold')
    X = lambda x: ox + (x - x0) * s
    Y = lambda y: oy + (y - y0) * s
    svg.rect(X(x0), Y(y0), (x1 - x0) * s, (y1 - y0) * s, '#f3f2ef')
    svg.rect(X(0), Y(0), 176 * s, 120 * s, SURFACE, INK2, 1.5)
    for c in range(0, 177, 8):
        svg.line(X(c), Y(0), X(c), Y(120), '#eeede9', 1)
    for r in range(0, 121, 8):
        svg.line(X(0), Y(r), X(176), Y(r), '#eeede9', 1)
    svg.text(X(0), Y(0) - 10, '(0, 0)', 11, INK2, anchor='start')
    svg.text(X(176), Y(120) + 12, '(176, 120)', 11, INK2, anchor='end')
    for i in range(18):
        d = depth(i)
        cls = {3: 0, 2: 1, 1: 2, 0: 3}[d]          # depth class of the scale table
        pts = [(88 + x, 124 + y) for x, y in SPOTS[i]]
        if d > 0:                                   # rows ahead: outline of the floor
            quad = [pts[0], pts[1], pts[3], pts[2]]
            svg.poly([(X(x), Y(y)) for x, y in quad], 'none', DEPTH_FILL[d], 1.2)
        for k, (x, y) in enumerate(pts[:4]):
            sc = ITEM_SCALE[cls][k]
            if d == 0 and sc < 0:
                continue                            # behind the viewer: never drawn
            fill = DEPTH_FILL[d] if sc >= 0 else SURFACE
            svg.add(f'<circle cx="{X(x):g}" cy="{Y(y):g}" r="4" fill="{fill}" '
                    f'stroke="{DEPTH_FILL[d]}" stroke-width="1.6"/>')
        if i in (15, 17):
            continue                                # spots outside the view
        cx, cy = pts[4]
        svg.add(f'<circle cx="{X(cx):g}" cy="{Y(cy):g}" r="3" fill="{INK2}"/>')
        svg.text(X(cx), Y(cy) - 11, f'{i:02d}', 11, INK, 'bold', halo=True)
    ly = Y(y1) + 30
    for k, d in enumerate((3, 2, 1, 0)):
        xx = ox + k * 160
        svg.add(f'<circle cx="{xx + 6}" cy="{ly}" r="5" fill="{DEPTH_FILL[d]}"/>')
        svg.text(xx + 16, ly, DEPTH_NAME[d], 12, INK2, anchor='start')
    svg.text(ox, ly + 24, 'Each outline joins the four corner spots of one block: far left, far right, near right,', 12, INK2, anchor='start')
    svg.text(ox, ly + 42, 'near left. Small dark dot: the centre spot (4), with the block number.', 12, INK2, anchor='start')
    svg.text(ox, ly + 60, 'Hollow dots: corner spots where floor items are not drawn.', 12, INK2, anchor='start')
    svg.text(ox, ly + 78, 'Party\u2019s row: only the two front spots are drawn; those of 15 and 17 lie outside the view.', 12, INK2, anchor='start')
    svg.save(out / 'view-object-spots.svg')


# --------------------------------------------------------------------------- pages split in 2026
# Values transcribed from the pages of docs/view/ (themselves read from START.EXE).
FLY_SCALE = {1: [-1, -1, -1, 3], 2: [-1, -1, 3, 3], 3: [-1, -1, 3, 3], 4: [-1, -1, 3, 3], 5: [-1, -1, 3, -1],
             8: [2, 2, 2, 2], 9: [2, 2, 2, 2], 10: [2, 2, 2, 2], 12: [-1, 1, -1, 1], 13: [1, 1, 1, 1],
             14: [1, -1, 1, -1], 16: [0, 0, -1, -1]}
DOOR = {3: (30, 59, 59, 8), 2: (24, 71, 71, 12), 1: (16, 86, 86, 18)}   # frame top, frame bottom, bottom, raise
FRAMES_NORTH = [4, -2, 1, 3]        # normal table, animation step 0, party facing north; monster facing N, E, S, W


def figure_pixels(out):
    W, H = 700, 330
    svg = Svg(W, H, 'From tiles to pixels',
              'Left: the 22 by 15 tile grid of the view, 176 by 120 pixels in the top-left corner of the screen; '
              'tile (3, 2) covers the pixels x 24 to 31 and y 16 to 23. Right: how one tile is drawn from its two '
              'layers. A wall entry of 0 shows the backdrop tile; a wall entry with the over-backdrop bit draws '
              'the backdrop, then the wall block over it, skipping colour 0; any other wall entry draws the wall '
              'block alone.')
    s = 12
    ox, oy = 30, 60
    for c in range(VIEW_W):
        for r in range(VIEW_H):
            hit = (c, r) == (3, 2)
            svg.rect(ox + c * s, oy + r * s, s - 1, s - 1, FRONT if hit else '#f1f0ec')
    svg.text(ox, oy - 12, 'The view: 22 × 15 tiles of 8 × 8 pixels', 12, INK, 'bold', 'start')
    svg.text(ox, oy + VIEW_H * s + 16, 'Tile (3, 2): x 24 to 31, y 16 to 23', 11, INK2, anchor='start')
    svg.text(ox, oy + VIEW_H * s + 32, 'tile (c, r) starts at pixel (8c, 8r)', 11, INK2, anchor='start')
    rx = 340
    svg.text(rx, oy - 12, 'One tile, from its two layers', 12, INK, 'bold', 'start')
    rows = [('wall entry 0', 'backdrop tile only', ['#d8d6d0', None]),
            ('over-backdrop bit set', 'backdrop, then the wall block over it (colour 0 skipped)', ['#d8d6d0', FRONT]),
            ('any other entry', 'the wall block alone', [None, FRONT])]
    for k, (cond, result, layers) in enumerate(rows):
        y = oy + 10 + k * 62
        svg.rect(rx, y, 40, 40, layers[0] or SURFACE, GRID)
        if layers[1]:
            if layers[0]:
                svg.add(f'<polygon points="{rx},{y + 40} {rx + 40},{y} {rx + 40},{y + 40}" fill="{FRONT}"/>')
            else:
                svg.rect(rx, y, 40, 40, FRONT, GRID)
        svg.text(rx + 54, y + 12, cond, 12, INK, 'bold', 'start')
        svg.text(rx + 54, y + 30, result, 11, INK2, anchor='start')
    svg.save(out / 'view-pixels.svg')


def figure_item_scale(out):
    W, H = 700, 370
    svg = Svg(W, H, 'Scale steps of items and flying objects',
              'Left: the scale steps of an item on the floor by row of distance and spot; three steps ahead the '
              'far spots are not drawn and the near spots take 3 steps; two steps ahead 2 steps; one step ahead '
              '1 step; on the party’s row the far spots are drawn at full size and the near spots not at all. '
              'Right: the scale steps of a flying object by visible block and spot; a dash means not drawn.')
    shade = {-1: '#f1f0ec', 0: '#0d366b', 1: '#1c5cab', 2: '#3987e5', 3: '#86b6ef'}
    ink = {-1: MUTED, 0: '#ffffff', 1: '#ffffff', 2: INK, 3: INK}
    spots = ['far L', 'far R', 'near L', 'near R']
    ox, oy, cw, ch = 150, 84, 40, 30
    svg.text(30, 56, 'Items on the floor', 13, INK, 'bold', 'start')
    for j, s in enumerate(spots):
        svg.text(ox + j * cw + cw / 2, oy - 10, s, 10, INK2)
    for i, d in enumerate((3, 2, 1, 0)):
        svg.text(ox - 8, oy + i * ch + ch / 2, DEPTH_NAME[d], 11, INK2, anchor='end')
        for j in range(4):
            v = ITEM_SCALE[i][j]
            svg.rect(ox + j * cw, oy + i * ch, cw - 2, ch - 2, shade[v])
            svg.text(ox + j * cw + cw / 2 - 1, oy + i * ch + ch / 2 - 1, '—' if v < 0 else str(v), 12, ink[v], 'bold')
    fx, fy, fw = 420, 84, 46
    svg.text(fx - 60, 56, 'Flying objects, by block', 13, INK, 'bold', 'start')
    for j, s in enumerate(spots):
        svg.text(fx + j * fw + fw / 2, fy - 10, s, 10, INK2)
    for i, (b, row) in enumerate(FLY_SCALE.items()):
        y = fy + i * 18
        svg.text(fx - 8, y + 8, f'{b:02d}', 10, INK2, anchor='end')
        for j, v in enumerate(row):
            svg.rect(fx + j * fw, y, fw - 2, 16, shade[v])
            svg.text(fx + j * fw + fw / 2 - 1, y + 8, '—' if v < 0 else str(v), 10, ink[v], 'bold')
    svg.text(30, H - 40, 'Each step keeps two pixels out of three. Blocks not listed never show flying objects.', 11, INK2, anchor='start')
    svg.text(30, H - 22, 'Items three steps ahead on the far spots and on the near spots of the party’s row are not drawn.', 11, INK2, anchor='start')
    svg.save(out / 'view-item-scale.svg')


def figure_monster_frames(out):
    W, H = 700, 270
    svg = Svg(W, H, 'Which frame a monster shows',
              'For a party facing north, at animation step 0 of the normal frame table: a monster facing north, '
              'away from the party, shows frame 4; facing east, frame 2 mirrored; facing south, towards the party, '
              'frame 1; facing west, frame 3. Reading frame 1 as the front view, 4 as the back and 2 and 3 as the '
              'sides is inferred from the frame tables.')
    svg.text(30, 30, 'Which frame a monster shows, party facing north', 14, INK, 'bold', 'start')
    svg.text(30, 50, 'Normal frame table, animation step 0; the view of each frame is inferred.', 12, INK2, anchor='start')
    names = ['north', 'east', 'south', 'west']
    seen = {4: 'from behind', 2: 'from a side', 1: 'from the front', 3: 'from a side'}
    for k, f in enumerate(FRAMES_NORTH):
        x = 40 + k * 160
        svg.rect(x, 74, 140, 130, '#f1f0ec', GRID, 1)
        arrow(svg, x + 70, 120, k, 22, FRONT)
        svg.text(x + 70, 168, f'monster faces {names[k]}', 11, INK2)
        svg.text(x + 70, 188, f'frame {abs(f)}' + (', mirrored' if f < 0 else ''), 12, INK, 'bold')
        svg.text(x + 70, 222, seen[abs(f)], 11, INK2)
    arrow(svg, 350, 248, 0, 8, INK2)
    svg.text(364, 248, 'the party looks north, up the page', 11, INK2, anchor='start')
    svg.save(out / 'view-monster-frames.svg')


def figure_door_rows(out):
    W, H = 700, 420
    svg = Svg(W, H, 'Where a rising door is drawn',
              'For a rising door three, two and one step ahead: the rows of its frame in the 120-row view (30 to 59, '
              '24 to 71, 16 to 86), and the row of its bottom edge at each opening step, from closed (59, 71, 86) '
              'upward by 8, 12 or 18 rows per step. Parts outside the frame are not drawn.')
    svg.text(30, 30, 'Where a rising door is drawn', 14, INK, 'bold', 'start')
    svg.text(30, 50, 'Bottom edge of the door at opening steps 0 (closed) to 4; rows of the 120-row view.', 12, INK2, anchor='start')
    top, k = 70, 2.2
    Y = lambda r: top + r * k
    ax = 70
    svg.line(ax, Y(0), ax, Y(120), MUTED, 1)
    for r in range(0, 121, 20):
        svg.line(ax - 4, Y(r), ax, Y(r), MUTED, 1)
        svg.text(ax - 8, Y(r), str(r), 10, INK2, anchor='end')
    for i, d in enumerate((3, 2, 1)):
        x = 140 + i * 180
        ft, fb, bottom, raise_ = DOOR[d]
        svg.rect(x, Y(0), 120, 120 * k, '#f6f5f2', GRID)
        svg.rect(x, Y(ft), 120, (fb - ft) * k, DEPTH_FILL[d], 'none', 1, None, 'fill-opacity="0.35"')
        svg.text(x + 60, Y(120) + 16, DEPTH_NAME[d], 11, INK, 'bold')
        svg.text(x + 60, Y(120) + 32, f'frame rows {ft}–{fb}', 10, INK2)
        for n in range(5):
            r = bottom - n * raise_
            inside = r >= ft
            svg.line(x + 10, Y(r), x + 110, Y(r), FRONT if inside else MUTED, 2.5 if inside else 1.2,
                     None if inside else '4 3')
            svg.text(x + 124, Y(r), f'{n}', 10, INK2 if inside else MUTED, anchor='start')
    svg.save(out / 'view-door-rows.svg')


def figure_scale_steps(out):
    W, H = 700, 300
    sizes = [(64, 48)]
    for _ in range(3):
        w, h = sizes[-1]
        cols = -(-2 * (w // 8) // 3)
        sizes.append((8 * cols, (2 * (h + 1)) // 3))
    assert sizes == [(64, 48), (48, 32), (32, 22), (24, 15)], sizes
    base = (42, 120, 214)
    colours = [base]
    for _ in range(3):
        colours.append(tuple(c - ((c * 84) >> 8) for c in colours[-1]))
    svg = Svg(W, H, 'Scale steps and darkening',
              'A shape of 64 by 48 pixels and the same shape after one, two and three scale steps: 48 by 32, 32 by 22 '
              'and 24 by 15 pixels; widths are counted in 8-pixel columns. Each step also darkens the shape by '
              'moving every colour about a third of the way toward black and picking the closest other colour of '
              'the palette; the colours shown here only illustrate the darkening.')
    svg.text(30, 30, 'Scale steps and darkening', 14, INK, 'bold', 'start')
    svg.text(30, 50, 'Each step keeps two pixels out of three and darkens the shape by one step.', 12, INK2, anchor='start')
    s, x, base_y = 2.4, 40, 220
    for n, ((w, h), c) in enumerate(zip(sizes, colours)):
        svg.rect(x, base_y - h * s, w * s, h * s, 'rgb(%d,%d,%d)' % c)
        svg.text(x + w * s / 2, base_y + 16, f'{n} step' + ('s' if n != 1 else ''), 12, INK, 'bold')
        svg.text(x + w * s / 2, base_y + 34, f'{w} × {h} pixels', 11, INK2)
        x += w * s + 30
    svg.text(30, H - 22, 'Illustrative colours: the game picks the closest colour of the level’s palette at each step.', 11, INK2, anchor='start')
    svg.save(out / 'view-scale-steps.svg')


def figure_display_modes(out):
    W, H = 700, 280
    modes = [('Mode 3: MCGA/VGA', 'MGA.OVL, .PAL palettes', 'BIOS mode 0x13:|320 × 200, 256 colours', 'one screen pixel per game pixel', 1),
             ('Mode 5: 256K EGA', 'XGA.OVL, .EGA palettes', 'BIOS mode 0x0e:|640 × 200, 16 colours', 'two screen pixels per game pixel', 2),
             ('Mode 6: Tandy', 'yga.ovl, .PAL palettes', 'BIOS mode 0x09', 'driver not in the collection', 0)]
    svg = Svg(W, H, 'The three display modes',
              'The three display modes that the setup program offers. Mode 3, MCGA/VGA: driver MGA.OVL, .PAL palettes, '
              'BIOS mode 0x13 at 320 by 200 in 256 colours, one screen pixel per game pixel. Mode 5, 256K EGA: driver '
              'XGA.OVL, .EGA palettes, BIOS mode 0x0e at 640 by 200 in 16 colours, each game pixel shown as two '
              'screen pixels. Mode 6, Tandy: driver yga.ovl, .PAL palettes, BIOS mode 0x09; the driver is not in the '
              'collection. The game draws the same view in every mode.')
    svg.text(30, 30, 'The three display modes', 14, INK, 'bold', 'start')
    svg.text(30, 50, 'The game decides the same view in every mode; only the way it becomes pixels differs.', 12, INK2, anchor='start')
    for k, (title, driver, bios, pixels, n) in enumerate(modes):
        x = 30 + k * 220
        svg.rect(x, 70, 205, 180, '#f6f5f2', GRID, 1)
        svg.text(x + 12, 92, title, 12.5, INK, 'bold', 'start')
        svg.text(x + 12, 114, driver, 11, INK2, anchor='start')
        for j, part in enumerate(bios.split('|')):
            svg.text(x + 12, 132 + 16 * j, part, 11, INK2, anchor='start')
        if n:
            for i in range(n):
                svg.rect(x + 12 + i * 26, 160, 24, 24, FRONT)
            svg.text(x + 12, 204, pixels, 11, INK, anchor='start')
        else:
            svg.rect(x + 12, 160, 24, 24, '#f1f0ec', MUTED, 1, '3 3')
            svg.text(x + 12, 200, pixels, 11, INK, anchor='start')
            svg.text(x + 12, 218, 'what it draws is unknown', 11, INK2, anchor='start')
    svg.save(out / 'view-display-modes.svg')


def main():
    out = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[2] / 'docs/view/img'
    out.mkdir(parents=True, exist_ok=True)
    figure_visible_blocks(out)
    figure_faces(out)
    figure_screen(out)
    figure_corridor(out)
    figure_object_spots(out)
    figure_pixels(out)
    figure_item_scale(out)
    figure_monster_frames(out)
    figure_door_rows(out)
    figure_scale_steps(out)
    figure_display_modes(out)
    print('written to', out)


if __name__ == '__main__':
    main()
