ExperimentsFable 5.2 Python art (30 images)

Imaginary island map, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""16 Imaginary island map.

The script invents an island as a height map (layers of smooth noise shaped by
a few soft blobs), then treats it like real terrain. Water is routed downhill
with a "priority flood" so every cell drains to the sea; cells that collect
enough water become rivers, and filled hollows become lakes. The map is drawn
with elevation tints, hill shading from the north-west, contour lines, coastal
water lines, woodland dots, peaks, towns, a scale bar and a compass rose, all
built from lines and polygons (no fonts).
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/16-imaginary-island-map.py
"""
import os, time, math, heapq
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '16-imaginary-island-map.png')
F32 = np.float32
rng = np.random.default_rng(1616)


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 smoothstep(a, b, x):
    t = np.clip((x - a) / (b - a), 0, 1)
    return t * t * (3 - 2 * t)


def vnoise(cell):
    """Smooth noise, roughly -1..1: random grid enlarged with cubic interpolation."""
    gh, gw = int(H / cell) + 4, int(W / cell) + 4
    g = rng.standard_normal((gh, gw)).astype(F32)
    z = ndi.zoom(g, cell, order=3)
    o = int(cell * 1.5)
    return z[o:o + H, o:o + W] * 0.6


def ramp(t, stops):
    pos = [p for p, _ in stops]
    cols = np.array([hexc(c) for _, c in stops])
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)


yy, xx = np.mgrid[0:H, 0:W].astype(F32)

# ----------------------------------------------------------------------------
# 1. Terrain
# ----------------------------------------------------------------------------
# Warp the coordinates so that coasts are not simple ovals.
wx = xx + 95 * vnoise(170) + 26 * vnoise(55)
wy = yy + 95 * vnoise(170) + 26 * vnoise(55)


def blob(cx, cy, sx, sy, rot, amp):
    c, s = math.cos(rot), math.sin(rot)
    dx = wx - cx * W; dy = wy - cy * H
    u = (dx * c + dy * s) / (sx * W); v = (-dx * s + dy * c) / (sy * W)
    return amp * np.exp(-(u * u + v * v))


shape = (blob(0.47, 0.40, 0.25, 0.33, 0.45, 1.00) + blob(0.60, 0.62, 0.22, 0.20, -0.3, 0.80)
         + blob(0.34, 0.60, 0.13, 0.12, 0.2, 0.45)
         + blob(0.80, 0.86, 0.055, 0.04, 0.6, 0.62) + blob(0.86, 0.165, 0.05, 0.035, -0.5, 0.60)
         + blob(0.70, 0.90, 0.03, 0.025, 0.0, 0.50) + blob(0.155, 0.27, 0.035, 0.03, 0.3, 0.52))
fbm = (vnoise(150) * 1.0 + vnoise(75) * 0.5 + vnoise(38) * 0.26 + vnoise(19) * 0.13 + vnoise(9) * 0.06)
ridge = 1 - np.abs(vnoise(120) * 1.2 + vnoise(50) * 0.45)            # sharp crests
ridge = np.clip(ridge, 0, 1) ** 2.2
base = shape - 0.36 + 0.17 * fbm
elev = np.where(base > 0, base, base * 0.6)
inland = smoothstep(0.02, 0.45, base)
# Distance from the coast has no hollows, so mixing it in gives the island a
# steady fall toward the sea (fewer closed basins, better rivers).
dcoast = ndi.gaussian_filter(ndi.distance_transform_edt(base > 0).astype(F32), 14)
dcoast /= dcoast.max()
elev = elev * (0.45 + 0.20 * fbm) + 0.42 * dcoast ** 0.85 + inland ** 1.6 * ridge * 0.36 + inland * 0.05 * vnoise(30)
elev = ndi.gaussian_filter(elev, 1.6)
h = (elev / elev.max() * 1480.0).astype(F32)                         # metres; sea is negative
h[base <= 0] = np.minimum(h[base <= 0], -1.0)
h = np.where(h > 0, np.maximum(h, 1.0), h)
print('terrain done %.1fs  max %.0f m, land %.2f' % (time.time() - T0, h.max(), (h > 0).mean()))

# ----------------------------------------------------------------------------
# 2. Drainage on a coarse grid: priority flood, flow accumulation, rivers, lakes
# ----------------------------------------------------------------------------
CS = 5
hc = ndi.gaussian_filter(h, 2.0)[CS // 2::CS, CS // 2::CS].astype(np.float64)
ch, cw = hc.shape
hc = hc + rng.normal(0, 0.8, hc.shape)                               # tiny noise breaks ties
filled = hc.copy()
recv = -np.ones(ch * cw, np.int64)                                   # the cell each cell drains to
done = np.zeros(ch * cw, bool)
heap = []
sea_c = hc <= 0
for i in np.flatnonzero(sea_c.ravel()):
    done[i] = True
# start from sea cells that touch land
edge_c = sea_c & ndi.binary_dilation(~sea_c, np.ones((3, 3), bool))
for i in np.flatnonzero(edge_c.ravel()):
    heapq.heappush(heap, (0.0, int(i)))
order = []
NB = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
ff = filled.ravel()
while heap:
    z, i = heapq.heappop(heap)
    y, x = divmod(i, cw)
    for dy, dx in NB:
        ny, nx = y + dy, x + dx
        if 0 <= ny < ch and 0 <= nx < cw:
            j = ny * cw + nx
            if not done[j]:
                done[j] = True
                ff[j] = max(ff[j], z + 0.02 * (1.4 if dy and dx else 1.0))
                recv[j] = i
                order.append(j)
                heapq.heappush(heap, (ff[j], j))
# Rain: a little more in the hills. Add it up from the last-reached cells down.
acc = (1.0 + np.clip(hc, 0, None) / 700.0).ravel().copy()
acc[sea_c.ravel()] = 0
for j in reversed(order):
    r = recv[j]
    if r >= 0 and not sea_c.ravel()[r]:
        acc[r] += acc[j]
acc2 = acc.reshape(ch, cw)
lake_c = ((filled - hc) > 5.0) & ~sea_c
lake_c = ndi.binary_opening(lake_c, iterations=1)
lab, nlab = ndi.label(lake_c)
if nlab:
    sizes = ndi.sum(lake_c, lab, range(1, nlab + 1))
    big = sorted([(s, k + 1) for k, s in enumerate(sizes) if s >= 14], reverse=True)[:5]
    lake_c = np.isin(lab, [k for s, k in big])
RIVER_T = 150.0
is_river = (acc2 > RIVER_T) & ~sea_c
print('drainage done %.1fs  river cells %d  lake cells %d' % (time.time() - T0, is_river.sum(), lake_c.sum()))

# Trace river polylines from their sources down to the sea.
has_up = np.zeros(ch * cw, bool)
for j in np.flatnonzero(is_river.ravel()):
    r = recv[j]
    if r >= 0 and is_river.ravel()[r]:
        has_up[r] = True
sources = [j for j in np.flatnonzero(is_river.ravel()) if not has_up[j]]
sources.sort(key=lambda j: -hc.ravel()[j])
seen = np.zeros(ch * cw, bool)
rivers = []                                    # list of (points [(x, y)], widths)
mouths = []
for s in sources:
    pts, wd = [], []
    j = s
    while j >= 0:
        y, x = divmod(j, cw)
        pts.append((x * CS + CS / 2, y * CS + CS / 2)); wd.append(acc[j])
        if sea_c.ravel()[j]:
            break
        if seen[j]:
            break
        seen[j] = True
        nxt = recv[j]
        if nxt >= 0 and sea_c.ravel()[nxt]:
            mouths.append((acc[j], x * CS + CS / 2, y * CS + CS / 2))
        j = nxt
    # A river that crosses a lake is cut into the part above and the part below it.
    inlake = [bool(lake_c[min(int(py // CS), ch - 1), min(int(px // CS), cw - 1)]) for px, py in pts]
    start = 0
    for k in range(len(pts) + 1):
        if k == len(pts) or inlake[k]:
            lo, hi = max(start - 1, 0), min(k + 1, len(pts))        # one point of overlap into the lake
            if k - start >= 3:
                rivers.append((np.array(pts[lo:hi], float), np.array(wd[lo:hi], float)))
            start = k + 1


def smooth_line(p, w, passes=3):
    """Moving average, then Chaikin corner cutting: turns grid steps into bends."""
    q = p.copy()
    for _ in range(2):
        q[1:-1] = (q[:-2] + 2 * q[1:-1] + q[2:]) / 4
    for _ in range(passes - 1):
        a = 0.75 * q[:-1] + 0.25 * q[1:]; b = 0.25 * q[:-1] + 0.75 * q[1:]
        q = np.concatenate([q[:1], np.stack([a, b], 1).reshape(-1, 2), q[-1:]])
        wa = 0.75 * w[:-1] + 0.25 * w[1:]; wb = 0.25 * w[:-1] + 0.75 * w[1:]
        w = np.concatenate([w[:1], np.stack([wa, wb], 1).ravel(), w[-1:]])
    return q, w


rivers = [smooth_line(p, w) for p, w in rivers]
# Meanders: push every river sideways with a slow noise field (less at both ends).
mnx, mny = vnoise(34), vnoise(34)
for p, w in rivers:
    xi = np.clip(p[:, 0].astype(int), 0, W - 1); yi = np.clip(p[:, 1].astype(int), 0, H - 1)
    n = len(p)
    taper = np.minimum(np.arange(n), np.arange(n)[::-1]) / 6.0
    taper = np.clip(taper, 0, 1)[:, None]
    p += np.stack([mnx[yi, xi], mny[yi, xi]], 1) * 9.0 * taper

# Carve the valleys a little, so the contour lines bend upstream.
rmask = np.zeros((H, W), F32)
im_r = Image.new('F', (W, H), 0.0)
dr = ImageDraw.Draw(im_r)
for p, w in rivers:
    dr.line([tuple(q) for q in p], fill=1.0, width=5)
rmask = ndi.gaussian_filter(np.asarray(im_r, F32), 7)
rmask /= rmask.max() + 1e-6
h_land = np.where(h > 0, np.maximum(h - 38 * rmask * smoothstep(0, 120, h), 1.0), h)
h = ndi.gaussian_filter(h_land, 1.0)
h = np.where(base > 0, np.maximum(h, 1.0), np.minimum(h, -1.0))
land = base > 0
lake = ndi.gaussian_filter(ndi.zoom(lake_c.astype(F32), CS, order=1)[:H, :W], 2.5) > 0.5
lake &= land

# ----------------------------------------------------------------------------
# 3. Raster layers: sea, tints, hill shade, contours
# ----------------------------------------------------------------------------
d_sea = ndi.distance_transform_edt(~land).astype(F32)       # distance from the coast, in the sea
d_land = ndi.distance_transform_edt(land).astype(F32)

# Sea: pale near the coast, deeper blue far away, with soft depth bands.
depth = np.clip(d_sea / 420.0, 0, 1) ** 0.7 + 0.05 * vnoise(120)
depth_b = np.floor(np.clip(depth, 0, 0.999) * 6) / 6 * 0.75 + depth * 0.25
sea = ramp(depth_b, [(0.0, '#e4eee6'), (0.25, '#cfe3e0'), (0.55, '#b3d3d8'), (1.0, '#8fbccb')])
# Water lines that follow the coast, fading away from it.
for k, dist in enumerate([7, 16, 27, 40, 55]):
    line = 1 - smoothstep(0.5, 1.5, np.abs(d_sea - dist))
    sea = sea * (1 - line[..., None] * (0.50 - 0.09 * k)) + hexc('#4d86a3') * line[..., None] * (0.50 - 0.09 * k)

# Land: elevation tints.
tint = ramp(h, [(0, '#c5d6a0'), (60, '#b4cf94'), (180, '#cfd89b'), (330, '#e8e0a6'), (520, '#e6c98a'),
                (760, '#cfa371'), (1000, '#b08462'), (1220, '#a98f80'), (1360, '#e9e4dc'), (1500, '#ffffff')])
beach = (1 - smoothstep(4, 16, h)) * (1 - smoothstep(6, 18, d_land))
tint = tint * (1 - beach[..., None] * 0.8) + hexc('#f0e2b4') * beach[..., None] * 0.8

# Woodland: darker green patches on the lower slopes.
wood_n = vnoise(60) + 0.5 * vnoise(22)
gy, gx = np.gradient(ndi.gaussian_filter(h, 2.0))
slope = np.hypot(gx, gy)
wood = smoothstep(0.05, 0.45, wood_n) * smoothstep(20, 60, h) * (1 - smoothstep(380, 560, h)) * (1 - smoothstep(9, 16, slope))
tint = tint * (1 - 0.30 * wood[..., None]) + hexc('#6f9a62') * 0.30 * wood[..., None]

# Hill shade: sun in the north-west.
ZF = 0.085
nxv, nyv = -gx * ZF, -gy * ZF
nz = 1 / np.sqrt(nxv * nxv + nyv * nyv + 1)
Lx, Ly, Lz = -0.5, -0.5, 0.7071
shade = (nxv * Lx + nyv * Ly + Lz) * nz
shade2 = ndi.gaussian_filter(shade, 6)                       # soft and crisp shading mixed
sh = 0.6 * shade + 0.4 * shade2
landc = tint * (0.50 + 0.72 * sh)[..., None]
landc += np.clip(sh - 0.7071, 0, 1)[..., None] * hexc('#fff3d0') * 0.35     # warm light on sunny slopes
landc = landc * (1 - 0.0) + (np.clip(0.7071 - sh, 0, 1) * 0.22)[..., None] * (hexc('#3d4a6b') - landc)  # cool shadows

# Contours: 50 m lines, every fifth one heavier. Constant width whatever the slope.
hs = ndi.gaussian_filter(h, 1.2)
cgy, cgx = np.gradient(hs)
cg = np.hypot(cgx, cgy) + 1e-4


def contour(interval, width):
    f = hs / interval
    dist = np.abs(f - np.round(f)) * interval / cg          # pixels to the nearest line
    return 1 - smoothstep(width - 0.6, width + 0.6, dist)


c_minor = contour(50.0, 0.55) * (hs > 20)
c_major = contour(250.0, 1.05) * (hs > 20)
# very flat ground makes fat lines; fade them there
flat = smoothstep(0.25, 0.9, cg)
c_minor *= flat; c_major *= flat
ink_c = hexc('#7d5632')
landc = landc * (1 - 0.42 * c_minor[..., None]) + ink_c * 0.42 * c_minor[..., None]
landc = landc * (1 - 0.78 * c_major[..., None]) + ink_c * 0.78 * c_major[..., None]

img = np.where(land[..., None], landc, sea)

# Lakes
lk = ndi.gaussian_filter(lake.astype(F32), 1.0)
img = img * (1 - lk[..., None]) + hexc('#a9d0dc') * lk[..., None]
lk_edge = np.clip(1 - np.abs(lk - 0.5) * 4, 0, 1)
img = img * (1 - 0.7 * lk_edge[..., None]) + hexc('#3f7797') * 0.7 * lk_edge[..., None]

# Coastline: a firm dark line with a soft inner glow.
coast = 1 - smoothstep(1.0, 2.2, d_sea + d_land)
img = img * (1 - 0.85 * coast[..., None]) + hexc('#2f4553') * 0.85 * coast[..., None]
print('raster done %.1fs' % (time.time() - T0))

# ----------------------------------------------------------------------------
# 4. Vector overlay (drawn at 2x, scaled down): rivers, symbols, frame, compass
# ----------------------------------------------------------------------------
S = 2
ov = Image.new('RGBA', (W * S, H * S), (0, 0, 0, 0))
d = ImageDraw.Draw(ov)
RIV = (58, 118, 158, 255)


def P(x, y):
    return (x * S, y * S)


# Rivers: width grows with the water collected.
for p, w in rivers:
    wpx = np.clip(0.75 + 0.33 * np.sqrt(w / RIVER_T) ** 1.25, 0.8, 5.0)
    for k in range(len(p) - 1):
        ww = max(1, int(round(wpx[k] * S)))
        d.line([P(*p[k]), P(*p[k + 1])], fill=RIV, width=ww)
        r = ww / 2
        d.ellipse((p[k][0] * S - r, p[k][1] * S - r, p[k][0] * S + r, p[k][1] * S + r), fill=RIV)

# Woodland dots (tiny tree marks).
gxs = np.arange(60, W - 60, 9.0); gys = np.arange(60, H - 60, 9.0)
TX, TY = np.meshgrid(gxs, gys)
TX = (TX + rng.uniform(-4, 4, TX.shape)).ravel(); TY = (TY + rng.uniform(-4, 4, TY.shape)).ravel()
tw = wood[TY.astype(int), TX.astype(int)]
keep = ((tw > 0.55) & (rng.random(TX.size) < 0.75) & (rmask[TY.astype(int), TX.astype(int)] < 0.25)
        & ~lake[TY.astype(int), TX.astype(int)])
for x, y in zip(TX[keep], TY[keep]):
    r = rng.uniform(1.6, 2.6) * S
    d.ellipse((x * S - r, y * S - r, x * S + r, y * S + r), fill=(58, 104, 66, 200))
    d.ellipse((x * S - r * 0.6, y * S - r * 0.7, x * S + r * 0.1, y * S), fill=(112, 156, 100, 160))

# Peaks: small triangles on the highest summits.
mx = ndi.maximum_filter(h, size=170)
py_, px_ = np.nonzero((h == mx) & (h > 640))
peaks = sorted(zip(h[py_, px_], px_, py_), reverse=True)[:9]
for hh, x, y in peaks:
    s = 9
    d.polygon([P(x, y - s), P(x + s * 0.9, y + s * 0.7), P(x - s * 0.9, y + s * 0.7)], fill=(52, 40, 34, 255))
    d.polygon([P(x, y - s), P(x + s * 0.9, y + s * 0.7), P(x, y + s * 0.7)], fill=(250, 246, 236, 255))
    d.line([P(x, y - s), P(x + s * 0.9, y + s * 0.7), P(x - s * 0.9, y + s * 0.7), P(x, y - s)], fill=(52, 40, 34, 255), width=2)

# Towns at the mouths of the largest rivers (kept apart from each other).
mouths.sort(reverse=True)
towns = []
for a, x, y in mouths:
    if all(math.hypot(x - tx, y - ty) > 260 for tx, ty in towns) and 110 < x < W - 110 and 110 < y < H - 110:
        towns.append((x, y))
    if len(towns) == 5:
        break
for k, (x, y) in enumerate(towns):
    r = 8 if k == 0 else 6
    d.ellipse((x * S - (r + 3) * S, y * S - (r + 3) * S, x * S + (r + 3) * S, y * S + (r + 3) * S), fill=(250, 244, 230, 255),
              outline=(40, 34, 30, 255), width=3)
    d.ellipse((x * S - r * S + 3, y * S - r * S + 3, x * S + r * S - 3, y * S + r * S - 3), fill=(176, 44, 38, 255))
    if k == 0:                                    # the capital gets a star-like cross
        d.line([P(x - 3, y), P(x + 3, y)], fill=(250, 244, 230, 255), width=3)
        d.line([P(x, y - 3), P(x, y + 3)], fill=(250, 244, 230, 255), width=3)

# Frame: a ladder border with alternating blocks.
M = 58                                             # margin of the map area
INK = (46, 38, 32, 255)
PAPER = (240, 230, 208, 255)
d.rectangle((0, 0, W * S, M * S), fill=PAPER); d.rectangle((0, (H - M) * S, W * S, H * S), fill=PAPER)
d.rectangle((0, 0, M * S, H * S), fill=PAPER); d.rectangle(((W - M) * S, 0, W * S, H * S), fill=PAPER)
B0, B1 = M - 22, M - 6                             # the ladder sits between these distances from the edge
d.rectangle((B0 * S, B0 * S, (W - B0) * S, (H - B0) * S), outline=INK, width=5)
d.rectangle((B1 * S, B1 * S, (W - B1) * S, (H - B1) * S), outline=INK, width=3)
d.rectangle((M * S, M * S, (W - M) * S, (H - M) * S), outline=INK, width=3)
STEP = (W - 2 * B1) / 12.0
n_h = 12; n_v = int(round((H - 2 * B1) / STEP)); STEPV = (H - 2 * B1) / n_v
for k in range(n_h):
    if k % 2 == 0:
        x0 = B1 + k * STEP
        d.rectangle((x0 * S, B0 * S, (x0 + STEP) * S, B1 * S), fill=INK)
        d.rectangle(((x0 + STEP) * S if False else (W - x0 - STEP) * S, (H - B1) * S, (W - x0) * S, (H - B0) * S), fill=INK)
for k in range(n_v):
    if k % 2 == 0:
        y0 = B1 + k * STEPV
        d.rectangle((B0 * S, y0 * S, B1 * S, (y0 + STEPV) * S), fill=INK)
        d.rectangle(((W - B1) * S, (H - y0 - STEPV) * S, (W - B0) * S, (H - y0) * S), fill=INK)
# small ticks inside the frame
for k in range(1, n_h * 4):
    x = B1 + k * STEP / 4
    ln = 9 if k % 4 == 0 else 5
    d.line([P(x, M), P(x, M + ln)], fill=INK, width=2); d.line([P(x, H - M), P(x, H - M - ln)], fill=INK, width=2)
for k in range(1, n_v * 4):
    y = B1 + k * STEPV / 4
    ln = 9 if k % 4 == 0 else 5
    d.line([P(M, y), P(M + ln, y)], fill=INK, width=2); d.line([P(W - M, y), P(W - M - ln, y)], fill=INK, width=2)

# Scale bar (bottom right, in the sea).
sx0, sy0, seg = W - 470, H - 128, 70
d.rectangle((sx0 * S - 4, sy0 * S - 4, (sx0 + seg * 5) * S + 4, (sy0 + 10) * S + 4), fill=(250, 244, 230, 255), outline=INK, width=3)
for k in range(5):
    if k % 2 == 0:
        d.rectangle(((sx0 + k * seg) * S, sy0 * S, (sx0 + (k + 1) * seg) * S, (sy0 + 10) * S), fill=INK)
for k in range(6):
    d.line([P(sx0 + k * seg, sy0 - 12), P(sx0 + k * seg, sy0 - 2)], fill=INK, width=3)
for k in range(4):                                 # finer divisions of the first segment
    d.line([P(sx0 + k * seg / 4, sy0 - 7), P(sx0 + k * seg / 4, sy0 - 2)], fill=INK, width=2)

# Compass rose.
RX, RY, RR = 300.0, 1655.0, 150.0
DARK = (46, 60, 78, 255); LIGHT = (246, 238, 220, 255); RED = (170, 48, 40, 255); GOLD = (200, 150, 70, 255)


def point(angle, length, half, dark, light):
    """One spear of the rose, split into a dark and a light half."""
    a = math.radians(angle)
    tip = (RX + length * math.sin(a), RY - length * math.cos(a))
    bl = (RX + half * math.sin(a - math.pi / 2), RY - half * math.cos(a - math.pi / 2))
    br = (RX + half * math.sin(a + math.pi / 2), RY - half * math.cos(a + math.pi / 2))
    d.polygon([P(*tip), P(*bl), P(RX, RY)], fill=light)
    d.polygon([P(*tip), P(*br), P(RX, RY)], fill=dark)
    d.line([P(*tip), P(*bl), P(RX, RY), P(*br), P(*tip)], fill=INK, width=2)
    d.line([P(*tip), P(RX, RY)], fill=INK, width=2)


def ring(r, width, col=INK):
    d.ellipse(((RX - r) * S, (RY - r) * S, (RX + r) * S, (RY + r) * S), outline=col, width=width)


d.ellipse(((RX - RR * 0.80) * S, (RY - RR * 0.80) * S, (RX + RR * 0.80) * S, (RY + RR * 0.80) * S), fill=(246, 238, 220, 150))
ring(RR * 0.80, 3); ring(RR * 0.74, 2); ring(RR * 0.50, 2); ring(RR * 0.28, 2)
for k in range(72):                                 # degree ticks between the two outer rings
    a = math.radians(k * 5)
    r0 = RR * (0.74 if k % 2 else 0.70)
    d.line([P(RX + r0 * math.sin(a), RY - r0 * math.cos(a)), P(RX + RR * 0.80 * math.sin(a), RY - RR * 0.80 * math.cos(a))], fill=INK, width=2)
for a in np.arange(11.25, 360, 22.5):
    point(a, RR * 0.50, RR * 0.045, GOLD, LIGHT)
for a in np.arange(22.5, 360, 45):
    point(a, RR * 0.62, RR * 0.06, DARK, LIGHT)
for a in (45, 135, 225, 315):
    point(a, RR * 0.80, RR * 0.085, RED, LIGHT)
for a in (90, 180, 270):
    point(a, RR * 1.02, RR * 0.11, DARK, LIGHT)
point(0, RR * 1.18, RR * 0.11, DARK, LIGHT)
d.ellipse(((RX - 7) * S, (RY - 7) * S, (RX + 7) * S, (RY + 7) * S), fill=RED, outline=INK, width=2)
# North mark: a small fleur made of three petals and a bar, then the letter N from three strokes.
ny0 = RY - RR * 1.18
for dxp, tilt in ((0, 0), (-9, -0.5), (9, 0.5)):
    tipx = RX + dxp * 1.6 + tilt * 6; tipy = ny0 - 34 + abs(dxp) * 1.3
    d.polygon([P(RX + dxp * 0.3, ny0 - 6), P(tipx - 5, (ny0 - 6 + tipy) / 2), P(tipx, tipy), P(tipx + 5, (ny0 - 6 + tipy) / 2)],
              fill=DARK, outline=INK)
d.rectangle(((RX - 11) * S, (ny0 - 9) * S, (RX + 11) * S, (ny0 - 5) * S), fill=INK)
nx0, nyt = RX - 9, ny0 - 72
d.line([P(nx0, nyt + 26), P(nx0, nyt), P(nx0 + 18, nyt + 26), P(nx0 + 18, nyt)], fill=INK, width=5, joint='curve')

overlay = np.asarray(ov.resize((W, H), Image.LANCZOS), F32) / 255.0

# Rhumb lines: faint rays from the compass over the sea only (under the overlay).
rl = Image.new('L', (W * S, H * S), 0)
dl = ImageDraw.Draw(rl)
for k in range(32):
    a = math.radians(k * 11.25)
    dl.line([P(RX, RY), P(RX + 3000 * math.sin(a), RY - 3000 * math.cos(a))], fill=255 if k % 4 == 0 else 150, width=2)
rhumb = np.asarray(rl.resize((W, H), Image.LANCZOS), F32) / 255.0
rhumb *= (~land) * (d_sea > 6) * 0.20
img = img * (1 - rhumb[..., None]) + hexc('#6b4a2e') * rhumb[..., None]

# A faint grid over land and sea.
grid = np.zeros((H, W), F32)
for gx_ in np.arange(B1 + STEP, W - B1 - 1, STEP):
    grid = np.maximum(grid, 1 - smoothstep(0.3, 1.1, np.abs(xx - gx_)))
for gy_ in np.arange(B1 + STEPV, H - B1 - 1, STEPV):
    grid = np.maximum(grid, 1 - smoothstep(0.3, 1.1, np.abs(yy - gy_)))
img = img * (1 - 0.13 * grid[..., None]) + hexc('#3b3a48') * 0.13 * grid[..., None]

a = overlay[..., 3:4]
img = img * (1 - a) + overlay[..., :3] * a

# ----------------------------------------------------------------------------
# 5. Paper: warm tone, fibres, soft stains, darker edges
# ----------------------------------------------------------------------------
fib = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (0.7, 2.5)); fib /= fib.std()
grain = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), 0.8); grain /= grain.std()
stain = vnoise(260) + 0.5 * vnoise(90)
img = img * hexc('#fbf3df')                                  # everything sits on cream paper
img *= (1 + 0.016 * fib + 0.014 * grain + 0.035 * stain)[..., None]
edge = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))
img *= (0.86 + 0.14 * smoothstep(0, 120, edge + 25 * vnoise(40)))[..., None]
img = np.clip(img, 0, 1) ** 1.04
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))