#!/usr/bin/env python3
"""Fotomontaza: pogled s Maksimirske (kod kafica Lokin) prema stadionu, s gradjanskim konceptom.

Ulaz je autorova fotografija (registarske plocice zamucene, EXIF uklonjen). Izlaz je ista
fotografija u kojoj je danasnji stadion zamijenjen proceduralno nacrtanim konceptom:
plave lamele, bijeli prstenasti krov, rub podignutog parka kao blagi zeleni brezuljak sa stazom,
ljudima i drvecem te ulaz ceste pod parkovni pokrov. Nema generativnog modela: isti ulaz uz iste verzije
biblioteka daje istu sliku.

Sva geometrija je ILUSTRATIVNA (pretpostavke za perspektivu, ne projektne kote); opis u
docs/20_pogled_s_ulice.md. Pokretanje iz korijena repoa:  python3 scripts/render_lokin_view.py
Ovisnosti: Pillow i numpy (requirements.txt).
"""
from __future__ import annotations

import argparse
import math
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / 'dist/assets/photo-maksimirska-lokin-danas.jpg'
OUT = ROOT / 'dist/assets/concept-maksimirska-lokin.jpg'
FONT = Path('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf')
SEED = 20261112

# --- Kamera procijenjena iz fotografije (pretpostavka, ne mjerenje) -------------------------
F = 1515.0          # zarisna duljina u px (telefon ~26 mm ekv., slika 1512 x 2016)
CX = 735.0          # nedogled ulice
CY = 925.0          # visina horizonta u slici
EYE = 1.6           # visina oka iznad ulice, m

# --- Radne pretpostavke montaze (ilustrativno, nisu projektne kote) ------------------------
Z_EDGE = 88.0       # rub podignutog parka i portal ceste, m od kamere
PARK = 8.4          # razina parka iznad ulice, m
PORTAL_TOP = 6.2    # svijetla visina portala, m
ROOF_TOP = 47.0     # vrh krovnog vijenca, m
FIN_TOP = 42.0
SKIN_TOP = 41.0

# Haze calibrated so that the existing stadium (~100 m away) keeps its washed-out look.
HAZE_COLOR = np.array([233.0, 237.0, 240.0])
HAZE_L = 265.0
SKY = np.array([243.0, 245.0, 245.0])

# Render window (photo pixels) and supersampling factor.
U0, V0, U1, V1 = 360, 340, 1200, 960
S = 3


def haze(rgb, z):
    h = 1.0 - math.exp(-z / HAZE_L)
    c = np.asarray(rgb, float) * (1 - h) + HAZE_COLOR * h
    return tuple(int(round(x)) for x in np.clip(c, 0, 255))


def proj(x, y, z):
    u = CX + F * x / z
    v = CY - F * (y - EYE) / z
    return ((u - U0) * S, (v - V0) * S)


def shade(rgb, k):
    return tuple(min(255.0, max(0.0, c * k)) for c in rgb)


def mix(a, b, t):
    return tuple(x * (1 - t) + y * t for x, y in zip(a, b))


class Canvas:
    """Painter's-algorithm canvas in supersampled render-window coordinates.

    Colour is blended onto a sky-coloured RGB image; a separate mask records coverage, so the
    compositor knows where the new scene hides the photograph's background.
    """

    def __init__(self):
        self.w, self.h = (U1 - U0) * S, (V1 - V0) * S
        self.img = Image.new('RGB', (self.w, self.h), tuple(int(c) for c in SKY))
        self.d = ImageDraw.Draw(self.img, 'RGBA')
        self.cov = Image.new('L', (self.w, self.h), 0)
        self.dc = ImageDraw.Draw(self.cov)

    def _poly(self, pts2, rgba):
        self.d.polygon(pts2, fill=rgba)
        self.dc.polygon(pts2, fill=255)

    def poly3(self, pts, rgb, z=None, alpha=255):
        if z is None:
            z = sum(p[2] for p in pts) / len(pts)
        self._poly([proj(*p) for p in pts], haze(rgb, z) + (alpha,))

    def rect(self, x0, x1, y0, y1, z, rgb, alpha=255):
        self.poly3([(x0, y0, z), (x1, y0, z), (x1, y1, z), (x0, y1, z)], rgb, z, alpha)

    def line3(self, a, b, rgb, width_m, z=None, alpha=255):
        z = z or (a[2] + b[2]) / 2
        wpx = max(1, int(round(F * width_m / z * S)))
        pts = [proj(*a), proj(*b)]
        self.d.line(pts, fill=haze(rgb, z) + (alpha,), width=wpx)
        self.dc.line(pts, fill=255, width=wpx)

    def blob(self, x, y, z, rx, ry, rgb, alpha=255):
        u, v = proj(x, y, z)
        px, py = F * rx / z * S, F * ry / z * S
        box = [u - px, v - py, u + px, v + py]
        self.d.ellipse(box, fill=haze(rgb, z) + (alpha,))
        self.dc.ellipse(box, fill=255)

    def line_px(self, a, b, rgba, width):
        self.d.line([a, b], fill=rgba, width=width)
        self.dc.line([a, b], fill=255, width=width)

    def layer(self):
        size = (U1 - U0, V1 - V0)
        rgb = self.img.resize(size, Image.LANCZOS).filter(ImageFilter.GaussianBlur(0.45))
        cov = self.cov.resize(size, Image.LANCZOS).filter(ImageFilter.GaussianBlur(0.45))
        out = rgb.convert('RGBA')
        out.putalpha(cov)
        return out


# --------------------------------------------------------------------------------------------
# Stadium: rounded-rectangle bowl; its north-west corner and north facade face the camera.
# x = south (right), z = east (forward), y = up. Only front-facing parts are drawn.
# --------------------------------------------------------------------------------------------
XN, ZW, RC = 4.0, 121.0, 40.0            # north edge line, west edge line, corner radius
XS, ZE = XN + 250.0, ZW + 215.0          # south and east edge lines (hidden)
LIGHT = np.array([0.35, 0.75, -0.56])
LIGHT /= np.linalg.norm(LIGHT)

