ExperimentsFable 5.2 Python art (30 images)

Rainy city street at night, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""04 Rainy city street at night.

A small ray tracer: two rows of buildings with shop windows and neon
signs, a wet road that mirrors them with streaky reflections, rain,
and one walker with an umbrella. The sign "letters" are random strokes.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/04-rainy-city-street.py
"""
import os, sys, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

# ----------------------------------------------------------------------------
# Shared helper code (copied into every script so that each script runs alone)
# ----------------------------------------------------------------------------
W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
F32 = np.float32


def hexc(s):
    s = s.lstrip('#')
    return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0


def c8(c):
    return tuple(int(max(0, min(255, round(float(v) * 255)))) for v in c)


def smooth(a, b, x):
    t = np.clip((x - a) / (b - a + 1e-12), 0, 1)
    return t * t * (3 - 2 * t)


def mix(a, b, t):
    return a + (b - a) * t


def ramp(t, stops):
    """Colour gradient. stops = [(position, '#hex'), ...]; t is an array."""
    pos = [p for p, _ in stops]
    cols = np.array([hexc(c) if isinstance(c, str) else c for _, c in stops])
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)


def vnoise(shape, cell, rng):
    """Smooth value noise in 0..1: a random grid, enlarged with cubic interpolation."""
    h, w = shape
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    cy, cx = max(1.0, float(cy)), max(1.0, float(cx))
    gh, gw = int(h / cy) + 4, int(w / cx) + 4
    g = rng.random((gh, gw)).astype(F32)
    z = ndi.zoom(g, (cy, cx), order=3 if min(cy, cx) >= 3 else 1)
    oy, ox = int(cy * 1.5), int(cx * 1.5)
    z = z[oy:oy + h, ox:ox + w]
    if z.shape != (h, w):
        z = np.pad(z, ((0, h - z.shape[0]), (0, w - z.shape[1])), mode='edge')
    return z


def fbm(shape, cell, octaves, rng, gain=0.5, lac=2.0):
    """Fractal noise in about 0..1 (sum of value noise octaves)."""
    cy, cx = (cell, cell) if np.isscalar(cell) else cell
    out = np.zeros(shape, F32)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (cy, cx), rng)
        tot += amp
        amp *= gain
        cy /= lac
        cx /= lac
    return out / tot


def blur(a, s):
    """Gaussian blur for 2D or 3D (h, w, c) arrays; large radii use a small copy."""
    if s <= 0:
        return a
    if s > 10:
        k = int(s // 5)
        h, w = a.shape[:2]
        ph, pw = (-h) % k, (-w) % k
        pad = ((0, ph), (0, pw)) + (((0, 0),) if a.ndim == 3 else ())
        b = np.pad(a, pad, mode='edge')
        hh, ww = b.shape[0] // k, b.shape[1] // k
        if a.ndim == 3:
            b = b.reshape(hh, k, ww, k, -1).mean((1, 3))
            b = ndi.gaussian_filter(b, (s / k, s / k, 0), mode='nearest')
            b = ndi.zoom(b, (k, k, 1), order=1)
        else:
            b = b.reshape(hh, k, ww, k).mean((1, 3))
            b = ndi.gaussian_filter(b, s / k, mode='nearest')
            b = ndi.zoom(b, (k, k), order=1)
        return b[:h, :w].astype(F32)
    sig = (s, s, 0) if a.ndim == 3 else s
    return ndi.gaussian_filter(a, sig, mode='nearest').astype(F32)


def bloom(a, thresh=0.7, sigmas=(6, 20, 60), gains=(0.35, 0.3, 0.25)):
    """Soft glow around bright areas."""
    lum = a.max(-1)
    hi = a * smooth(thresh, thresh + 0.25, lum)[..., None]
    out = a.copy()
    for s, g in zip(sigmas, gains):
        out += g * blur(hi, s)
    return out


def glow(cx, cy, r, power=2.0):
    """Radial falloff field, 1 at the centre."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    d2 = ((xx - cx) ** 2 + (yy - cy) ** 2) / (r * r)
    return 1.0 / (1.0 + d2) ** power


def comp(base, rgb, a):
    """Alpha composite. rgb may be one colour or an image; a is an (h, w) mask."""
    return base * (1 - a[..., None]) + np.asarray(rgb, F32) * a[..., None]


