ExperimentsFable 5.2 Python art (30 images)
Image 13 of 30
Voronoi stained glass
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""13 Voronoi stained glass.
A pointed-arch window in a dark stone wall. Every pane is a Voronoi cell: the
area closer to one "site" point than to any other. The sites are placed with a
plan (rings around a low sun, pairs along the hill lines and the river banks,
random points elsewhere), so the lead lines draw a sunrise landscape. Each pane
gets a jewel colour, streaky glass texture and back light; the bright panes
bloom over the lead and spill colour onto the stone.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/13-voronoi-stained-glass.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
from scipy.spatial import cKDTree
W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '13-voronoi-stained-glass.png')
F32 = np.float32
rng = np.random.default_rng(1313)
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 noise(sigma):
n = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), sigma)
return n / n.std()
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. Window shape: a pointed arch. din = distance inside the opening (pixels).
# ----------------------------------------------------------------------------
CX, HALF = 800.0, 610.0
YS, YB = 1040.0, 1905.0 # spring line of the arch, bottom edge
R = 0.80 * 2 * HALF # arch radius
def inside_dist(x, y):
lower = np.minimum(HALF - np.abs(x - CX), YB - y)
d1 = R - np.hypot(x - (CX - HALF + R), y - YS)
d2 = R - np.hypot(x - (CX + HALF - R), y - YS)
upper = np.minimum(np.minimum(d1, d2), YB - y)
return np.where(y > YS, lower, upper)
din = inside_dist(xx, yy)
BAND = 74.0 # width of the border of small panes
LEAD = 4.6 # half width of a lead line
# ----------------------------------------------------------------------------
# 2. The picture plan: sun, sky, three hills and a river
# ----------------------------------------------------------------------------
SUNX, SUNY = 800.0, 905.0
def ridge1(x): return 1150 + 42 * np.sin(x / 190 + 0.5) + 20 * np.sin(x / 75.0)
def ridge2(x): return 1345 + 66 * np.sin(x / 260 + 2.0) + 20 * np.sin(x / 90.0 + 1)
def ridge3(x): return 1590 + 60 * np.sin(x / 300 + 4.2) + 24 * np.sin(x / 110.0)
Y0R = float(ridge1(np.array(SUNX))) # the river starts under the sun
def river_x(y):
t = np.clip((y - Y0R) / (YB - Y0R), 0, 1)
return SUNX + 185 * np.sin(t * 5.6) * t ** 0.7 - 60 * t
def river_w(y):
t = np.clip((y - Y0R) / (YB - Y0R), 0, 1)
return 15 + 120 * t ** 1.5
def region(x, y):
"""0 sun, 1 sky, 2 far hill, 3 middle hill, 4 near hill, 5 river."""
x = np.asarray(x, F32); y = np.asarray(y, F32)
r = np.hypot(x - SUNX, y - SUNY)
reg = np.ones(x.shape, int)
reg[r < 118] = 0
reg[y > ridge1(x)] = 2
reg[y > ridge2(x)] = 3
reg[y > ridge3(x)] = 4
reg[(y > ridge1(x) - 4) & (np.abs(x - river_x(y)) < river_w(y))] = 5
return reg
# ----------------------------------------------------------------------------
# 3. Sites
# ----------------------------------------------------------------------------
sites = []
# 3a. Rings around the sun: these make the sunburst.
sites.append((SUNX, SUNY))
RINGS = [(236, 12, 0.0), (350, 24, 0.5), (468, 24, 0.5), (592, 48, 0.5), (722, 48, 0.5), (858, 48, 0.5)]
for r, n, off in RINGS:
for k in range(n):
a = (k + off) / n * 2 * math.pi
jit = 2.0 + 0.030 * (r - 230)
sites.append((SUNX + r * math.cos(a) + rng.normal(0, jit), SUNY + r * math.sin(a) + rng.normal(0, jit)))
# 3b. Pairs of sites on both sides of each plan line, so that a lead line follows it.
def pairs_along(px, py, spacing, off):
"""px, py: dense polyline. Returns pairs offset by +-off along the normal."""
seg = np.hypot(np.diff(px), np.diff(py))
s = np.concatenate([[0], np.cumsum(seg)])
out = []
for d in np.arange(spacing * 0.5, s[-1], spacing):
x = np.interp(d, s, px); y = np.interp(d, s, py)
x2 = np.interp(d + 2, s, px); y2 = np.interp(d + 2, s, py)
tx, ty = x2 - x, y2 - y
L = math.hypot(tx, ty) + 1e-9
nx, ny = -ty / L, tx / L
j = rng.normal(0, 2.0)
out.append((x + nx * off + j * tx / L, y + ny * off + j * ty / L))
out.append((x - nx * off + j * tx / L, y - ny * off + j * ty / L))
return out
xs = np.linspace(CX - HALF, CX + HALF, 800)
line_sites = []
for f, sp in ((ridge1, 66), (ridge2, 72), (ridge3, 78)):
for (x, y) in pairs_along(xs, f(xs), sp, 25):
# no ridge sites inside the river
if abs(x - river_x(np.array(y))) > river_w(np.array(y)) + 22 or y < Y0R - 30:
line_sites.append((x, y))
ys = np.linspace(Y0R + 6, YB, 800)
for sgn in (-1, 1):
bx = river_x(ys) + sgn * river_w(ys)
for (x, y) in pairs_along(bx, ys, 62, 15):
line_sites.append((x, y))
# Centre line of the river where it is wide enough.
for y in np.arange(Y0R + 230, YB, 58):
if river_w(np.array(y)) > 52:
line_sites.append((float(river_x(np.array(y))) + rng.normal(0, 3), y + rng.normal(0, 3)))
def add_if_free(cands, existing, dmin):
ex = list(existing)
for c in cands:
if all((c[0] - e[0]) ** 2 + (c[1] - e[1]) ** 2 > dmin * dmin for e in ex[-4000:]):
ex.append(c)
return ex
# Ring sites only above the far hill.
ring_ok = [s for s in sites if s[1] < ridge1(np.array(s[0])) - 34]
sites = add_if_free(line_sites, ring_ok, 26)
# 3c. Random fill (dart throwing with a minimum distance per region).
arr = np.array(sites)
cand_x = rng.uniform(CX - HALF - 30, CX + HALF + 30, 60000)
cand_y = rng.uniform(40, YB + 30, 60000)
reg_c = region(cand_x, cand_y)
r_c = np.hypot(cand_x - SUNX, cand_y - SUNY)
pts = list(map(tuple, arr))
P = np.array(pts)
for x, y, rg, rr in zip(cand_x, cand_y, reg_c, r_c):
if rg <= 1 and rr < 905:
continue # the sunburst is already planned
dmin = {1: 76, 2: 58, 3: 64, 4: 72, 5: 46, 0: 99}[int(rg)]
d2 = (P[:, 0] - x) ** 2 + (P[:, 1] - y) ** 2
if d2.min() > dmin * dmin:
P = np.vstack([P, (x, y)])
sites = P
print('interior sites:', len(sites))
# 3d. Border band: sites evenly along the middle of the band give neat tiles.
border = []
bx, by = [], []
# walk the centre line of the band: up the left side, over the arch, down the right, along the bottom
m = BAND / 2
for y in np.arange(YB - m, YS, -4): bx.append(CX - HALF + m); by.append(y)
c1 = (CX - HALF + R, YS)
a_top = math.acos((R - HALF) / R)
for a in np.linspace(math.pi, math.pi + a_top, 400):
bx.append(c1[0] + (R - m) * math.cos(a)); by.append(c1[1] + (R - m) * math.sin(a))
c2 = (CX + HALF - R, YS)
for a in np.linspace(2 * math.pi - a_top, 2 * math.pi, 400):
bx.append(c2[0] + (R - m) * math.cos(a)); by.append(c2[1] + (R - m) * math.sin(a))
for y in np.arange(YS, YB - m, 4): bx.append(CX + HALF - m); by.append(y)
for x in np.arange(CX + HALF - m, CX - HALF + m, -4): bx.append(x); by.append(YB - m)
bx = np.array(bx); by = np.array(by)
seg = np.hypot(np.diff(bx), np.diff(by)); s = np.concatenate([[0], np.cumsum(seg)])
# The walk starts at the bottom left corner and ends there. One site sits exactly
# on each bottom corner, and the others are spaced evenly between the corners.
s_c2 = s[-1] - (2 * HALF - 2 * m) # arc length at the bottom right corner
n_a = int(round(s_c2 / 77)); n_b = int(round((s[-1] - s_c2) / 77))
stops = np.concatenate([np.linspace(0, s_c2, n_a, endpoint=False), np.linspace(s_c2, s[-1], n_b, endpoint=False)])
for d in stops:
border.append((np.interp(d, s, bx), np.interp(d, s, by)))
border = np.array(border)
# ----------------------------------------------------------------------------
# 4. Voronoi: nearest and second nearest site for every pixel
# ----------------------------------------------------------------------------
pix = np.stack([xx.ravel(), yy.ravel()], -1)
def voronoi(S):
d, i = cKDTree(S).query(pix, k=2, workers=-1)
p1 = S[i[:, 0]]; p2 = S[i[:, 1]]
gap = np.hypot(p1[:, 0] - p2[:, 0], p1[:, 1] - p2[:, 1]) + 1e-6
edge = (d[:, 1] ** 2 - d[:, 0] ** 2) / (2 * gap) # exact distance to the cell wall
return i[:, 0].reshape(H, W), edge.reshape(H, W).astype(F32), d[:, 0].reshape(H, W).astype(F32)
cell_i, edge_i, cd_i = voronoi(sites)
cell_b, edge_b, cd_b = voronoi(border)
in_band = din < BAND
cell = np.where(in_band, cell_b + len(sites), cell_i)
edge = np.where(in_band, edge_b, edge_i)
cdist = np.where(in_band, cd_b, cd_i)
# Lead also runs along the band's inner edge and along the stone frame.
edge = np.minimum(edge, np.abs(din - BAND))
edge = np.minimum(edge, np.maximum(din, 0) * 0.8)
glass_mask = din > 0
print('voronoi done %.1fs' % (time.time() - T0))
# ----------------------------------------------------------------------------
# 5. A colour for every pane
# ----------------------------------------------------------------------------
NS, NBD = len(sites), len(border)
sx, sy = sites[:, 0], sites[:, 1]
reg = region(sx, sy)
rs = np.hypot(sx - SUNX, sy - SUNY)
ang = np.arctan2(sy - SUNY, sx - SUNX)
col = np.zeros((NS + NBD, 3), F32)
sky = ramp(rs, [(120, '#ffe680'), (236, '#ffc83c'), (350, '#ff8a1f'), (468, '#e63c3a'), (592, '#8c2a9c'),
(722, '#2c38b0'), (858, '#16307e'), (1000, '#10255e')])
ray = (np.floor((ang / (2 * math.pi) + 2) * 24 + 0.5).astype(int) % 2 == 0) # alternate rays
ray_gain = np.where(ray, 1.20, 0.76)
ray_gain = np.where(rs > 900, 1.0, ray_gain)
ray_gain = np.where(rs < 300, 1.0, ray_gain)
sky *= ray_gain[:, None]
# warm tint on the light rays
sky += np.where(ray & (rs < 900) & (rs > 300), 1.0, 0.0)[:, None] * np.array([0.07, 0.04, 0.0], F32)
HILL = {
2: ['#4c57c2', '#3e6cc0', '#5a46ae', '#2f7fb8', '#6a5cc8'],
3: ['#1f9d6c', '#2bb07a', '#168a66', '#3fb45a', '#11796e', '#8fbf3a'],
4: ['#0f6a4a', '#0c5a52', '#167a44', '#0a4a58', '#1e8a3e', '#0d5040'],
5: ['#8fe0ea', '#5cc6e0', '#b6eef0', '#49b2dc', '#7fd6f0'],
}
for i in range(NS):
rg = int(reg[i])
if rg == 0:
col[i] = hexc('#fff3c4')
elif rg == 1:
col[i] = sky[i]
else:
col[i] = hexc(HILL[rg][rng.integers(len(HILL[rg]))])
if rg == 5:
# the river carries the sun's gold near the horizon
t = np.clip((sy[i] - Y0R) / 420, 0, 1)
col[i] = col[i] * t + hexc('#ffe59a') * (1 - t)
else:
# hills are lighter where they face the sun
near = math.exp(-((sx[i] - SUNX) / 420) ** 2) * (1.0 if rg == 2 else 0.6)
col[i] = col[i] * (0.86 + 0.34 * near) + hexc('#ffb040') * 0.10 * near
col[:NS] *= rng.uniform(0.80, 1.13, (NS, 1)).astype(F32)
col[:NS] *= rng.uniform(0.95, 1.05, (NS, 3)).astype(F32)
# Border: ruby and cobalt alternate, every fourth pane is gold.
for k in range(NBD):
c = '#f0b028' if k % 4 == 1 else ('#b01030' if k % 2 == 0 else '#1b3fae')
col[NS + k] = hexc(c) * rng.uniform(0.82, 1.1)
# ----------------------------------------------------------------------------
# 6. Glass: back light, streaks, seeds (bubbles) and grime near the lead
# ----------------------------------------------------------------------------
NC = NS + NBD
streak_h = noise((2.0, 34)); streak_v = noise((34, 2.0)); cloud = noise(9); fine = noise(1.0)
d1 = ndi.rotate(noise((2.0, 34)), 35, reshape=False, mode='reflect', order=1)
d2 = ndi.rotate(noise((2.0, 34)), -40, reshape=False, mode='reflect', order=1)
kind = rng.integers(0, 5, NC)[cell]
tex = np.choose(kind, [streak_h, streak_v, cloud, d1, d2])
tex_amt = rng.uniform(0.04, 0.12, NC).astype(F32)[cell]
# each pane has its own soft brightness slope
gdir = rng.uniform(0, 2 * math.pi, NC)
gamt = rng.uniform(0.0, 0.16, NC)
allx = np.concatenate([sites[:, 0], border[:, 0]]); ally = np.concatenate([sites[:, 1], border[:, 1]])
slope = ((xx - allx[cell]) * np.cos(gdir)[cell] + (yy - ally[cell]) * np.sin(gdir)[cell]) / 60.0 * gamt[cell]
rsun = np.hypot(xx - SUNX, yy - SUNY)
light = 0.62 + 0.75 * np.exp(-(rsun / 330) ** 2) + 0.28 * np.exp(-(rsun / 800) ** 2)
light *= 1 + 0.10 * noise(120) # uneven daylight behind the window
glass = col[cell] * (light * (1 + tex * tex_amt + slope) * (1 + 0.035 * fine))[..., None]
seeds = (rng.random((H, W)) < 0.0007).astype(F32)
seeds = ndi.gaussian_filter(seeds, 1.1) * 9
glass *= (1 + 0.9 * seeds)[..., None]
grime = 0.62 + 0.38 * smoothstep(LEAD, LEAD + 16, edge) # darker next to the lead
glass *= grime[..., None]
# the sun pane itself glows from the middle
glass += (np.exp(-(rsun / 105) ** 2) * 0.55)[..., None] * hexc('#fff8dc')
# ----------------------------------------------------------------------------
# 7. Lead lines, stone wall, bloom
# ----------------------------------------------------------------------------
lead_a = 1 - smoothstep(LEAD - 0.8, LEAD + 0.8, edge) # 1 on the lead
prof = np.clip(1 - edge / LEAD, 0, 1) # rounded came profile
lead_col = (0.030 + 0.055 * prof ** 2 + 0.003 * fine)[..., None] * np.array([1.0, 1.02, 1.08], F32)
window = glass * (1 - lead_a[..., None]) + lead_col * lead_a[..., None]
# Stone: dark, rough blocks.
out = -din
stone_n = 0.5 * noise(2.2) + 0.35 * noise(9) + 0.3 * noise(45)
course = 118.0
row = np.floor(yy / course)
joint_y = np.abs((yy / course) % 1 - 0.5) * course
xoff = (row % 2) * 95.0
joint_x = np.abs(((xx + xoff) / 190.0) % 1 - 0.5) * 190.0
joint = np.minimum(course / 2 - joint_y, 95.0 - joint_x)
jmask = 1 - smoothstep(1.0, 4.5, joint)
block_tone = rng.uniform(0.85, 1.15, (40, 40)).astype(F32)[(row.astype(int)) % 40, (np.floor((xx + xoff) / 190.0).astype(int)) % 40]
stone = (0.070 + 0.016 * stone_n) * block_tone * (1 - 0.50 * jmask)
stone_rgb = stone[..., None] * np.array([1.0, 0.97, 0.94], F32)
# Coloured light that spills from the glass onto the stone reveal.
wl = np.where(glass_mask[..., None], window, 0).astype(F32)
spill = np.stack([ndi.gaussian_filter(wl[..., c], 34) for c in range(3)], -1)
spill2 = np.stack([ndi.gaussian_filter(wl[..., c], 110) for c in range(3)], -1)
reveal = np.exp(-np.clip(out, 0, None) / 30.0) # the bevelled stone edge
lit = (0.80 + 0.22 * stone_n) * block_tone * (1 - 0.40 * jmask) # stone texture shows in the light
stone_rgb = stone_rgb + (spill * 0.85 * reveal[..., None] + spill2 * 0.42) * lit[..., None]
# a thin dark shadow line right at the frame
stone_rgb *= (0.45 + 0.55 * smoothstep(0, 5, out))[..., None]
img = np.where(glass_mask[..., None], window, stone_rgb)
aa = smoothstep(-0.7, 0.7, din)[..., None]
img = window * aa + stone_rgb * (1 - aa)
# Bloom: bright panes glow over the lead (halation).
bright = np.clip(img - 0.55, 0, None)
bloom = sum(np.stack([ndi.gaussian_filter(bright[..., c], s) for c in range(3)], -1) * w
for s, w in ((5, 0.40), (18, 0.30), (60, 0.25)))
img = img + bloom
img = np.clip(img, 0, None)
img = 1 - np.exp(-img * 1.25) # filmic shoulder keeps the sun from clipping hard
img = np.clip(img, 0, 1) ** 0.90
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.005
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))