FIN_BLUE = (12, 56, 150)
FIN_BLUE_DARK = (8, 34, 96)
SKIN_GLASS = (128, 146, 170)
GLASS_WARM = (238, 176, 98)
SLAB = (170, 174, 180)
ROOF_WHITE = (242, 244, 246)


def facing(x, z, nx, nz):
    """True when the outward facade normal looks toward the camera (convex bowl)."""
    return nx * (0.0 - x) + nz * (0.0 - z) > 0.0


def _perimeter(step):
    pts = []
    cx, cz = XN + RC, ZE - RC                       # north-east corner (far)
    for a in np.arange(180.0, 90.0, -step / RC * 180 / math.pi):
        r = math.radians(a)
        nx, nz = -math.sin(r), -math.cos(r)
        pts.append((cx + RC * nx, cz + RC * nz, nx, nz))
    for z in np.arange(ZE - RC, ZW + RC, -step):     # north facade, far -> near
        pts.append((XN, float(z), -1.0, 0.0))
    cx, cz = XN + RC, ZW + RC                       # north-west corner
    for a in np.arange(90.0, -0.01, -step / RC * 180 / math.pi):
        r = math.radians(a)
        nx, nz = -math.sin(r), -math.cos(r)
        pts.append((cx + RC * nx, cz + RC * nz, nx, nz))
    for x in np.arange(XN + RC + step, XN + RC + 40, step):   # west facade (behind building)
        pts.append((float(x), ZW, 0.0, -1.0))
    return pts


def perimeter(step):
    return [p for p in _perimeter(step) if facing(*p)]


def lit(normal, base, amb=0.62, k=0.38):
    n = np.asarray(normal, float)
    n /= np.linalg.norm(n)
    return shade(base, amb + k * float(np.dot(n, LIGHT)))