class Layer:
    """Vector drawing layer (PIL) drawn at 2x size, then averaged down for smooth edges."""

    def __init__(self, ss=2):
        self.ss = ss
        self.im = Image.new('RGBA', (W * ss, H * ss), (0, 0, 0, 0))
        self.d = ImageDraw.Draw(self.im)

    def _p(self, pts):
        s = self.ss
        return [(float(x) * s, float(y) * s) for x, y in pts]

    def poly(self, pts, col, a=1.0):
        self.d.polygon(self._p(pts), fill=c8(col) + (int(a * 255),))

    def line(self, pts, col, width=1.0, a=1.0):
        wd = max(1, int(round(width * self.ss)))
        self.d.line(self._p(pts), fill=c8(col) + (int(a * 255),), width=wd, joint='curve')

    def dot(self, x, y, rx, col, a=1.0, ry=None):
        s = self.ss
        ry = rx if ry is None else ry
        self.d.ellipse([(x - rx) * s, (y - ry) * s, (x + rx) * s, (y + ry) * s],
                       fill=c8(col) + (int(a * 255),))

    def arrays(self):
        im = self.im.convert('RGBa').reduce(self.ss)       # premultiplied alpha
        a = np.asarray(im).astype(F32) / 255.0
        return a[..., :3], a[..., 3]

    def onto(self, base, opacity=1.0, soften=0.0):
        rgb, a = self.arrays()
        if soften > 0:
            rgb, a = blur(rgb, soften), blur(a, soften)
        return base * (1 - a[..., None] * opacity) + rgb * opacity


