#!/usr/bin/env python3
"""10 Cozy snowy village window.

Blue hour in a snowy lane: a row of dark houses, a half-timbered
cottage with one candlelit window, the light spilling over the snow,
chimney smoke, falling flakes, then a brush-stroke repaint.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/10-snowy-village-window.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 = 1010
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)

VPX, VPY = 600.0, 1190.0
WARM = hexc('#ffb04e')
FLX, FLY = 1180.0, 1238.0            # the candle flame
WX0, WX1, WY0, WY1 = 1062.0, 1298.0, 1007.0, 1328.0   # the glass

# ---- sky ------------------------------------------------------------------------------
ts = np.clip(yy / VPY, 0, 1)
sky = ramp(ts, [(0, '#0a1738'), (0.4, '#17305f'), (0.75, '#3a5a8e'), (0.92, '#6f7fa8'), (1, '#9a8fae')])
sky *= (0.93 + 0.14 * fbm((H, W), (90, 300), 4, rng))[..., None]
st = np.zeros((H, W), F32)
n = 420
st[rng.integers(0, 900, n), rng.integers(0, W, n)] = rng.random(n) ** 4 * 2 + 0.2
stars = blur(st, 0.8) * 5 + blur(st, 2.2) * 4
stars *= smooth(900, 300, yy)
img = sky
mo = Layer()
mo.dot(330, 300, 44, hexc('#f4f1dc'))
mo.dot(352, 288, 42, hexc('#11244d'))
img = mo.onto(img)

# far hills with pines
hl = Layer()
xs = xx[0]
ridge = VPY - 20 - 70 * vnoise((1, W), (1, 300), rng)[0]
hl.poly([(0, VPY + 60)] + [(float(x), float(ridge[int(x)])) for x in range(0, W, 8)] + [(W, VPY + 60)], hexc('#3a517c'))
for _ in range(150):
    x = rng.uniform(0, W)
    yb = float(ridge[int(x)]) + rng.uniform(0, 30)
    hgt = rng.uniform(18, 60)
    hl.poly([(x, yb - hgt), (x + hgt * 0.26, yb), (x - hgt * 0.26, yb)], hexc('#2b4069') * rng.uniform(0.8, 1.15))
img = hl.onto(img, soften=0.8)

# ---- snow lane --------------------------------------------------------------------------
tg = np.clip((yy - VPY) / (H - VPY), 0, 1)
base_n = fbm((H, W), (70, 200), 5, rng)
rows = np.clip((tg ** 0.6) * (H - 1), 0, H - 1).astype(int)
drift = np.take_along_axis(base_n, rows, 0)
dsl = ndi.sobel(ndi.gaussian_filter(drift, 3), axis=0)
dsl = np.clip(dsl / (np.abs(dsl).max() + 1e-6) * 4, -1, 1)
ground = ramp(tg, [(0, '#6c84b4'), (0.3, '#506da4'), (1, '#3b568e')])
ground *= (1 + 0.13 * dsl)[..., None]

# light from the window across the snow
v = (yy - 1596.0) / 410.0
xl, xr = 1000 - 520 * v, 1352 - 110 * v
u = (xx - xl) / np.maximum(xr - xl, 1)
pen = 0.03 + 0.10 * np.clip(v, 0, 1)
patch = smooth(0, 1, u / pen) * smooth(0, 1, (1 - u) / pen) * smooth(-0.02, 0.05, v)
bars = np.maximum.reduce([np.exp(-((u - 0.5) / (0.022 + 0.01 * np.clip(v, 0, 2))) ** 2),
                          np.exp(-((v - 0.36) / 0.03) ** 2), np.exp(-((v - 0.78) / 0.04) ** 2)])
patch = patch * (1 - 0.72 * bars) * np.exp(-np.clip(v, 0, None) * 1.25)
patch = blur(np.nan_to_num(patch).astype(F32), 11)
ground = ground * (1 - 0.6 * patch[..., None]) + hexc('#ffa23e') * 0.95 * (patch * (1 + 0.3 * dsl))[..., None]
ground += glow(1180, 1640, 420, 1.6)[..., None] * WARM * 0.16
img = comp(img, ground, smooth(-2, 2, yy - VPY))

tr = Layer()                                              # cart ruts and footprints
for x0 in (640.0, 900.0):
    pts = [(mix(VPX + (x0 - 770) * 0.03, x0, t ** 1.6) + 40 * math.sin(t * 3) * (1 - t), mix(VPY + 6, 2010, t)) for t in np.linspace(0, 1, 40)]
    for i in range(len(pts) - 1):
        t = i / 39
        tr.line(pts[i:i + 2], hexc('#324b84'), 2 + 26 * t, 0.4)
        tr.line([(pts[i][0] + 3 + 12 * t, pts[i][1]), (pts[i + 1][0] + 3 + 12 * t, pts[i + 1][1])], hexc('#8ba4d2'), 1 + 5 * t, 0.3)
for i, t in enumerate(np.linspace(0.25, 1, 22)):
    x = mix(700, 1060, t) + (14 if i % 2 else -14) * (1 - t * 0.5)
    y = mix(1990, 1660, t)
    sc = mix(1.0, 0.55, t)
    tr.dot(x, y, 20 * sc, hexc('#263c72'), 0.7, ry=9 * sc)
img = tr.onto(img, soften=1.2)


# ---- (the fence is drawn later, after the houses) ----
# ---- helpers for houses ---------------------------------------------------------------------
def snow_line(L, pts, th, lit='#a9bfe4', shade='#6079ad'):
    L.line([(x, y + th * 0.35) for x, y in pts], hexc(shade), th)
    L.line(pts, hexc(lit), th * 0.85)
    for x, y in pts:
        L.dot(x, y, th * 0.45, hexc(lit))


SMK = [np.zeros((H, W), F32) for _ in range(3)]


def smoke(x0, y0, hgt, drift, n=5000):
    """Particles that rise, drift and spread; collected in three size classes."""
    ph = rng.uniform(0, 6.28)
    t = rng.random(n)
    x = x0 + drift * t ** 1.6 + 75 * t * np.sin(t * 4.2 + ph) + 30 * t * np.sin(t * 11 + ph * 2) + rng.normal(0, 1, n) * (3 + 62 * t ** 1.2)
    y = y0 - hgt * t ** 0.85 + rng.normal(0, 1, n) * (3 + 30 * t)
    wgt = (1 - t) ** 1.3 + 0.04
    for b, (lo, hi) in enumerate(((0, 0.25), (0.25, 0.6), (0.6, 1.01))):
        m = (t >= lo) & (t < hi)
        d, _, _ = np.histogram2d(y[m], x[m], bins=(H, W), range=((0, H), (0, W)), weights=wgt[m])
        SMK[b] += d.astype(F32)


def tovp(pt, f=0.3):
    return (pt[0] + (VPX - pt[0]) * f, pt[1] + (VPY - pt[1]) * f)


def house(L, x0, x1, yb, wall_h, gable_h, haze, chim=True):
    wall = mix(hexc('#232f4a'), hexc('#5a709c'), haze)
    A_, B_, P_ = (x1, yb), (x1, yb - wall_h), ((x0 + x1) / 2, yb - wall_h - gable_h)
    L.poly([A_, B_, tovp(B_), tovp(A_)], wall * 0.72)                                   # side wall along the lane
    L.poly([B_, P_, tovp(P_), tovp(B_)], mix(hexc('#7f98c8'), hexc('#93a8cf'), haze))     # snowy side of the roof
    q = lambda fu, fv: tovp((x1, yb - wall_h * fv), fu)
    L.poly([q(0.1, 0.3), q(0.1, 0.56), q(0.19, 0.56), q(0.19, 0.3)], mix(hexc('#0e1830'), hexc('#4a6492'), haze))
    snow_line(L, [B_, tovp(B_)], max(4, (x1 - x0) * 0.035))
    snow_line(L, [P_, tovp(P_)], max(4, (x1 - x0) * 0.04))
    L.poly([(x0, yb), (x0, yb - wall_h), ((x0 + x1) / 2, yb - wall_h - gable_h), (x1, yb - wall_h), (x1, yb)], wall)
    w = x1 - x0
    if chim:
        cx_ = x0 + w * 0.72
        cyt = yb - wall_h - gable_h * 0.95
        L.poly([(cx_ - w * 0.05, yb - wall_h - gable_h * 0.3), (cx_ + w * 0.05, yb - wall_h - gable_h * 0.3), (cx_ + w * 0.05, cyt), (cx_ - w * 0.05, cyt)], wall * 0.75)
        snow_line(L, [(cx_ - w * 0.06, cyt), (cx_ + w * 0.06, cyt)], max(4, w * 0.035))
    # dark windows with a little sky in the glass
    for (fx, fy) in [(0.28, 0.42), (0.72, 0.42), (0.5, 1.12)]:
        wx_, wy_ = x0 + w * fx, yb - wall_h * fy
        ww, wh = w * 0.085, wall_h * 0.13
        L.poly([(wx_ - ww, wy_ - wh), (wx_ + ww, wy_ - wh), (wx_ + ww, wy_ + wh), (wx_ - ww, wy_ + wh)], mix(hexc('#0e1830'), hexc('#4a6492'), haze))
        L.line([(wx_ - ww, wy_ - wh * 0.2), (wx_ + ww * 0.3, wy_ - wh)], mix(hexc('#3c5686'), hexc('#6f88b4'), haze), max(1, ww * 0.25), 0.7)
        L.line([(wx_, wy_ - wh), (wx_, wy_ + wh)], wall * 0.7, max(1, ww * 0.12))
        snow_line(L, [(wx_ - ww * 1.2, wy_ + wh), (wx_ + ww * 1.2, wy_ + wh)], max(2.5, wh * 0.16))
    L.poly([(x0 + w * 0.42, yb), (x0 + w * 0.58, yb), (x0 + w * 0.58, yb - wall_h * 0.26), (x0 + w * 0.42, yb - wall_h * 0.26)], wall * 0.6)   # door
    th = max(7, w * 0.06)
    snow_line(L, [(x0 - w * 0.06, yb - wall_h + gable_h * 0.1), ((x0 + x1) / 2, yb - wall_h - gable_h * 1.02), (x1 + w * 0.06, yb - wall_h + gable_h * 0.1)], th)
    L.dot((x0 + x1) / 2, yb + 2, w * 0.56, hexc('#6782b6'), ry=max(4, w * 0.03))            # snow at the foot


HOUSES = []
for k in (0.19, 0.29, 0.44, 0.66, 1.0):                  # far to near, along one line to the vanishing point
    x1_, yb_ = VPX + (270 - VPX) * k, VPY + (1575 - VPY) * k
    HOUSES.append((x1_ - 470 * k, x1_, yb_, 400 * k, 250 * k, 0.05 + 0.62 * (1 - k)))
vil = Layer()
# church spire at the end of the lane
vil.poly([(640, 1215), (640, 1090), (662, 975), (684, 1090), (684, 1215)], hexc('#4a6190'))
snow_line(vil, [(643, 1085), (662, 980)], 5)
for (x0, x1, yb, wh, gh, hz) in HOUSES:
    house(vil, x0, x1, yb, wh, gh, hz)
    w = x1 - x0
    smoke(x0 + w * 0.72, yb - wh - gh * 0.98, 110 + w * 0.6, 70 + w * 0.5, n=int(1200 + w * 12))
img = vil.onto(img)

# ---- the cottage on the right -----------------------------------------------------------------
eave = lambda x: 838 - (x - 830) * 0.165                  # row of the eave at column x
cot = Layer()
cot.poly([(752, 1612), (752, 878), (830, 838), (830, 1640)], hexc('#1b2439'))                # side wall
cot.poly([(830, 1650), (830, eave(830)), (W + 10, eave(W + 10)), (W + 10, 1650)], hexc('#33405f'))   # front wall
cot.poly([(738, 880), (830, 832), (W + 10, eave(W + 10) - 6), (W + 10, 330), (985, 515)], hexc('#8097c6'))   # snowy roof
cot.poly([(985, 515), (W + 10, 330), (W + 10, 372), (990, 552)], hexc('#a9bfe4'))
img = cot.onto(img)
wallm = (xx > 830) & (yy > eave(xx)) & (yy < 1650)
plaster = fbm((H, W), 34, 4, rng)
img = np.where(wallm[..., None], img * (0.82 + 0.36 * plaster)[..., None], img)
roofm = (yy < eave(xx) - 8) & (xx > 760) & (yy > 300)
img = np.where(roofm[..., None] & (cot.arrays()[1] > 0.5)[..., None], img * (0.88 + 0.24 * fbm((H, W), (30, 120), 3, rng))[..., None], img)

tb = Layer()
beam = hexc('#161b2b')
for x in (846, 965, 1420, 1560):                                                                # timber frame
    tb.line([(x, eave(x) + 6), (x, 1560)], beam, 22)
for off in (150, 610):
    tb.line([(835, eave(835) + off), (W, eave(W) + off + 20)], beam, 20)
tb.line([(858, eave(858) + 160), (955, eave(955) + 600)], beam, 16)
tb.line([(1548, eave(1548) + 170), (1432, eave(1432) + 600)], beam, 16)
for i in range(26):                                                                             # stone base
    x = 836 + i * 31 + rng.uniform(-4, 4)
    for j in range(2):
        tb.dot(x + (15 if j else 0), 1580 + j * 34 + rng.uniform(-3, 3), rng.uniform(13, 18), hexc('#2a3552') * rng.uniform(0.8, 1.25), ry=rng.uniform(10, 14))
# shutters
for (sx0, sx1) in [(948, 1036), (1324, 1412)]:
    tb.poly([(sx0, 985), (sx1, 985), (sx1, 1350), (sx0, 1350)], hexc('#1d3a44'))
    for k in range(1, 4):
        xk = sx0 + (sx1 - sx0) * k / 4
        tb.line([(xk, 987), (xk, 1348)], hexc('#132a33'), 2.5)
    for yk in (1035, 1300):
        tb.line([(sx0 + 3, yk), (sx1 - 3, yk)], hexc('#2b525c'), 12)
    tb.line([(sx0 + 6, 1294), (sx1 - 6, 1041)], hexc('#2b525c'), 10)
# window frame and stone sill
tb.poly([(1040, 985), (1320, 985), (1320, 1350), (1040, 1350)], hexc('#2b1a12'))
tb.poly([(1022, 1350), (1338, 1350), (1338, 1376), (1022, 1376)], hexc('#4a5878'))
img = tb.onto(img)

# the glass: warm light that is brightest at the flame
gm = ((xx > WX0) & (xx < WX1) & (yy > WY0) & (yy < WY1)).astype(F32)
rd = np.sqrt((xx - FLX) ** 2 + ((yy - FLY) * 0.85) ** 2) / 230.0
room = ramp(np.clip(rd, 0, 1), [(0, '#ffe7a4'), (0.1, '#f7b450'), (0.35, '#d27c28'), (0.7, '#96481a'), (1, '#5c2a12')])
room *= (0.9 + 0.2 * fbm((H, W), 50, 3, rng))[..., None]
img = comp(img, room, gm)
win = Layer()
for sgn, xe in ((1, WX0), (-1, WX1)):                                                           # curtains
    win.poly([(xe, WY0), (xe + sgn * 60, WY0), (xe + sgn * 40, WY0 + 150), (xe + sgn * 22, WY1), (xe, WY1)], hexc('#7e2a1e'), 0.92)
    for k in range(4):
        xk = xe + sgn * (8 + k * 12)
        win.line([(xk, WY0), (xk - sgn * k * 4, WY1)], hexc('#4e1610'), 3, 0.6)
win.poly([(WX0, WY0), (WX1, WY0), (WX1, WY0 + 26), (WX0, WY0 + 26)], hexc('#6e241a'), 0.9)        # pelmet
win.poly([(FLX - 15, 1268), (FLX + 15, 1268), (FLX + 15, WY1), (FLX - 15, WY1)], hexc('#fff1d6'))  # candle
win.poly([(FLX + 4, 1268), (FLX + 15, 1268), (FLX + 15, WY1), (FLX + 4, WY1)], hexc('#d9b184'))
win.dot(FLX, WY1 - 3, 36, hexc('#4a2e10'), ry=8)
win.line([(FLX, 1266), (FLX, 1256)], hexc('#2a1a0a'), 2)
flame = [(FLX, FLY - 44), (FLX + 9, FLY - 12), (FLX + 12, FLY + 8), (FLX, FLY + 22), (FLX - 12, FLY + 8), (FLX - 9, FLY - 12)]
win.poly(flame, hexc('#ffcf5a'))
win.poly([(FLX, FLY - 24), (FLX + 5, FLY - 2), (FLX, FLY + 16), (FLX - 5, FLY - 2)], hexc('#fffbe8'))
dark = hexc('#2b1a12')
for yb_ in (1114, 1221):
    win.line([(WX0, yb_), (WX1, yb_)], dark, 8)
img = win.onto(img)
# the centre bar, drawn so that the flame stays in front of it
cb = Layer()
cb.line([(1180, WY0), (1180, FLY - 58)], dark, 10)
img = cb.onto(img)
# frost in the corners of the panes
fr = fbm((H, W), 14, 4, rng)
frost = np.zeros((H, W), F32)
for (px0, px1) in ((WX0, 1175), (1185, WX1)):
    for (py0, py1) in ((WY0, 1110), (1118, 1217), (1225, WY1)):
        ux = np.minimum(xx - px0, px1 - xx) / 60.0
        uy = (py1 - yy) / 46.0
        inp = (xx > px0) & (xx < px1) & (yy > py0) & (yy < py1)
        frost = np.maximum(frost, inp * smooth(0.75, 0.2, np.minimum(ux * 1.6, 9) * 0.5 + uy * 0.55 + (fr - 0.5) * 0.9))
img = comp(img, hexc('#e9f1ff'), frost * 0.5)

# snow on the sill, on the shutters, along the eave; icicles
sn = Layer()
for k in range(15):
    x = 1030 + k * 21.5
    lit = math.exp(-((x - 1180) / 120.0) ** 2)
    sn.dot(x, 1346 - 4 * math.sin(k * 1.3) ** 2, 17, mix(hexc('#93aad6'), hexc('#ffdca0'), lit * 0.9), ry=12 + 3 * math.sin(k * 2.1))
for (sx0, sx1) in [(948, 1036), (1324, 1412)]:
    snow_line(sn, [(sx0 - 2, 984), (sx1 + 2, 984)], 12)
snow_line(sn, [(738, 884), (830, 838)], 26)
ev = [(x, eave(x) - 2 + 5 * math.sin(x * 0.045)) for x in range(830, W + 30, 22)]
snow_line(sn, ev, 34, lit='#b4c8ea', shade='#566fa6')
for x in np.arange(842, W, 15.0):
    ln = rng.uniform(14, 78) * (0.5 + 0.5 * rng.random())
    xw = x + rng.uniform(-4, 4)
    lit = math.exp(-((xw - 1180) / 190.0) ** 2)
    sn.poly([(xw - 4.5, eave(xw) + 12), (xw + 4.5, eave(xw) + 12), (xw + 0.6, eave(xw) + 12 + ln)], mix(hexc('#a9c0e8'), hexc('#ffd9a0'), lit * 0.55), 0.9)
# drift against the wall
dp = [(x, 1622 + 12 * math.sin(x * 0.011) + 7 * math.sin(x * 0.037)) for x in range(740, W + 40, 20)]
sn.poly([(740, 1700)] + dp + [(W + 40, 1700)], hexc('#5673ac'))
snow_line(sn, dp, 20, lit='#7f9ad0', shade='#4a66a0')
# chimney of the cottage
sn.poly([(1280, 470), (1366, 446), (1366, 336), (1280, 336)], hexc('#2a3552'))
sn.poly([(1280, 470), (1300, 464), (1300, 336), (1280, 336)], hexc('#1c2439'))
snow_line(sn, [(1274, 332), (1372, 332)], 20)
img = sn.onto(img)
smoke(1323, 322, 300, 210, n=9000)
smd = blur(SMK[0], 6) * 2.2 + blur(SMK[1], 14) * 4.5 + blur(SMK[2], 28) * 7.0
img = comp(img, hexc('#93a7cc'), np.clip(1 - np.exp(-smd), 0, 0.62))

# a snowy fence in the near left corner
fc = Layer()
posts = [(60 + i * 105, 1905 - i * 44, 1.0 - i * 0.13) for i in range(5)]
for (px_, py_, sc_) in posts:
    fc.poly([(px_ - 13 * sc_, py_), (px_ + 13 * sc_, py_), (px_ + 13 * sc_, py_ - 150 * sc_), (px_ - 13 * sc_, py_ - 150 * sc_)], hexc('#151c30'))
    fc.dot(px_, py_ - 152 * sc_, 20 * sc_, hexc('#a9bfe4'), ry=12 * sc_)
    fc.dot(px_, py_ + 2, 34 * sc_, hexc('#6b86bc'), ry=9 * sc_)
for i in range(4):
    (xa, ya, sa), (xb_, yb2, sb) = posts[i], posts[i + 1]
    for hf in (0.45, 0.8):
        fc.line([(xa, ya - 150 * sa * hf), (xb_, yb2 - 150 * sb * hf)], hexc('#151c30'), 9 * sa)
        fc.line([(xa, ya - 150 * sa * hf - 7 * sa), (xb_, yb2 - 150 * sb * hf - 7 * sb)], hexc('#a9bfe4'), 6 * sa)
img = fc.onto(img)

# warm light on the wall, the sill snow and the drift
wallglow = glow(1180, 1180, 300, 1.7) * (yy > eave(xx)) * (xx > 830) * (1 - gm)
img += wallglow[..., None] * WARM * 0.55

# ---- brush pass, then the lights ------------------------------------------------------------------
ref = np.clip(img, 0, 1)
flow = np.where(yy < VPY, 0.4 * (fbm((H, W), 280, 2, rng) - 0.5) * 3, 0.25 * (fbm((H, W), 260, 2, rng) - 0.5) * 2)
painted = painterly(ref, rng, sizes=(38, 19, 10, 5, 3), thresh=(0, 0.06, 0.05, 0.04, 0.045), base_angle=flow, relief=0.3, jitter=0.04, length=5)
img = mix(painted, ref, 0.12)
img += stars[..., None] * 0.7
img += glow(FLX, FLY - 6, 11, 2.0)[..., None] * hexc('#fff6d0') * 0.7
img += glow(FLX, FLY, 55, 1.8)[..., None] * hexc('#ffd27a') * 0.25
img += glow(FLX, 1170, 330, 1.5)[..., None] * WARM * 0.13

fl = np.zeros((H, W), F32)
n = 1100
fl[rng.integers(0, H, n), rng.integers(0, W, n)] = rng.random(n) ** 2 + 0.25
flk = blur(fl, 1.4) * 11
fl2 = np.zeros((H, W), F32)
n = 150
fl2[rng.integers(0, H, n), rng.integers(0, W, n)] = rng.random(n) + 0.5
flk2 = blur(fl2, 3.8) * 40
nearw = glow(FLX, 1200, 300, 1.2)
fcol = mix(hexc('#b7cdee'), hexc('#ffd596'), np.clip(nearw * 2.0, 0, 1)[..., None])
img += fcol * ((flk * 0.5 + flk2 * 0.26) * (0.5 + 2.0 * nearw))[..., None]
img = bloom(img, 0.8, (5, 20), (0.22, 0.2))
img = np.clip(img, 0, 1) ** 0.95
finish(img, '10-snowy-village-window', rng, vignette=0.3)