def draw_stadium(cv: Canvas, rng):
    seg = perimeter(1.25)
    tone = 1.0
    for i in range(len(seg) - 1):
        x0, z0, nx0, nz0 = seg[i]
        x1, z1, nx1, nz1 = seg[i + 1]
        n = ((nx0 + nx1) / 2, 0.0, (nz0 + nz1) / 2)
        tone = 0.7 * tone + 0.3 * rng.uniform(0.88, 1.1)          # smooth panel variation

        def q(y0, y1, col):
            cv.poly3([(x0, y0, z0), (x1, y0, z1), (x1, y1, z1), (x0, y1, z0)], col)
        # lower concourse: warm interior behind glass
        for k in range(3):
            ya, yb = PARK + k * 1.5, PARK + (k + 1) * 1.5
            q(ya, yb, shade(GLASS_WARM, (0.72 + 0.1 * k) * rng.uniform(0.9, 1.12)))
        q(12.9, 13.5, lit(n, SLAB))
        warm = rng.random() < 0.7
        for k in range(3):
            ya, yb = 13.5 + k * 1.5, 13.5 + (k + 1) * 1.5
            q(ya, yb, shade(GLASS_WARM, 0.55 + 0.09 * k) if warm else (60, 78, 108))
        q(18.0, 18.6, lit(n, SLAB))
        # upper tier: glass skin reflecting the overcast sky, shadowed under the roof
        steps = np.linspace(18.6, SKIN_TOP, 9)
        for k in range(len(steps) - 1):
            t = k / (len(steps) - 2)
            ao = 0.86 + 0.14 * t - 0.36 * max(0.0, t - 0.72) / 0.28
            q(steps[k], steps[k + 1], lit(n, shade(SKIN_GLASS, tone * ao), 0.95, 0.12))
        for yj in np.arange(21.0, SKIN_TOP, 2.5):
            cv.line3((x0, yj, z0), (x1, yj, z1), (118, 128, 142), 0.06)
        cv.line3((x0, PARK, z0), (x0, SKIN_TOP, z0), (110, 120, 134), 0.06)  # mullion
        for yj in (12.9, 18.0):
            cv.line3((x0, yj, z0), (x1, yj, z1), (60, 64, 72), 0.12)

    fins = perimeter(4.2)
    for idx, (x, z, nx, nz) in enumerate(fins):
        tx, tz = -nz, nx
        hb, ht = 0.34, 1.86                 # half width: slender at the base, flaring at the top
        ob, ot = 0.35, 3.4                  # outward lean of the outer edge
        yb, yt = PARK, FIN_TOP
        twist = 0.45 if idx % 2 else -0.45  # alternating facets give the faceted rhythm

        def pt(off, side, y):
            return (x + nx * off + tx * side, y, z + nz * off + tz * side)
        cv.poly3([pt(0.02, -hb - 0.8, yb), pt(0.02, hb + 0.8, yb), pt(0.02, ht + 0.5, SKIN_TOP),
                  pt(0.02, -ht - 0.5, SKIN_TOP)], (70, 84, 110), alpha=60)          # shadow
        for sgn in (-1, 1):
            face = [pt(0.0, sgn * hb, yb), pt(ob, sgn * hb, yb), pt(ot, sgn * ht, yt),
                    pt(0.8, sgn * ht, yt)]
            cv.poly3(face, lit((tx * sgn, 0.0, tz * sgn), FIN_BLUE_DARK, 0.7, 0.3))
        nl = (nx - tx * (0.7 + twist), 0.14, nz - tz * (0.7 + twist))
        nr = (nx + tx * (0.7 - twist), 0.14, nz + tz * (0.7 - twist))
        slices = 7
        for k in range(slices):
            fa, fb = k / slices, (k + 1) / slices
            ya, yb2 = yb + (yt - yb) * fa, yb + (yt - yb) * fb
            oa, obb = ob + (ot - ob) * fa, ob + (ot - ob) * fb
            ha, hbb = hb + (ht - hb) * fa, hb + (ht - hb) * fb
            ra, rbb = oa + 0.2 + 0.35 * fa, obb + 0.2 + 0.35 * fb
            g = 0.86 + 0.2 * (k / (slices - 1))
            cv.poly3([pt(oa, -ha, ya), pt(ra, 0, ya), pt(rbb, 0, yb2), pt(obb, -hbb, yb2)],
                     shade(lit(nl, FIN_BLUE), g))
            cv.poly3([pt(ra, 0, ya), pt(oa, ha, ya), pt(obb, hbb, yb2), pt(rbb, 0, yb2)],
                     shade(lit(nr, FIN_BLUE), g))
        cv.line3(pt(ob + 0.2, 0, yb), pt(ot + 0.55, 0, yt), (60, 100, 196), 0.06)   # ridge
        for sgn in (-1, 1):                                                         # edges
            cv.line3(pt(ob, sgn * hb, yb), pt(ot, sgn * ht, yt), (120, 150, 210), 0.05)
        if idx in (len(fins) - 15, len(fins) - 9):                                  # checker
            for r in range(int(FIN_TOP - 29.0)):
                ya, yb2 = 29.0 + r, 30.0 + r
                fa, fb = (ya - yb) / (yt - yb), (yb2 - yb) / (yt - yb)
                oa, obb = ob + (ot - ob) * fa + 0.45, ob + (ot - ob) * fb + 0.45
                w = 0.5 * (hb + (ht - hb) * fa)
                for c, (s0, s1) in enumerate([(-w, 0.0), (0.0, w)]):
                    col = (196, 34, 44) if (r + c) % 2 == 0 else (238, 238, 236)
                    cv.poly3([pt(oa, s0, ya), pt(oa, s1, ya), pt(obb, s1, yb2),
                              pt(obb, s0, yb2)], lit((nx, 0.1, nz), col))

    ring = perimeter(1.25)
    off_soffit, off_ring = 1.0, 6.0
    lo, hi = SKIN_TOP, SKIN_TOP + 3.0
    for i in range(len(ring) - 1):
        x0, z0, nx0, nz0 = ring[i]
        x1, z1, nx1, nz1 = ring[i + 1]
        n = ((nx0 + nx1) / 2, 0, (nz0 + nz1) / 2)

        def p(x, z, nx, nz, y, off=off_ring):
            return (x + nx * off, y, z + nz * off)
        cv.poly3([p(x0, z0, nx0, nz0, lo + 1.0, off_soffit), p(x1, z1, nx1, nz1, lo + 1.0,
                  off_soffit), p(x1, z1, nx1, nz1, lo), p(x0, z0, nx0, nz0, lo)], (128, 136, 150))
        cv.poly3([p(x0, z0, nx0, nz0, lo), p(x1, z1, nx1, nz1, lo),
                  p(x1, z1, nx1, nz1, hi), p(x0, z0, nx0, nz0, hi)],
                 lit(n, (150, 160, 176), 0.6, 0.2))
        for k, (ya, yb) in enumerate([(hi, hi + 1.0), (hi + 1.0, hi + 2.0), (hi + 2.0, ROOF_TOP)]):
            cv.poly3([p(x0, z0, nx0, nz0, ya), p(x1, z1, nx1, nz1, ya),
                      p(x1, z1, nx1, nz1, yb), p(x0, z0, nx0, nz0, yb)],
                     lit(n, ROOF_WHITE, 0.74 + 0.05 * k, 0.2))
    nodes = perimeter(3.75)
    for i in range(len(nodes) - 1):
        x0, z0, nx0, nz0 = nodes[i]
        x1, z1, nx1, nz1 = nodes[i + 1]
        a = (x0 + nx0 * off_ring, lo if i % 2 == 0 else hi, z0 + nz0 * off_ring)
        b = (x1 + nx1 * off_ring, hi if i % 2 == 0 else lo, z1 + nz1 * off_ring)
        sa = (a[0], a[1] - 0.25, a[2])
        sb = (b[0], b[1] - 0.25, b[2])
        cv.line3(sa, sb, (96, 104, 118), 0.3)                                  # member shadow
        cv.line3(a, b, (250, 251, 252), 0.34)
    for i in range(len(ring) - 1):
        x0, z0, nx0, nz0 = ring[i]
        x1, z1, nx1, nz1 = ring[i + 1]
        cv.line3((x0 + nx0 * off_ring, ROOF_TOP, z0 + nz0 * off_ring),
                 (x1 + nx1 * off_ring, ROOF_TOP, z1 + nz1 * off_ring), (253, 253, 253), 0.3)
        cv.line3((x0 + nx0 * off_ring, hi, z0 + nz0 * off_ring),
                 (x1 + nx1 * off_ring, hi, z1 + nz1 * off_ring), (226, 230, 236), 0.22)
        cv.line3((x0 + nx0 * off_ring, lo, z0 + nz0 * off_ring),
                 (x1 + nx1 * off_ring, lo, z1 + nz1 * off_ring), (236, 238, 240), 0.22)


# --------------------------------------------------------------------------------------------
# Vegetation, people and the edge of the raised park.
# --------------------------------------------------------------------------------------------
AUTUMN = [(196, 150, 52), (214, 172, 70), (178, 104, 44), (150, 86, 48), (120, 112, 52),
          (92, 104, 56), (204, 128, 58), (168, 140, 70)]
EVERGREEN = [(48, 70, 52), (58, 82, 58), (40, 60, 46)]