def painterly(ref, rng, sizes=(44, 22, 11, 6), thresh=(0, 0.06, 0.05, 0.04), ss=2,
              jitter=0.035, length=5, base_angle=None, edge_follow=1.0, relief=0.3,
              density=1.0, tol=0.22, underblur=30, keep=None):
    """Repaint an image with oriented brush strokes, coarse to fine.

    Strokes follow the edges of the picture (structure tensor) and a flow field
    elsewhere. Finer strokes are added only where the canvas still differs from
    the reference. A separate height map of the strokes gives the paint relief.
    keep: optional (h, w) probability mask that limits where fine strokes go.
    """
    h, w = ref.shape[:2]
    lum = ref @ np.array([0.3, 0.59, 0.11], F32)
    l2 = ndi.gaussian_filter(lum, 2.0)
    gx, gy = ndi.sobel(l2, axis=1), ndi.sobel(l2, axis=0)
    jxx, jyy, jxy = blur(gx * gx, 6), blur(gy * gy, 6), blur(gx * gy, 6)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + np.pi / 2
    coh = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
    cw = smooth(0.0004, 0.01, coh) * edge_follow
    if base_angle is None:
        base_angle = fbm((h, w), 320, 3, rng) * np.pi * 3
    base_angle = np.broadcast_to(np.asarray(base_angle, F32), (h, w))
    c2 = cw * np.cos(2 * theta) + (1 - cw) * np.cos(2 * base_angle)
    s2 = cw * np.sin(2 * theta) + (1 - cw) * np.sin(2 * base_angle)
    ang = 0.5 * np.arctan2(s2, c2)
    dxf, dyf = np.cos(ang).astype(F32), np.sin(ang).astype(F32)

    start = np.clip(blur(ref, underblur), 0, 1)
    canvas = Image.fromarray((start * 255).astype(np.uint8)).resize((w * ss, h * ss), Image.BILINEAR)
    hmap = Image.new('L', (w * ss, h * ss), 128)
    dr, hd = ImageDraw.Draw(canvas), ImageDraw.Draw(hmap)

    for li, s in enumerate(sizes):
        sp = max(2.0, s * 0.45 / density)
        ny, nx = int(h / sp) + 1, int(w / sp) + 1
        gy_, gx_ = np.mgrid[0:ny, 0:nx].astype(F32)
        px = (gx_ + rng.random((ny, nx))).ravel() * sp
        py = (gy_ + rng.random((ny, nx))).ravel() * sp
        ok = (px < w - 1) & (py < h - 1)
        px, py = px[ok], py[ok]
        xi, yi = px.astype(int), py.astype(int)
        sel = np.ones(len(px), bool)
        if thresh[li] > 0:
            cur = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
            diff = blur(np.abs(cur - ref).sum(-1), s * 0.5)
            sel &= diff[yi, xi] > thresh[li]
        if keep is not None and li >= 1:
            sel &= rng.random(len(px)) < keep[yi, xi]
        px, py, xi, yi = px[sel], py[sel], xi[sel], yi[sel]
        n = len(px)
        if n == 0:
            continue
        col0 = ref[yi, xi]
        K = int(length)
        step = s * 0.6
        pts = np.zeros((n, 2 * K + 1, 2), F32)
        pts[:, K, 0], pts[:, K, 1] = px, py
        for sgn in (1, -1):
            x, y = px.copy(), py.copy()
            ddx, ddy = dxf[yi, xi] * sgn, dyf[yi, xi] * sgn
            alive = np.ones(n, bool)
            for k in range(1, K + 1):
                ix = np.clip(x.astype(int), 0, w - 1)
                iy = np.clip(y.astype(int), 0, h - 1)
                ndx, ndy = dxf[iy, ix], dyf[iy, ix]
                flip = np.where(ndx * ddx + ndy * ddy < 0, -1.0, 1.0)
                ddx, ddy = ndx * flip, ndy * flip
                nx_, ny_ = x + ddx * step, y + ddy * step
                jx = np.clip(nx_.astype(int), 0, w - 1)
                jy = np.clip(ny_.astype(int), 0, h - 1)
                alive &= np.abs(ref[jy, jx] - col0).sum(-1) < tol
                x = np.where(alive, nx_, x)
                y = np.where(alive, ny_, y)
                pts[:, K + sgn * k, 0], pts[:, K + sgn * k, 1] = x, y
        colj = col0 * (1 + jitter * rng.standard_normal((n, 1))) + 0.4 * jitter * rng.standard_normal((n, 3))
        cols = (np.clip(colj, 0, 1) * 255).astype(np.uint8)
        order = rng.permutation(n)
        P = (pts[order] * ss).reshape(n, -1).tolist()
        Cc = cols[order].tolist()
        G = rng.integers(40, 216, n).tolist()
        Bo = (rng.standard_normal((n, 3)) * s * ss * 0.28).tolist()
        Bl = (1 + 0.07 * rng.standard_normal((n, 3))).tolist()
        wd = max(1, int(s * ss))
        r = wd / 2.0
        for i in range(n):
            p = P[i]
            c = tuple(Cc[i])
            dr.line(p, fill=c, width=wd, joint='curve')
            hd.line(p, fill=G[i], width=wd, joint='curve')
            for ex, ey in ((p[0], p[1]), (p[-2], p[-1])):
                box = [ex - r, ey - r, ex + r, ey + r]
                dr.ellipse(box, fill=c)
                hd.ellipse(box, fill=G[i])
            if s >= 9:        # bristle streaks inside the larger strokes
                vx, vy = p[-2] - p[0], p[-1] - p[1]
                vl = math.hypot(vx, vy) + 1e-6
                ox_, oy_ = -vy / vl, vx / vl
                for b in range(3):
                    o = Bo[i][b]
                    q = [v + (o * ox_ if j % 2 == 0 else o * oy_) for j, v in enumerate(p)]
                    cb = tuple(int(max(0, min(255, v * Bl[i][b]))) for v in c)
                    dr.line(q, fill=cb, width=max(1, wd // 5), joint='curve')
                    hd.line(q, fill=int(max(0, min(255, G[i] + 40 * (Bl[i][b] - 1) * 14))), width=max(1, wd // 5))
    out = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
    if relief > 0:
        hm = ndi.gaussian_filter(np.asarray(hmap.reduce(ss)).astype(F32), 0.8)
        sh = np.clip((-ndi.sobel(hm, axis=1) * 0.5 - ndi.sobel(hm, axis=0) * 0.85) / 255.0, -1, 1)
        out = out * (1 + relief * sh[..., None])
    return out


def finish(a, name, rng, vignette=0.22, grain=0.012, weave=0.018):
    """Vignette, canvas weave, grain, then save to ../images/<name>.png."""
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    r = np.sqrt(((xx / W - 0.5) * 1.15) ** 2 + (yy / H - 0.5) ** 2)
    a = a * (1 - vignette * smooth(0.3, 0.8, r))[..., None]
    if weave > 0:
        wv = (np.sin(xx * 2.1) * np.sin(yy * 2.1)) * 0.5 + (vnoise((H, W), 2.5, rng) - 0.5)
        a = a * (1 + weave * wv)[..., None]
    if grain > 0:
        a = a + grain * rng.standard_normal((H, W, 1)).astype(F32)
    out = os.path.join(HERE, '..', 'images', name + '.png')
    os.makedirs(os.path.dirname(out), exist_ok=True)
    Image.fromarray((np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)).save(out)
    print(f'saved {os.path.normpath(out)}  ({time.time() - T0:.1f} s)')

# ----------------------------------------------------------------------------
# The picture
# ----------------------------------------------------------------------------
SEED = 404
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

CX, HZ, FOC, CAMH = 770.0, 1100.0, 1250.0, 1.6
WALL, KERB, ZEND = 4.3, 2.7, 190.0
HAZE = np.array([0.105, 0.07, 0.15], F32)
NEON = [hexc(c) for c in ('#ff2e88', '#19e3ff', '#ff5a2a', '#7dff5a', '#ffd23a', '#b06bff', '#ff3048', '#3a8bff')]
SHOP = [hexc(c) for c in ('#ffc978', '#ffe2b0', '#ffab5e', '#a8dcff', '#ffb3cc', '#c8ffc0', '#ffbf6a')]

TEX = []
for i in range(4):
    t = ndi.gaussian_filter(rng.random((256, 256)).astype(F32), 3 if i < 2 else 1.2, mode='wrap')
    TEX.append((t - t.min()) / (t.max() - t.min()))


def N(i, x, z, scale):
    c = np.stack([(z / scale * 16) % 256, (x / scale * 16) % 256])
    return ndi.map_coordinates(TEX[i], c, order=1, mode='grid-wrap')


def glyphs(n):
    """n random 5x5 stroke patterns that look a little like sign characters."""
    g = np.zeros((n, 5, 5), bool)
    for k in range(n):
        for r in rng.choice([0, 2, 4], rng.integers(1, 4), replace=False):
            a, b = sorted(rng.choice(6, 2, replace=False))
            g[k, r, a:max(b, a + 3)] = True
        for c in rng.choice([0, 2, 4], rng.integers(1, 3), replace=False):
            a, b = sorted(rng.choice(6, 2, replace=False))
            g[k, a:max(b, a + 3), c] = True
    return g


# ---- the buildings on both sides ------------------------------------------------
SIDES = {}
for side in (-1, 1):
    zb = [1.0]
    while zb[-1] < ZEND:
        zb.append(zb[-1] + rng.uniform(6.5, 12.5))
    nb = len(zb) - 1
    SIDES[side] = dict(
        zb=np.array(zb, F32), top=rng.uniform(10, 34, nb).astype(F32),
        wcol=(np.array([0.06, 0.058, 0.09], F32) * rng.uniform(0.6, 1.6, (nb, 1))
              * (1 + 0.25 * rng.standard_normal((nb, 3)))).astype(F32),
        shop=np.array([SHOP[i] for i in rng.integers(0, len(SHOP), nb)]) * (rng.random((nb, 1)) > 0.16) * rng.uniform(0.7, 1.25, (nb, 1)),
        neon=np.array([NEON[i] for i in rng.integers(0, len(NEON), nb)]) * (rng.random((nb, 1)) > 0.2),
        plit=rng.uniform(0.18, 0.6, nb).astype(F32),
        wrand=rng.random((nb, 16, 12)).astype(F32), wtone=rng.random((nb, 16, 12)).astype(F32),
        gl=glyphs(nb * 16).reshape(nb, 16, 5, 5))


def wall_tex(side, z, y):
    S = SIDES[side]
    b = np.clip(np.searchsorted(S['zb'], z) - 1, 0, len(S['top']) - 1)
    u = z - S['zb'][b]
    L = S['zb'][b + 1] - S['zb'][b]
    col = S['wcol'][b] * (0.75 + 0.5 * N(0, u + b * 7.3, y, 3.0))[..., None]
    col = col * (1 - 0.35 * ((y / 3.1) % 1.0 < 0.06))[..., None]
    # upper windows
    fy, wu = (y - 5.0) / 3.1, u / 1.9
    fi, wi = np.floor(fy).astype(int), np.floor(wu).astype(int)
    inwin = (y > 5.0) & (fy % 1 > 0.22) & (fy % 1 < 0.78) & (wu % 1 > 0.2) & (wu % 1 < 0.8) & (u < L - 0.3)
    r = S['wrand'][b, fi % 16, wi % 12]
    tone = S['wtone'][b, fi % 16, wi % 12]
    lit = inwin & (r < S['plit'][b])
    wc = np.where((tone < 0.6)[..., None], hexc('#ffc98a'), np.where((tone < 0.85)[..., None], hexc('#cfe2ff'), hexc('#ff9ad0')))
    shade = 0.35 + 0.65 * ((fy % 1 - 0.22) / 0.56)
    col = np.where(lit[..., None], wc * (0.25 + 0.75 * tone * 0 + 0.5 * r / (S['plit'][b] + 1e-3))[..., None] * shade[..., None] * 0.9, col)
    col = np.where((inwin & ~lit)[..., None], np.array([0.03, 0.04, 0.075], F32), col)
    cross = inwin & ((np.abs(wu % 1 - 0.5) < 0.02) | (np.abs(fy % 1 - 0.47) < 0.02))
    col = np.where(cross[..., None], col * 0.25, col)
    # shop window on the ground floor
    inshop = (y > 0.5) & (y < 2.95) & (u > 0.45) & (u < L - 0.45)
    frame = ((u - 0.45) % 1.7 < 0.07) | (y > 2.88)
    door = np.abs(u - L * 0.5) < 0.55
    v = (y - 0.5) / 2.45
    cellu, shelf = np.floor(u / 0.3), np.floor(v * 4)
    item = N(3, cellu * 3.7 + b * 11.0, shelf * 5.3 + 2.0, 16.0)
    hue = (N(2, cellu * 5.1 + b * 3.0, shelf * 2.9, 16.0) + b * 0.37) % 1.0
    isitem = ((u / 0.3) % 1 > 0.14) & ((v * 4) % 1 < 0.2 + 0.5 * item) & (v < 0.76)
    glowv = 0.55 + 0.5 * v
    back = S['shop'][b] * (glowv * (0.62 + 0.25 * N(0, u + b, y, 1.5)))[..., None]
    tint = np.where((hue < 0.4)[..., None], hexc('#b8412e'), np.where((hue < 0.6)[..., None], hexc('#2f6d8a'), hexc('#c9a03a')))
    goods = S['shop'][b] * 0.22 + tint * (0.25 + 0.5 * item)[..., None] * S['shop'][b].max(-1, keepdims=True)
    sc = np.where(isitem[..., None], goods, back)
    sc = np.where((((v * 4) % 1 > 0.93) & (v < 0.8))[..., None], S['shop'][b] * 0.22, sc)
    sc = np.where((v > 0.88)[..., None], S['shop'][b] * 1.5, sc)
    glowv = 0.6 + 0.55 * smooth(0.5, 2.9, y)
    sc = np.where(door[..., None], S['shop'][b] * 0.55 * glowv[..., None], sc)
    sc = np.where(frame[..., None], 0.02, sc)
    col = np.where(inshop[..., None], sc, col)
    # neon sign band above the shop
    gu, cv = (u - 0.7) / 0.78, (y - 3.42) / 0.82
    inband = (y > 3.25) & (y < 4.4) & (u > 0.5) & (u < L - 0.5)
    col = np.where(inband[..., None], np.array([0.012, 0.012, 0.02], F32), col)
    ci = np.floor(gu).astype(int)
    cu = gu % 1
    ing = inband & (cv > 0) & (cv < 1) & (cu > 0.1) & (cu < 0.9) & (gu > 0) & (gu < np.floor((L - 1.4) / 0.78))
    bit = S['gl'][b, ci % 16, np.clip((cv * 5).astype(int), 0, 4), np.clip(((cu - 0.1) / 0.8 * 5).astype(int), 0, 4)]
    col = np.where((ing & bit)[..., None], S['neon'][b] * 2.6, col)
    edge = inband & ((y < 3.3) | (y > 4.35))
    col = np.where(edge[..., None], S['neon'][b] * 1.3, col)
    return col.astype(F32), S['top'][b]


# ---- things that face the camera: blade signs, lamps, a car -----------------------
RECTS = []     # (z, x0, x1, y0, y1, colour, glyph stack or None, second colour)
for side in (-1, 1):
    S = SIDES[side]
    for b in range(len(S['top'])):
        if rng.random() < 0.62 and S['zb'][b] > 6:
            z = float(S['zb'][b] + rng.uniform(1, 5))
            wdt = rng.uniform(0.75, 1.15)
            y0 = rng.uniform(4.3, 6.0)
            k = int(rng.integers(3, 7))
            x_in = WALL - 0.15 - wdt
            x0, x1 = (side * WALL - 0.15, side * WALL - 0.15 - wdt) if side > 0 else (-WALL + 0.15, -WALL + 0.15 + wdt)
            c1, c2 = NEON[rng.integers(0, len(NEON))], NEON[rng.integers(0, len(NEON))]
            RECTS.append((z, min(x0, x1), max(x0, x1), y0, y0 + k * wdt, c1, glyphs(k), mix(c2, np.ones(3, F32), 0.35)))
for z in np.arange(11.0, 150.0, 17.0):
    for side in (-1, 1):
        RECTS.append((float(z + (2.5 if side > 0 else -3.5)), side * 3.15 - 0.2, side * 3.15 + 0.2, 6.28, 6.42,
                      np.array([1.0, 0.78, 0.48], F32) * 5.0, None, None))
RECTS.append((40.0, 0.35, 2.1, 0.3, 1.45, np.array([0.012, 0.014, 0.022], F32), None, None))
for xo in (0.5, 1.95):
    RECTS.append((39.95, xo - 0.17, xo + 0.17, 0.72, 0.9, np.array([1.0, 0.07, 0.04], F32) * 5.0, None, None))
for xo in (-1.9, -0.75):
    RECTS.append((95.0, xo - 0.12, xo + 0.12, 0.6, 0.78, np.array([1.0, 0.95, 0.8], F32) * 9.0, None, None))


def trace(oy, dx, dy):
    """Follow rays that start at (0, oy, 0) with direction (dx, dy, 1). Returns colour and distance."""
    el = np.clip(dy, 0, 1.4)
    col = ramp(el, [(0, '#231634'), (0.25, '#120f24'), (1.4, '#04050c')])
    dist = np.full(dx.shape, 1e4, F32)
    # the far end of the street
    ye = oy + dy * ZEND
    xe = dx * ZEND
    endhit = (ye > 0) & (ye < 46 + 14 * np.sin(xe * 0.21))
    ewin = ((ye / 3.2) % 1 > 0.3) & ((ye / 3.2) % 1 < 0.7) & ((xe / 2.2) % 1 > 0.25) & ((xe / 2.2) % 1 < 0.75)
    er = N(3, np.floor(xe / 2.2) * 5.1, np.floor(ye / 3.2) * 3.7, 16.0)
    ecol = np.where((ewin & (er > 0.62))[..., None], hexc('#ffcf96') * 0.7, np.array([0.03, 0.03, 0.05], F32))
    col = np.where(endhit[..., None], ecol, col)
    dist = np.where(endhit, ZEND, dist)
    for side in (-1, 1):
        ok = dx * side > 1e-6
        t = np.where(ok, WALL / (np.abs(dx) + 1e-9), 1e9).astype(F32)
        y = oy + dy * t
        tc = np.clip(t, 0, ZEND)
        c, top = wall_tex(side, tc, np.clip(y, 0, 80))
        hit = ok & (y >= 0) & (y <= top) & (t < ZEND) & (t < dist)
        col = np.where(hit[..., None], c, col)
        dist = np.where(hit, t, dist)
    for (z, x0, x1, y0, y1, c1, gl, c2) in RECTS:
        x, y = dx * z, oy + dy * z
        ins = (x > x0) & (x < x1) & (y > y0) & (y < y1) & (z < dist)
        if not ins.any():
            continue
        if gl is None:
            c = np.broadcast_to(c1, dx.shape + (3,))
        else:
            su, sv = (x - x0) / (x1 - x0), (y1 - y) / (y1 - y0)
            k = gl.shape[0]
            border = (su < 0.09) | (su > 0.91) | (sv < 0.09 / k) | (sv > 1 - 0.09 / k)
            cell = np.clip((sv * k).astype(int), 0, k - 1)
            cv, cu = (sv * k) % 1, su
            ing = (cv > 0.16) & (cv < 0.9) & (cu > 0.2) & (cu < 0.8)
            bit = gl[cell, np.clip(((cv - 0.16) / 0.74 * 5).astype(int), 0, 4), np.clip(((cu - 0.2) / 0.6 * 5).astype(int), 0, 4)]
            c = np.where(border[..., None], c1 * 2.4, np.where((ing & bit)[..., None], c2 * 2.6, c1 * 0.10 + 0.01))
        col = np.where(ins[..., None], c, col)
        dist = np.where(ins, z, dist)
    f = np.exp(-np.minimum(dist, 400.0) / 105.0)[..., None]
    return col * f + HAZE * (1 - f), dist


# ---- primary rays (three slightly shifted passes smooth the far detail) ------------
dx0, dy0 = (xx - CX) / FOC, -(yy - HZ) / FOC
acc = np.zeros((H, W, 3), F32)
OFFS = [(0.0, 0.0), (0.35, 0.45), (-0.4, -0.3)]
for (ox, oy_) in OFFS:
    c, d = trace(CAMH, dx0 + ox / FOC, dy0 - oy_ / FOC)
    acc += c
    if ox == 0:
        dist0 = d
scene = acc / len(OFFS)

# ---- the wet road --------------------------------------------------------------------
gz = CAMH / np.maximum(-dy0, 1e-4)
gx = dx0 * gz
gmask = (dy0 < 0) & (gz < dist0)
side_walk = smooth(KERB - 0.03, KERB + 0.03, np.abs(gx))
pud = smooth(0.42, 0.6, N(0, gx, gz, 6.0)) * (1 - 0.6 * side_walk)
m1, m2 = N(2, gx, gz, 0.5) - 0.5, N(3, gx, gz, 0.5) - 0.5
big1 = N(1, gx, gz, 2.5) - 0.5
rough = mix(0.05, 0.007, pud)
refl = np.zeros((H, W, 3), F32)
NS = 10
for s in range(NS):
    jx = (m1 * 1.7 + 0.3 * rng.standard_normal((H, W)).astype(F32)) * rough * 0.6
    jy = (m2 * 1.5 + big1 * 1.0 + 0.4 * rng.standard_normal((H, W)).astype(F32)) * rough * 3.3
    c, _ = trace(-CAMH, dx0 + jx, np.maximum(np.abs(dy0) + jy, 0.004))
    refl += c
refl /= NS
cosv = np.abs(dy0) / np.sqrt(dx0 ** 2 + dy0 ** 2 + 1)
fres = mix(0.36, 0.82, pud) + 0.4 * (1 - cosv) ** 4
tiles = ((gx / 0.6) % 1 < 0.05) | ((gz / 0.6) % 1 < 0.05)
asph = np.array([0.016, 0.017, 0.024], F32) * (0.6 + 0.8 * N(2, gx, gz, 0.3))[..., None]
asph = asph * (1 + 0.9 * side_walk * (1 - 0.5 * tiles))[..., None]
lane = (np.abs(gx) < 0.08) & ((gz / 6.0) % 1 < 0.42)
asph = asph + lane[..., None] * np.array([0.05, 0.05, 0.055], F32)
kerbline = np.exp(-((np.abs(gx) - KERB) / 0.06) ** 2)
ground = asph + refl * fres[..., None] * (1 - 0.35 * kerbline[..., None])
gf = np.exp(-gz / 105.0)[..., None]
ground = ground * gf + HAZE * (1 - gf)
img = np.where(gmask[..., None], ground, scene)

# ---- people: one walker with an umbrella, two far figures ---------------------------
def P(X, Y, Z):
    return (CX + FOC * X / Z, HZ - FOC * (Y - CAMH) / Z)


def walker(L, x, z, umb, col, flip=False, a=1.0):
    s = -1 if flip else 1                      # s=-1 draws the mirror image in the road
    q = lambda X, Y: P(x + X, s * Y, z)
    L.poly([q(-0.27, 0.5), q(0.27, 0.5), q(0.24, 1.0), q(0.2, 1.42), q(0.09, 1.5), q(-0.09, 1.5),
            q(-0.2, 1.42), q(-0.24, 1.0)], col, a)                                         # coat
    L.poly([q(-0.17, 0.02), q(-0.05, 0.0), q(-0.03, 0.6), q(-0.2, 0.6)], col, a)           # legs
    L.poly([q(0.07, 0.0), q(0.2, 0.05), q(0.19, 0.6), q(0.03, 0.6)], col, a)
    L.poly([q(-0.2, 0.0), q(-0.03, 0.0), q(-0.03, 0.06), q(-0.2, 0.06)], col, a)
    hx_, hy_ = q(0.0, 1.62)
    L.dot(hx_, hy_, 0.115 * FOC / z, col, a)
    if umb is not None:
        pts = [q(0.72 * math.cos(t) + 0.05, 1.92 + 0.36 * math.sin(t)) for t in np.linspace(0, np.pi, 16)]
        L.poly(pts, umb, a)
        L.line([q(0.05, 1.3), q(0.05, 2.0)], col, 0.03 * FOC / z, a)


fig, figr = Layer(), Layer()
PEOPLE = [(0.55, 8.2, hexc('#d01c36')), (-1.5, 30.0, None), (3.4, 22.0, hexc('#10131c')), (-3.5, 44.0, None)]
for (px_, pz_, umb) in PEOPLE:
    walker(figr, px_, pz_, None if umb is None else umb * 0.5, np.array([0.01, 0.01, 0.016], F32), flip=True)
    walker(fig, px_, pz_, umb, np.array([0.02, 0.02, 0.035], F32))
rr, ra = figr.arrays()
smear = lambda a_: ndi.gaussian_filter(a_, (9, 1.2))
ra = smear(ra) * 0.8
rr = np.stack([smear(rr[..., c]) for c in range(3)], -1) * 0.8
img = img * (1 - ra[..., None] * gmask[..., None]) + rr * gmask[..., None]
poles = Layer()
for z in np.arange(11.0, 150.0, 17.0)[::-1]:
    for side in (-1, 1):
        zz = float(z + (2.5 if side > 0 else -3.5))
        xb = side * 3.55
        poles.line([P(xb, 0, zz), P(xb, 6.2, zz), P(side * 3.15, 6.5, zz)], (0.012, 0.012, 0.02), max(1.0, 0.07 * FOC / zz))
img = poles.onto(img)
img = fig.onto(img)
# rim light on the main walker's umbrella from the signs above
ux_, uy_ = P(0.6, 2.2, 8.2)
img += (glow(ux_, uy_ - 30, 90, 2.5) * fig.arrays()[1] * (yy < uy_ + 25))[..., None] * hexc('#ff5a8a') * 0.6

# ---- glow, rain, tone --------------------------------------------------------------
img = img + blur(np.clip(img - 0.55, 0, None), 4) * 0.5 + blur(np.clip(img - 0.5, 0, None), 16) * 0.42 \
    + blur(np.clip(img - 0.45, 0, None), 55) * 0.34 + blur(np.clip(img - 0.4, 0, None), 160) * 0.2

rain = Layer()
lumb = blur(img.max(-1), 20)
for _ in range(5200):
    x, y = rng.uniform(-40, W), rng.uniform(-60, H)
    near = rng.random() ** 2.2
    ln = 14 + 95 * near
    li = float(lumb[int(np.clip(y, 0, H - 1)), int(np.clip(x, 0, W - 1))])
    a = min(0.85, (0.035 + 0.5 * li) * (0.35 + 0.65 * rng.random()))
    rain.line([(x, y), (x + ln * 0.13, y + ln)], (0.82, 0.88, 1.0), 0.6 + 1.5 * near, a)
img = rain.onto(img, soften=0.5)
# small splashes on the road
sp = Layer()
for _ in range(1000):
    z = 2.6 + 55 * rng.random() ** 2.2
    x = rng.uniform(-WALL, WALL)
    px_, py_ = P(x, 0, z)
    if 0 <= px_ < W and 0 <= py_ < H:
        li = float(lumb[int(py_), int(px_)])
        r = rng.uniform(0.012, 0.03) * FOC / z
        sp.dot(px_, py_, r, (0.9, 0.93, 1.0), min(0.55, 0.03 + 0.55 * li), ry=max(0.5, r * 0.3))
img = sp.onto(img)

img = 1 - np.exp(-img * 1.35)
img = np.clip(img, 0, 1) ** 0.92
finish(img, '04-rainy-city-street', rng, vignette=0.3, weave=0.0, grain=0.018)