#!/usr/bin/env python3
"""Thirty Times, Every Spot at Once

Wall drawing for 2026-11-28, concept "spots".

Instruction (quoted in full):
"White crayon on a black wall. Spots 1/8 inch apart, in one broad patch each
white by coin toss. Thirty times, every spot at once: a spot is white if the
white spots within 1/4 inch number more than a fifth of the white spots 1/4
to 3/4 inch away, else bare."

Carried out literally as a program. Decisions where the instruction is open
are listed in statement.md and log.md (patch size, wall size, boundary
handling, distance ties, spot size).

Pure standard library. Writes render-1.png (after the thirtieth
application), render-2.png (the initial coin toss) and render-3.png (after
the first application) beside itself.
"""

import random
import struct
import zlib

# --- fixed choices (see statement.md) -------------------------------------
SEED = 20261128
EIGHTHS_WIDE = 288        # patch width:  288 spots x 1/8 in = 36 in
EIGHTHS_TALL = 288        # patch height: 288 spots x 1/8 in = 36 in
MARGIN_IN = 3.0           # bare wall around the patch on every side
PPI = 64                  # pixels per inch in the render
SPOT_FRAC = 0.75          # spot diameter as a fraction of the 1/8 in pitch
GENERATIONS = 30

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# --- the rule --------------------------------------------------------------
# Spots sit on a grid of 1/8 in. Distance between spots is measured centre
# to centre in inches. "within 1/4 inch" includes exactly 1/4 in
# (dx^2 + dy^2 <= 4 in eighths); "1/4 to 3/4 inch away" means strictly more
# than 1/4 in and at most 3/4 in (4 < dx^2 + dy^2 <= 36). A spot never
# counts itself. Spots outside the patch do not exist, so they are never
# white and never counted.
NEAR_D2 = 4
MID_D2 = 36


def band_widths(d2_max):
    """For each row offset dy, the largest |dx| with dx^2+dy^2 <= d2_max."""
    widths = {}
    dy = 0
    while dy * dy <= d2_max:
        dx = int((d2_max - dy * dy) ** 0.5)
        while dx * dx + dy * dy > d2_max:
            dx -= 1
        while (dx + 1) * (dx + 1) + dy * dy <= d2_max:
            dx += 1
        widths[dy] = dx
        dy += 1
    return widths


def window_count(grid, widths):
    """count[j][i] = number of white spots at dx^2+dy^2 <= max (incl. self)."""
    rows, cols = len(grid), len(grid[0])
    count = [[0] * cols for _ in range(rows)]
    for dy, xmax in widths.items():
        for sign in (1, -1) if dy else (1,):
            off = sign * dy
            for j in range(rows):
                src = j + off
                if not 0 <= src < rows:
                    continue
                row = grid[src]
                # sliding window sum of row[i-xmax .. i+xmax], clipped
                acc = sum(row[0:xmax + 1])
                cj = count[j]
                for i in range(cols):
                    lo = i - xmax
                    hi = i + xmax
                    if i > 0:
                        if hi < cols:
                            acc += row[hi]
                        if lo - 1 >= 0:
                            acc -= row[lo - 1]
                    cj[i] += acc
    return count


def step(grid):
    near = window_count(grid, NEAR_W)   # includes the spot itself
    within6 = window_count(grid, MID_W)
    rows, cols = len(grid), len(grid[0])
    out = [[0] * cols for _ in range(rows)]
    for j in range(rows):
        gj, nj, wj, oj = grid[j], near[j], within6[j], out[j]
        for i in range(cols):
            n = nj[i] - gj[i]              # white within 1/4 in, excl. self
            m = wj[i] - nj[i]              # white at 1/4..3/4 in
            oj[i] = 1 if n * 5 > m else 0  # more than a fifth
    return out


NEAR_W = band_widths(NEAR_D2)
MID_W = band_widths(MID_D2)

# --- drawing ---------------------------------------------------------------
def render(grid, path):
    rows, cols = len(grid), len(grid[0])
    wall_w_in = cols / 8.0 + 2 * MARGIN_IN
    wall_h_in = rows / 8.0 + 2 * MARGIN_IN
    W = int(round(wall_w_in * PPI))
    H = int(round(wall_h_in * PPI))
    img = bytearray(W * H * 3)  # all black
    pitch = PPI / 8.0
    r = SPOT_FRAC * pitch / 2.0
    ox = MARGIN_IN * PPI + pitch / 2.0
    oy = MARGIN_IN * PPI + pitch / 2.0
    ri = max(1, int(round(r)))
    # circular crayon spot, precomputed once
    stamp = [(dx, dy) for dy in range(-ri, ri + 1) for dx in range(-ri, ri + 1)
             if dx * dx + dy * dy <= r * r]
    for j in range(rows):
        cy = int(round(oy + j * pitch))
        for i in range(cols):
            if not grid[j][i]:
                continue
            cx = int(round(ox + i * pitch))
            for dx, dy in stamp:
                x, y = cx + dx, cy + dy
                if 0 <= x < W and 0 <= y < H:
                    p = (y * W + x) * 3
                    img[p:p + 3] = b'\xff\xff\xff'
    write_png(path, W, H, bytes(img))


def write_png(path, w, h, rgb):
    raw = b''.join(b'\x00' + rgb[y * w * 3:(y + 1) * w * 3] for y in range(h))
    def chunk(tag, data):
        c = tag + data
        return struct.pack('>I', len(data)) + c + struct.pack('>I', zlib.crc32(c) & 0xffffffff)
    png = (b'\x89PNG\r\n\x1a\n'
           + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0))
           + chunk(b'IDAT', zlib.compress(raw, 6))
           + chunk(b'IEND', b''))
    with open(path, 'wb') as f:
        f.write(png)


def main():
    rng = random.Random(SEED)
    grid = [[1 if rng.random() < 0.5 else 0 for _ in range(EIGHTHS_WIDE)]
            for _ in range(EIGHTHS_TALL)]
    render(grid, 'render-2.png')            # the coin toss
    for g in range(1, GENERATIONS + 1):
        grid = step(grid)                   # every spot at once
        if g == 1:
            render(grid, 'render-3.png')    # after the first application
    render(grid, 'render-1.png')            # after the thirtieth
    white = sum(sum(r) for r in grid)
    print(f'after {GENERATIONS} applications: {white} of '
          f'{EIGHTHS_WIDE * EIGHTHS_TALL} spots white')


if __name__ == '__main__':
    main()