def _branch(cv, rng, p, d, length, width, depth, tips, bark):
    end = p + d * length
    cv.line3(tuple(p), tuple(end), bark, width)
    if depth == 0:
        tips.append(end)
        return
    for _ in range(int(rng.integers(2, 4))):
        nd = d + rng.normal(0, 0.55, 3)
        nd[1] = abs(nd[1]) + 0.35
        nd /= np.linalg.norm(nd)
        _branch(cv, rng, end, nd, length * rng.uniform(0.62, 0.8), width * 0.62, depth - 1,
                tips, bark)


def draw_tree(cv, rng, x, z, base, height, radius, palette, density=1.0, bare=0.0):
    """Branching deciduous tree; leaves cluster at twig tips, interior shaded."""
    bark = (60, 52, 44)
    tips = []
    trunk = height * 0.38
    p0 = np.array([x, base, z], float)
    cv.line3(tuple(p0), (x, base + trunk, z), bark, 0.3)
    for _ in range(int(rng.integers(3, 5))):
        d = np.array([rng.normal(0, 0.6), 1.0, rng.normal(0, 0.6)])
        d /= np.linalg.norm(d)
        _branch(cv, rng, np.array([x, base + trunk * rng.uniform(0.8, 1.0), z]), d,
                (height - trunk) * 0.42, 0.16, 3, tips, bark)
    tips = [t for t in tips if t[1] < base + height + 1.0]
    cx_, cy_ = x, base + trunk + (height - trunk) * 0.55
    leaves = []
    for t in tips:
        if rng.random() < bare:
            continue
        n = int(70 * density)
        cr = rng.uniform(0.55, 1.0) * radius / 4.0
        pts = t + rng.normal(0, cr, (n, 3)) * np.array([1.0, 0.7, 1.0])
        for q in pts:
            leaves.append(q)
    leaves.sort(key=lambda q: -q[2])
    for q in leaves:
        rel_y = (q[1] - cy_) / radius
        inner = math.hypot(q[0] - cx_, q[2] - z) / radius
        col = palette[rng.integers(len(palette))]
        light = 0.62 + 0.3 * rel_y + 0.22 * min(1.0, inner) + 0.08 * ((q[0] - x) / radius)
        col = shade(col, max(0.35, light) * rng.uniform(0.82, 1.12))
        r = rng.uniform(0.09, 0.2)
        cv.blob(q[0], q[1], q[2], r, r * rng.uniform(0.5, 0.9), col)


def draw_far_trees(cv, rng):
    """Mature park and deck trees beyond the stadium's north edge, seen through gaps."""
    for z in np.linspace(430, 150, 30):
        for x in np.arange(-46.0, 3.0, 2.6):
            xx = x + rng.uniform(-1.2, 1.2)
            h = rng.uniform(15, 24)
            rad = rng.uniform(3.2, 5.2)
            base_col = AUTUMN[rng.integers(len(AUTUMN))] if rng.random() < 0.7 \
                else EVERGREEN[rng.integers(3)]
            cv.blob(xx, PARK + h - rad * 1.1, z, rad * 0.9, rad * 0.7, shade(base_col, 0.55))
            for _ in range(int(60 + rad * 14)):
                cv.blob(xx + rng.normal(0, rad * 0.42), PARK + h - rad + rng.normal(0, rad * 0.36),
                        z + rng.uniform(-2, 2), rad * 0.08, rad * 0.065,
                        shade(base_col, rng.uniform(0.62, 0.95)))


def draw_person(cv, rng, x, z, base, h=1.72, coat=(36, 40, 54), umbrella=None, scarf=None,
                stride=0.0):
    s = h / 1.72
    legs = (34, 34, 38)
    for dx, st in ((-0.075, stride), (0.075, -stride)):
        cv.poly3([(x + dx - 0.06 * s, base, z), (x + dx + 0.06 * s + st, base, z),
                  (x + dx + 0.065 * s, base + 0.86 * s, z), (x + dx - 0.065 * s, base + 0.86 * s, z)],
                 legs)
    long_coat = rng.random() < 0.45
    hem = base + (0.62 if long_coat else 0.82) * s
    cv.poly3([(x - 0.2 * s, hem, z), (x + 0.2 * s, hem, z), (x + 0.23 * s, base + 1.44 * s, z),
              (x - 0.23 * s, base + 1.44 * s, z)], coat)
    cv.poly3([(x - 0.26 * s, base + 0.9 * s, z), (x - 0.2 * s, base + 0.9 * s, z),
              (x - 0.19 * s, base + 1.42 * s, z), (x - 0.25 * s, base + 1.4 * s, z)],
             shade(coat, 0.8))
    cv.poly3([(x + 0.2 * s, base + 0.9 * s, z), (x + 0.26 * s, base + 0.9 * s, z),
              (x + 0.25 * s, base + 1.4 * s, z), (x + 0.19 * s, base + 1.42 * s, z)],
             shade(coat, 1.08))
    if scarf:
        cv.rect(x - 0.13 * s, x + 0.13 * s, base + 1.38 * s, base + 1.48 * s, z - 0.01, scarf)
    hair = [(52, 40, 32), (90, 70, 50), (150, 140, 130), (40, 36, 34)][rng.integers(4)]
    cv.blob(x, base + 1.6 * s, z, 0.1 * s, 0.12 * s, (196, 158, 128))
    cv.blob(x, base + 1.65 * s, z + 0.01, 0.105 * s, 0.07 * s, hair)
    if umbrella:
        u_y = base + 2.02 * s
        cv.line3((x + 0.05, base + 1.3 * s, z), (x + 0.05, u_y, z), (40, 40, 40), 0.025)
        cv.poly3([(x - 0.56, u_y - 0.12, z)] +
                 [(x + 0.56 * math.cos(t), u_y + 0.26 * math.sin(t), z)
                  for t in np.linspace(math.pi, 0, 14)] + [(x + 0.56, u_y - 0.12, z)], umbrella)


def draw_portal_interior(cv, rng):
    x0, x1, top = -27.0, 0.5, PORTAL_TOP
    zs = [Z_EDGE, 100, 140, 165, 230, 255, 420, 700]
    tones = [(46, 48, 52), (30, 32, 36), (168, 176, 182), (28, 30, 34), (140, 148, 156),
             (24, 26, 30), (22, 24, 28)]
    for (za, zb), col in zip(zip(zs[:-1], zs[1:]), tones):
        cv.poly3([(x0, top, za), (x1, top, za), (x1, top, zb), (x0, top, zb)], col, z=Z_EDGE + 6)
        road = (150, 150, 148) if col[0] > 150 else (58, 58, 60)
        cv.poly3([(x0, 0, za), (x1, 0, za), (x1, 0, zb), (x0, 0, zb)], road, z=Z_EDGE + 6)
        wall = (200, 200, 196) if col[0] > 150 else (104, 104, 100)
        cv.poly3([(x1, 0, za), (x1, top, za), (x1, top, zb), (x1, 0, zb)], wall, z=Z_EDGE + 6)
    for (za, zb), col in zip(zip(zs[:-1], zs[1:]), tones):           # left tunnel wall
        wall = (176, 176, 172) if col[0] > 150 else (82, 82, 80)
        cv.poly3([(x0, 0, za), (x0, top, za), (x0, top, zb), (x0, 0, zb)], wall, z=Z_EDGE + 6)
    cv.rect(x0, x1, 0, top, 700, (178, 184, 190))               # far exit, daylight
    for zl in np.arange(102, 560, 9.0):                         # linear tunnel luminaires
        for xl in (-20.0, -13.5, -7.0):
            cv.poly3([(xl - 0.2, top - 0.05, zl), (xl + 0.2, top - 0.05, zl),
                      (xl + 0.2, top - 0.05, zl + 4), (xl - 0.2, top - 0.05, zl + 4)],
                     (255, 242, 214), z=Z_EDGE + 6)


def draw_portal_front(cv):
    """Concrete portal of the road under the park; the hill wraps around it on the right."""
    z = Z_EDGE
    cv.rect(-27.0, 0.5, PORTAL_TOP, PORTAL_TOP + 0.35, z, (88, 88, 86))
    cv.rect(-27.0, 0.5, PORTAL_TOP + 0.35, BROW, z, (176, 173, 166))
    cv.rect(0.5, 2.5, 0.0, BROW, z, (168, 165, 158))
    cv.rect(0.4, 0.55, 0.0, BROW, z, (120, 118, 112))
    cv.rect(-27.0, 2.5, BROW - 0.35, BROW, z - 0.01, (190, 188, 182))          # coping
    cv.rect(-27.0, 2.5, BROW - 0.36, BROW - 0.3, z - 0.02, (120, 118, 112))
    zr = z + 0.2                                       # railing where the portal drops away
    cv.rect(-27.0, 2.5, BROW + 1.0, BROW + 1.07, zr, (176, 180, 184))
    cv.rect(-27.0, 2.5, BROW + 0.5, BROW + 0.54, zr, (160, 164, 168), alpha=200)
    for xp in np.arange(-27.0, 2.6, 1.6):
        cv.rect(xp - 0.025, xp + 0.025, BROW, BROW + 1.05, zr, (150, 154, 158))


# --- the edge of the raised park as a gentle green hill -------------------------------------
BROW = 7.85          # top of the portal lintel; the grass brow rises from here to park level
HILL_LEN = 34.0      # horizontal length of the slope from street to park level (assumption)
RAMP_HALF = 1.2      # half width of the accessible ramp terraces, m
RAMP_LEGS = [(4.0, 44.0, 0.0, 2.1), (44.0, 4.0, 2.1, 4.2), (4.0, 44.0, 4.2, 6.3),
             (44.0, 4.0, 6.3, PARK)]             # switchback legs, about 5 % along x
GRASS = (70, 94, 46)
GRASS_AUTUMN = (104, 104, 56)
STRAW = [(178, 158, 106), (160, 140, 92), (196, 178, 128)]
SHRUBS = [(46, 66, 42), (58, 80, 48), (128, 74, 52), (132, 110, 60), (54, 72, 50)]


def hill_foot(x):
    return 80.0 + 4.0 * math.exp(-max(0.0, x - 2.5) / 4.0) + 1.1 * math.sin(x / 6.5)


def hill_profile(x, z):
    t = min(1.0, max(0.0, (z - hill_foot(x)) / HILL_LEN))
    return PARK * (1 - math.cos(math.pi * t)) / 2


def hill_z(x, y):
    t = math.acos(max(-1.0, min(1.0, 1 - 2 * y / PARK))) / math.pi
    return hill_foot(x) + t * HILL_LEN


def leg_level(leg, x):
    xa, xb, ya, yb = leg
    if not min(xa, xb) - 1.5 <= x <= max(xa, xb) + 1.5:
        return None
    f = min(1.0, max(0.0, (x - xa) / (xb - xa)))
    return ya + (yb - ya) * f


def ground(x, z):
    """Smooth hill surface; ramp terraces are drawn on top as kerbs and rails."""
    return hill_profile(x, z)


def on_ramp(x, z, margin=0.5):
    for leg in RAMP_LEGS:
        y = leg_level(leg, x)
        if y is not None and abs(z - hill_z(x, y)) <= RAMP_HALF + margin:
            return True
    return False


def brow_y(z):
    t = min(1.0, max(0.0, (z - (Z_EDGE + 0.3)) / 7.0))
    return BROW + (PARK - BROW) * (1 - math.cos(math.pi * t)) / 2


def patch(x, z):
    return 0.5 + 0.5 * math.sin(x * 0.33 + z * 0.21) * math.cos(x * 0.12 - z * 0.37)


def draw_park_edge(cv, rng):
    """Hill, brow, ramp, planting, trees and people in one far-to-near painter's order."""
    items = []

    def surface_quad(x0, x1, za, zb, fy):
        ys = [fy(x0, za), fy(x1, za), fy(x1, zb), fy(x0, zb)]
        quad = [(x0, ys[0], za), (x1, ys[1], za), (x1, ys[2], zb), (x0, ys[3], zb)]
        rise = (ys[2] + ys[3] - ys[0] - ys[1]) / 2
        if max(ys) <= 0.01:
            col = (150, 150, 146)                       # pavement at the foot of the hill
        else:
            slope = rise / (zb - za)
            n = np.array([0.0, 1.0, -slope]) / math.sqrt(1 + slope * slope)
            k = 0.68 + 0.32 * float(np.dot(n, LIGHT))
            col = shade(mix(GRASS, GRASS_AUTUMN, 0.25 + 0.5 * patch(x0, za)),
                        k * rng.uniform(0.95, 1.05))
        items.append(((za + zb) / 2, 'poly', (quad, col)))

    for za in np.arange(76.0, 124.0, 0.5):              # the hill right of the portal
        for x0 in np.arange(2.5, 46.0, 1.0):
            surface_quad(x0, x0 + 1.0, za, za + 0.5, ground)
    for za in np.arange(Z_EDGE + 0.3, 104.0, 0.5):      # the grass brow above the portal
        for x0 in np.arange(-27.0, 2.5, 1.0):
            surface_quad(x0, min(2.5, x0 + 1.0), za, za + 0.5, lambda x, z: brow_y(z))

    def place(x, z):
        return (brow_y(z) if x < 2.5 else ground(x, z))

    for _ in range(14000):                              # grass tufts and leaf litter
        x = rng.uniform(-27.0, 46.0)
        z = rng.uniform(78.0, 122.0) if x >= 2.5 else rng.uniform(Z_EDGE + 0.4, 104.0)
        if x >= 2.5 and (z < hill_foot(x) or on_ramp(x, z, 0.1)):
            continue
        col = [GRASS, GRASS_AUTUMN, (96, 118, 58), (140, 108, 66), (70, 94, 46)][rng.integers(5)]
        r = rng.uniform(0.07, 0.16)
        items.append((z, 'blob', (x, place(x, z) + r * 0.6, z, r, r * 0.6,
                                  shade(col, rng.uniform(0.78, 1.12)))))
    for _ in range(170):                                # ornamental grasses (autumn straw)
        x = rng.uniform(2.5, 46.0)
        z = rng.uniform(hill_foot(x) + 3.0, hill_foot(x) + HILL_LEN)
        if on_ramp(x, z, 0.8):
            continue
        r = rng.uniform(0.35, 0.6)
        y = ground(x, z)
        items.append((z, 'clump', (x, y, z, r, STRAW[rng.integers(3)])))
    for _ in range(110):                                # shrubs, some in autumn colour
        x = rng.uniform(-26.0, 46.0)
        z = rng.uniform(hill_foot(x) + 2.0, hill_foot(x) + HILL_LEN + 4.0) if x >= 2.5 \
            else rng.uniform(Z_EDGE + 1.5, 103.0)
        if x >= 2.5 and on_ramp(x, z, 1.2):
            continue
        r = rng.uniform(0.5, 1.1)
        items.append((z, 'shrub', (x, place(x, z), z, r, SHRUBS[rng.integers(len(SHRUBS))])))
    for leg in RAMP_LEGS:                               # ramp legs: kerb, edge line and handrail
        xa, xb = sorted(leg[:2])
        xs = np.arange(max(2.6, xa), xb + 0.01, 0.5)
        for i, (x0, x1) in enumerate(zip(xs[:-1], xs[1:])):
            y0, y1 = leg_level(leg, x0), leg_level(leg, x1)
            if y0 <= 0.05 and y1 <= 0.05:
                continue
            z0, z1 = hill_z(x0, y0) - RAMP_HALF, hill_z(x1, y1) - RAMP_HALF
            items.append(((z0 + z1) / 2 - 0.05, 'kerb', ((x0, y0, z0), (x1, y1, z1), i % 4 == 0)))

    gold = [(206, 164, 62), (218, 178, 74), (188, 142, 54), (170, 120, 50)]
    rust = [(178, 104, 44), (150, 86, 48), (196, 128, 58), (128, 96, 56)]
    trees = [
        # x, z, height, crown radius, palette, density, bare; base follows the ground
        (-23.0, 117.0, 13.0, 4.6, AUTUMN, 1.0, 0.2),
        (-17.0, 104.0, 11.0, 4.0, rust, 1.0, 0.25),
        (-11.5, 111.0, 12.5, 4.4, gold, 1.0, 0.15),
        (-6.8, 98.0, 10.0, 3.6, gold + rust[:1], 1.0, 0.2),
        (-2.2, 108.0, 11.5, 3.8, EVERGREEN + AUTUMN[5:6], 1.3, 0.0),
        (30.0, hill_z(30.0, 4.2), 7.5, 2.8, gold, 0.9, 0.35),
        (17.0, hill_z(17.0, 6.3), 8.0, 2.9, rust, 0.9, 0.35),
        (38.0, hill_z(38.0, 6.7), 7.0, 2.6, AUTUMN, 0.8, 0.4),
        (13.0, 119.0, 9.5, 3.3, AUTUMN, 0.8, 0.45),
        (24.0, 117.5, 9.0, 3.1, gold, 0.8, 0.5),
    ]
    for x, z, h, r, pal, dens, bare in trees:
        items.append((z, 'tree', (x, z, place(x, z), h, r, pal, dens, bare)))

    def ramp_person(leg_i, x):
        y = leg_level(RAMP_LEGS[leg_i], x)
        return (x, hill_z(x, y) + 0.2, y)
    crowd = [
        # x, z, base, height, coat, umbrella, scarf
        (-10.4, 92.0, None, 1.74, (34, 38, 50), (30, 34, 48), None),
        (-8.7, 93.2, None, 1.66, (150, 132, 108), None, (24, 60, 150)),
        (-6.5, 91.6, None, 1.78, (40, 70, 140), (24, 56, 140), None),
        (-1.6, 92.4, None, 1.70, (70, 72, 76), None, None),
        (*ramp_person(2, 12.0), 1.72, (32, 34, 40), (150, 34, 40), None),
        (*ramp_person(2, 13.1), 1.21, (200, 60, 54), None, None),          # child
        (*ramp_person(2, 21.0), 1.68, (60, 64, 52), None, (24, 60, 150)),
        (*ramp_person(3, 9.0), 1.80, (28, 30, 36), (28, 30, 36), None),
        (*ramp_person(3, 18.5), 1.70, (110, 96, 84), None, None),
        (*ramp_person(3, 24.0), 1.73, (30, 52, 110), (24, 56, 140), (240, 240, 240)),
        (*ramp_person(1, 26.0), 1.64, (44, 46, 56), None, None),
        (6.0, 118.5, PARK, 1.70, (130, 40, 44), (34, 34, 40), None),
        (20.4, 119.0, PARK, 1.64, (44, 46, 56), (30, 34, 48), None),
        (21.5, 119.3, PARK, 1.30, (64, 120, 170), None, None),             # child
        (27.0, 118.8, PARK, 1.76, (30, 52, 110), (24, 56, 140), None),
    ]
    for x, z, base, h, coat, umb, scarf in crowd:
        b = base if base is not None else place(x, z)
        items.append((z - 0.02, 'person', (x, z, b, h, coat, umb, scarf)))

    items.sort(key=lambda it: -it[0])
    for _, kind, d in items:
        if kind == 'poly':
            cv.poly3(*d)
        elif kind == 'blob':
            cv.blob(*d)
        elif kind == 'clump':
            x, y, z, r, col = d
            cv.blob(x, y + r * 0.12, z, r * 0.6, r * 0.18, shade(col, 0.5))
            for k in range(16):
                ang = rng.uniform(-0.9, 0.9)
                length = r * rng.uniform(1.0, 1.7)
                tip = (x + math.sin(ang) * length * 0.6, y + math.cos(ang) * length, z - 0.02)
                cv.line3((x + ang * 0.05, y, z - 0.02), tip,
                         shade(col, rng.uniform(0.8, 1.15)), 0.03)
                if k % 4 == 0:                              # seed heads
                    cv.blob(tip[0], tip[1], tip[2], 0.05, 0.09, shade(col, 1.15))
        elif kind == 'shrub':
            x, y, z, r, col = d
            cv.blob(x, y + r * 0.5, z, r, r * 0.62, shade(col, 0.55))
            for k in range(9):
                cv.blob(x + rng.normal(0, r * 0.4), y + r * (0.55 + 0.35 * rng.random()),
                        z - 0.03, r * 0.32, r * 0.26, shade(col, rng.uniform(0.75, 1.15)))
        elif kind == 'kerb':
            a, b2, post = d
            cv.poly3([(a[0], a[1] - 0.42, a[2]), (b2[0], b2[1] - 0.42, b2[2]),
                      (b2[0], b2[1] + 0.06, b2[2]), (a[0], a[1] + 0.06, a[2])], (176, 174, 166))
            cv.line3((a[0], a[1] + 0.06, a[2]), (b2[0], b2[1] + 0.06, b2[2]), (214, 212, 204), 0.05)
            cv.line3((a[0], a[1] + 0.95, a[2] + 0.1), (b2[0], b2[1] + 0.95, b2[2] + 0.1),
                     (198, 200, 202), 0.045)
            if post:
                cv.line3((a[0], a[1] + 0.06, a[2] + 0.1), (a[0], a[1] + 0.95, a[2] + 0.1),
                         (168, 170, 172), 0.035)
        elif kind == 'tree':
            x, z, base, h, r, pal, dens, bare = d
            draw_tree(cv, rng, x, z, base, h, r, pal, dens, bare)
        elif kind == 'person':
            x, z, base, h, coat, umb, scarf = d
            draw_person(cv, rng, x, z, base, h, coat, umb, scarf, stride=rng.uniform(-0.12, 0.12))


def draw_wires(cv):
    """Existing tram/street wires in front of the stadium, measured from the photo."""
    def px(u, v):
        return ((u - U0) * S, (v - V0) * S)
    cv.line_px(px(900, 685.6), px(1190, 679.1), (58, 62, 66, 255), 2 * S)
    cv.line_px(px(905, 772.4), px(1190, 710.0), (96, 104, 112, 230), int(1.3 * S))


def render_layer(rng):
    cv = Canvas()
    draw_far_trees(cv, rng)
    draw_stadium(cv, rng)
    draw_park_edge(cv, rng)
    draw_portal_interior(cv, rng)
    draw_portal_front(cv)
    draw_wires(cv)
    return cv.layer()


# --------------------------------------------------------------------------------------------
# Compositing into the photograph: foreground (trees, poles, signs, cars, buildings) stays.
# --------------------------------------------------------------------------------------------
def box_blur(a, r):
    if r <= 0:
        return a
    img = Image.fromarray(np.clip(a * 255, 0, 255).astype(np.uint8))
    return np.asarray(img.filter(ImageFilter.GaussianBlur(r))).astype(float) / 255


def min_filter(a, size):
    img = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
    return np.asarray(img.filter(ImageFilter.MinFilter(size))).astype(float)


def masks(roi):
    h, w, _ = roi.shape
    vv, uu = np.mgrid[V0:V0 + h, U0:U0 + w]
    R, G, B = roi[..., 0], roi[..., 1], roi[..., 2]
    lum = roi.mean(2)
    # right boundary: left edge of the yellow building
    u_edge = np.where(vv < 600, 1183.5 + (600 - vv) * 0.015, 1183.5)
    inside_w = uu < u_edge
    old = inside_w & (uu >= 738) & (vv >= 603) & (vv < 950)
    gap = (~old) & inside_w & (((uu >= 545) & (uu < 738) & (vv >= 780) & (vv < 940)) |
                               ((uu >= 690) & (uu < 738) & (vv >= 640) & (vv < 780)))
    roof_u = [540, 560, 650, 660, 700, 720, 760, 800, 860, 880, 902, 903, 937, 938, 1000, 1200]
    roof_v = [921, 920, 920, 933, 931, 927, 924, 923, 919, 917, 915, 889, 889, 912, 911, 910]
    below_roof = vv >= np.interp(uu, roof_u, roof_v)
    inside_w &= ~below_roof
    old &= ~below_roof
    gap &= ~below_roof
    leaf = (R - B > 22) & (G - B > 8)
    dark = (lum < 82) & (B - R < 18)
    pole = (lum > 168) & (np.abs(B - R) < 24) & (np.abs(R - G) < 20) & (lum < 228)
    red = (R > 140) & (R - G > 60)
    bluesign = (B - R > 95) & (lum < 150)
    banner = (uu >= 1150) & (uu < 1193) & (vv >= 686) & (vv < 888)
    # the old banner peeks out a few pixels beyond the building corner; take only bluish pixels
    bannerish = (B - R > 6) | ((G < R - 20) & (B > G + 15))
    old |= (uu >= 1183) & (uu < 1193) & (vv >= 686) & (vv < 872) & bannerish & ~below_roof
    fg_old = (leaf | dark | pole | red | bluesign) & ~banner
    m_old = old & (~fg_old | ((vv < 611) & ~leaf & ~dark))
    bg_like = (lum > 80) & (lum < 200) & (np.abs(R - G) < 24) & (np.abs(G - B) < 28) & ~leaf
    m_gap = gap & bg_like & ~dark
    # sky everywhere else inside the window: thin dark things (branches, wires) are unmixed
    # against the sky; street lamps hanging in the sky are protected explicitly.
    floc = np.minimum(min_filter(lum, 7), 120.0)
    a_sky = np.clip((lum - floc) / np.maximum(SKY.mean() - floc, 1), 0, 1)
    a_sky *= ((lum > 120) & inside_w & ~old & ~gap & (vv < 905))
    lamps = np.zeros_like(lum, bool)
    for u0, v0, u1, v1 in [(998, 463, 1028, 492), (993, 562, 1014, 586), (1015, 480, 1026, 604),
                           (1088, 500, 1140, 556)]:
        lamps |= (uu >= u0) & (uu < u1) & (vv >= v0) & (vv < v1)
    a_sky = np.where(lamps, np.clip((lum - 214.0) / 24.0, 0, 1), a_sky)
    return (box_blur(m_old.astype(float), 0.6) * old, box_blur(m_gap.astype(float), 0.6) * gap,
            a_sky)


def composite(photo: Image.Image, layer: Image.Image, rng) -> Image.Image:
    a = np.asarray(photo).astype(float)
    roi = a[V0:V1, U0:U1].copy()
    lay = np.asarray(layer).astype(float)
    new_rgb, new_a = lay[..., :3], lay[..., 3:] / 255.0
    m_old, m_gap, a_sky = masks(roi)
    opaque = new_rgb + rng.normal(0, 1.2, new_rgb.shape) * (1 - new_a)   # layer is over sky
    sharp = np.asarray(layer.convert('RGB').filter(ImageFilter.UnsharpMask(1.2, 60, 2))).astype(float)
    new_rgb = new_rgb * 0.5 + sharp * 0.5
    grain = rng.normal(0, 2.6, new_rgb.shape[:2])[..., None] + rng.normal(0, 0.9, new_rgb.shape)
    opaque_g = opaque + grain
    out = roi.copy()
    for m in (m_old, m_gap):
        out = out * (1 - m[..., None]) + opaque_g * m[..., None]
    out = out + (a_sky[..., None] * new_a) * (new_rgb + grain - SKY)
    a[V0:V1, U0:U1] = out
    return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))


def label(img: Image.Image) -> Image.Image:
    img = img.convert('RGBA')
    over = Image.new('RGBA', img.size, (0, 0, 0, 0))
    d = ImageDraw.Draw(over)
    font = ImageFont.truetype(str(FONT), 25)
    text = 'GRAĐANSKA VIZIJA · AI KONCEPT · FOTOMONTAŽA'
    w = d.textbbox((0, 0), text, font=font)[2]
    x, y = img.width - w - 34, img.height - 66      # bottom right: stays on the vision side
    bbox = d.textbbox((x, y), text, font=font)
    d.rounded_rectangle([bbox[0] - 14, bbox[1] - 10, bbox[2] + 14, bbox[3] + 10], 8,
                        fill=(8, 22, 44, 170))
    d.text((x, y), text, font=font, fill=(255, 255, 255, 240))
    img.alpha_composite(over)
    return img.convert('RGB')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--src', default=str(SRC))
    ap.add_argument('--out', default=str(OUT))
    ap.add_argument('--layer', default=None, help='debug: also save the render layer')
    args = ap.parse_args()
    rng = np.random.default_rng(SEED)
    photo = Image.open(args.src).convert('RGB')
    layer = render_layer(rng)
    if args.layer:
        layer.convert('RGB').save(args.layer)
    out = label(composite(photo, layer, rng))
    out.save(args.out, quality=90, optimize=True)
    print(args.out)


if __name__ == '__main__':
    main()
