ExperimentsFable 5.2 Python art (30 images)

Glass of water, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""22 Glass of water.

A tumbler of water on an oak table, ray-marched with real refraction.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The glass and the water are distance formulas. Camera rays bend at every
air / glass / water surface (Snell's law). The bright pattern on the table
(the caustic) and the soft shadow come from about 13 million light rays
that are sent from the lamp through the same glass and counted on the table,
once per colour with a slightly different bending strength.
Run: .venv/bin/python scripts/22-glass-of-water.py
"""
import os, time, math
import numpy as np
from PIL import Image
from scipy import ndimage as ndi

W, H = 1600, 2000
SS = 2                          # 2 x 2 rays per pixel
SEED = 22
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '22-glass-of-water.png')
F = np.float32
rng = np.random.default_rng(SEED)


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


def norm(v):
    return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-12)


def vnoise(shape, cell, r):
    h, w = shape
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    g = r.random((int(h / cy) + 4, int(w / cx) + 4)).astype(F)
    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]
    return z


def fbm(shape, cell, octaves, r):
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    out = np.zeros(shape, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (max(1.0, cy), max(1.0, cx)), r)
        tot += amp
        amp *= 0.5
        cy /= 2
        cx /= 2
    return out / tot


# ----------------------------------------------------------------------------
# Glass and water as distance formulas
# ----------------------------------------------------------------------------
GH = 1.5                        # glass height
LEVEL = 1.06                    # water level
WALL_T = 0.036
BASE_T = 0.13
BOUND_R, BOUND_Y = 0.60, 1.60
AIR, WATER, GLASS = 0, 1, 2


def sd2(p):
    """Signed distances to the glass body and to the water body."""
    x, y, z = p[:, 0], p[:, 1], p[:, 2]
    r = np.sqrt(x * x + z * z)
    R = 0.42 + 0.0533 * y
    do = np.maximum(np.maximum(r - R, y - GH), -y)
    # rounded rim and rounded heel
    rim = np.sqrt((r - (R - WALL_T / 2)) ** 2 + (y - (GH - WALL_T / 2)) ** 2) - WALL_T / 2
    do = np.where(y > GH - WALL_T / 2, np.maximum(rim, -(r - (R - WALL_T))), do)
    Rin = R - WALL_T
    di = np.maximum(r - Rin, BASE_T - y)
    dG = np.maximum(do, -di)
    surf = LEVEL + 0.03 * np.exp(-np.clip(Rin - r, 0, None) / 0.03)      # the water climbs the wall a little
    dW = np.maximum(np.maximum(r - Rin - 0.004, BASE_T - 0.004 - y), (y - surf) * 0.8)
    return dG, dW


def iface(p):
    dG, dW = sd2(p)
    dWm = np.maximum(dW, -dG)
    return np.minimum(np.abs(dG), np.abs(dWm)), dG, dW


def medium(p):
    dG, dW = sd2(p)
    return np.where(dG < 0, GLASS, np.where(dW < 0, WATER, AIR))


def bound_hit(ro, rd):
    """Entry distance of rays into the cylinder that encloses the glass (inf if they miss)."""
    a = rd[:, 0] ** 2 + rd[:, 2] ** 2 + 1e-12
    b = ro[:, 0] * rd[:, 0] + ro[:, 2] * rd[:, 2]
    c = ro[:, 0] ** 2 + ro[:, 2] ** 2 - BOUND_R ** 2
    disc = b * b - a * c
    ok = disc > 0
    sq = np.sqrt(np.where(ok, disc, 0))
    tA = (-b - sq) / a
    tB = (-b + sq) / a
    iy = 1.0 / np.where(np.abs(rd[:, 1]) < 1e-9, 1e-9, rd[:, 1])
    t1 = (0.0 - ro[:, 1]) * iy
    t2 = (BOUND_Y - ro[:, 1]) * iy
    tC = np.minimum(t1, t2)
    tD = np.maximum(t1, t2)
    te = np.maximum(np.maximum(tA, tC), 0)
    tx = np.minimum(tB, tD)
    return np.where(ok & (te < tx), te, np.inf)


def trace(ro, rd, ior, sigma, want_reflect=False, max_events=14):
    """Follow rays through glass and water until they leave.

    ior: (air, water, glass) refraction indices. sigma: (3 media, C) absorption.
    Returns exit position, exit direction, remaining light (N, C), and optionally the
    first mirror ray (position, direction, strength)."""
    N = len(ro)
    C = sigma.shape[1]
    ro = ro.copy(); rd = rd.copy()
    thr = np.ones((N, C), F)
    act = np.arange(N)
    refl = None
    ior = np.asarray(ior, F)
    for ev in range(max_events):
        if len(act) == 0:
            break
        o = ro[act]; d = rd[act]
        t = np.full(len(act), 0.003, F)
        sub = np.arange(len(act))
        for _ in range(70):
            p = o[sub] + d[sub] * t[sub, None]
            f = iface(p)[0]
            t[sub] += np.maximum(f, 1e-4) * 0.9
            rr = p[:, 0] ** 2 + p[:, 2] ** 2
            stop = (f < 3e-4) | (rr > 0.66 ** 2) | (p[:, 1] > 1.66) | (p[:, 1] < -0.004)
            sub = sub[~stop]
            if len(sub) == 0:
                break
        p = o + d * t[:, None]
        f, dG, dW = iface(p)
        hit = f < 3e-3
        m1 = medium(p - d * 0.003)
        m2 = medium(p + d * 0.003)
        thr[act] *= np.exp(-sigma[m1] * t[:, None])
        hit &= m1 != m2
        # rays that left the neighbourhood of the glass are finished
        ro[act] = p
        outside = ~hit & ((p[:, 0] ** 2 + p[:, 2] ** 2 > 0.64 ** 2) | (p[:, 1] > 1.64) | (p[:, 1] < -0.002))
        # surface normal from the formula that is closest
        e = 0.0015
        n = np.zeros_like(p)
        useG = np.abs(dG) <= np.abs(np.maximum(dW, -dG)) + 1e-5
        for ax in range(3):
            off = np.zeros(3, F); off[ax] = e
            gp, wp = sd2(p + off)
            gm, wm = sd2(p - off)
            n[:, ax] = np.where(useG, gp - gm, wp - wm)
        n = norm(n)
        cosi = -np.sum(n * d, 1)
        flip = cosi < 0
        n[flip] *= -1
        cosi = np.abs(cosi)
        n1 = ior[m1]; n2 = ior[m2]
        eta = n1 / n2
        k = 1 - eta * eta * (1 - cosi * cosi)
        tir = k < 0
        cost = np.sqrt(np.where(tir, 0, k))
        # Fresnel: the share of light that is mirrored at this surface
        rs = (n1 * cosi - n2 * cost) / (n1 * cosi + n2 * cost + 1e-9)
        rp = (n1 * cost - n2 * cosi) / (n1 * cost + n2 * cosi + 1e-9)
        fr = np.where(tir, 1.0, 0.5 * (rs * rs + rp * rp)).astype(F)
        dref = d + 2 * cosi[:, None] * n
        dtr = eta[:, None] * d + (eta * cosi - cost)[:, None] * n
        nd = np.where(tir[:, None], dref, dtr)
        nd = norm(nd)
        if ev == 0 and want_reflect:
            refl = (p.copy(), dref.copy(), np.where(hit, fr, 0).astype(F), act.copy())
        w = np.where(hit & ~tir, 1 - fr, 1.0)
        thr[act] *= w[:, None]
        rd[act] = np.where(hit[:, None], nd, d)
        act = act[~outside]
    if len(act):
        thr[act] *= 0.0                      # rays that never got out carry no light
    return (ro, rd, thr, refl) if want_reflect else (ro, rd, thr)


# ----------------------------------------------------------------------------
# Lamp, table, wall, room
# ----------------------------------------------------------------------------
LAMP = np.array([-3.3, 7.6, -5.4], F)
LAMP_R = 0.30
RX0, RZ0, RSIZE = -1.1, -1.0, 3.8          # table square where light rays are counted
CELLS = 1200
PH = 3                                      # light rays per cell side
WALL_Z = -3.4
IOR_RGB = [(1.0, 1.326, 1.482), (1.0, 1.333, 1.50), (1.0, 1.342, 1.522)]
SIG_CAM = np.array([[0, 0, 0], [0.16, 0.035, 0.02], [0.10, 0.03, 0.06]], F)


def photon_map():
    n = CELLS * PH
    E = np.zeros((3, CELLS, CELLS), F)
    blocked = np.zeros((CELLS, CELLS), F)
    rows_per = 240
    for ci in range(3):
        prng = np.random.default_rng(100)        # the same rays for every colour
        for r0 in range(0, n, rows_per):
            r1 = min(n, r0 + rows_per)
            iz, ix = np.mgrid[r0:r1, 0:n]
            tx = RX0 + (ix.ravel() + prng.random(ix.size)) / n * RSIZE
            tz = RZ0 + (iz.ravel() + prng.random(ix.size)) / n * RSIZE
            ang = prng.random(ix.size) * 2 * math.pi
            rad = np.sqrt(prng.random(ix.size)) * LAMP_R
            ro = np.empty((ix.size, 3), F)
            ro[:, 0] = LAMP[0] + rad * np.cos(ang)
            ro[:, 1] = LAMP[1]
            ro[:, 2] = LAMP[2] + rad * np.sin(ang)
            tgt = np.stack([tx, np.zeros_like(tx), tz], 1).astype(F)
            rd = norm(tgt - ro).astype(F)
            te = bound_hit(ro, rd)
            m = np.isfinite(te)
            if not m.any():
                continue
            cell = (iz.ravel()[m] // PH) * CELLS + (ix.ravel()[m] // PH)
            o = ro[m] + rd[m] * (te[m, None] - 0.004)
            sig = SIG_CAM[:, ci:ci + 1]
            po, pd, thr = trace(o, rd[m], IOR_RGB[ci], sig)
            # rays that only passed near the glass and never touched it stay "direct light"
            touched = (np.sum(pd * rd[m], 1) < 0.9999995) | (thr[:, 0] < 0.9999)
            if ci == 0:
                blocked += np.bincount(cell[touched], minlength=CELLS * CELLS).reshape(CELLS, CELLS)
            po = po[touched]; pd = pd[touched]; thr = thr[touched]
            down = (pd[:, 1] < -1e-4) | (po[:, 1] <= 0.001)
            tt = np.where(pd[:, 1] < -1e-4, -po[:, 1] / np.minimum(pd[:, 1], -1e-4), 0.0)
            lx = (po[:, 0] + pd[:, 0] * tt - RX0) / RSIZE * CELLS - 0.5
            lz = (po[:, 2] + pd[:, 2] * tt - RZ0) / RSIZE * CELLS - 0.5
            ok = down & (lx > 0) & (lz > 0) & (lx < CELLS - 1.001) & (lz < CELLS - 1.001)
            lx = lx[ok]; lz = lz[ok]; wgt = thr[ok, 0].astype(np.float64)
            x0 = lx.astype(int); z0 = lz.astype(int)
            fx = lx - x0; fz = lz - z0
            for dz, dx, ww in ((0, 0, (1 - fx) * (1 - fz)), (0, 1, fx * (1 - fz)), (1, 0, (1 - fx) * fz), (1, 1, fx * fz)):
                E[ci] += np.bincount((z0 + dz) * CELLS + x0 + dx, weights=wgt * ww, minlength=CELLS * CELLS).reshape(CELLS, CELLS)
        print('  light rays, colour %d done %.1fs' % (ci, time.time() - T0))
    exp = PH * PH
    direct = ndi.gaussian_filter(np.clip(1 - blocked / exp, 0, 1), 1.6)
    out = np.zeros((CELLS, CELLS, 3), F)
    for ci in range(3):
        c = E[ci] / exp
        wide = ndi.gaussian_filter(c, 5.0)
        fine = ndi.gaussian_filter(c, 1.1)
        k = smooth(0.25, 1.2, wide)
        out[..., ci] = direct + wide * (1 - k) + fine * k
    return out


def bilerp(tex, u, v):
    """tex[v, u] with linear interpolation; u, v in pixel units."""
    h, w = tex.shape[:2]
    u = np.clip(u, 0, w - 1.001); v = np.clip(v, 0, h - 1.001)
    u0 = u.astype(np.int32); v0 = v.astype(np.int32)
    fu = (u - u0).astype(F); fv = (v - v0).astype(F)
    if tex.ndim == 3:
        fu = fu[:, None]; fv = fv[:, None]
    a = tex[v0, u0] * (1 - fu) + tex[v0, u0 + 1] * fu
    b = tex[v0 + 1, u0] * (1 - fu) + tex[v0 + 1, u0 + 1] * fu
    return a * (1 - fv) + b * fv


TX0, TX1, TZ0, TZ1, TPPU = -9.0, 9.0, WALL_Z, 8.0, 150


def make_table_texture():
    r = np.random.default_rng(7)
    w = int((TX1 - TX0) * TPPU); h = int((TZ1 - TZ0) * TPPU)
    zz, xx = np.mgrid[0:h, 0:w].astype(F)
    X = TX0 + xx / TPPU
    Z = TZ0 + zz / TPPU
    plank_w = 0.86
    pid = np.floor((X + 0.31) / plank_w)
    pf = (X + 0.31) / plank_w - pid
    pr = np.random.default_rng(3).random(64).astype(F)
    tone = pr[(pid.astype(int) + 32) % 64]
    off = pr[(pid.astype(int) + 45) % 64] * 40
    warp = fbm((h, w), (900, 70), 3, r)
    fine = fbm((h, w), (320, 3), 4, r)
    rings = 0.5 + 0.5 * np.sin((pf * 16 + off + warp * 7 + 0.15 * np.sin(Z * 0.5 + off)) * 2.2)
    g = 0.30 * rings ** 3 + 0.70 * fine
    light = np.array([0.78, 0.60, 0.40], F)
    dark = np.array([0.50, 0.33, 0.18], F)
    tex = light[None, None, :] * (1 - g[..., None]) + dark[None, None, :] * g[..., None]
    tex *= (0.88 + 0.22 * tone)[..., None]
    pores = (vnoise((h, w), (30, 2), r) > 0.80) * fine
    tex *= (1 - 0.25 * pores)[..., None]
    seam = np.exp(-(np.minimum(pf, 1 - pf) * plank_w / 0.006) ** 2)
    tex *= (1 - 0.7 * seam)[..., None]
    return tex.astype(F)


LDIR = norm(LAMP - np.array([0.0, 0.75, 0.0], F))
LA = norm(np.cross(LDIR, np.array([0, 1, 0], F)))
LB = np.cross(LA, LDIR)
FDIR = norm(np.array([3.2, 2.2, 4.0], F))
FA = norm(np.cross(FDIR, np.array([0, 1, 0], F)))
FB = np.cross(FA, FDIR)
KEY_COL = np.array([1.0, 0.95, 0.86], F)


def room(rd):
    """What a ray sees when it leaves upward: a dark room, a bright window and a soft side light."""
    c = np.zeros((len(rd), 3), F)
    amb = 0.035 + 0.05 * np.clip(rd[:, 1], 0, 1)
    c += amb[:, None] * np.array([0.9, 0.95, 1.1], F)[None, :]
    cl = rd @ LDIR
    u = (rd @ LA) / np.maximum(cl, 1e-3)
    v = (rd @ LB) / np.maximum(cl, 1e-3)
    box = (cl > 0) * (1 - smooth(0.25, 0.29, np.abs(u))) * (1 - smooth(0.36, 0.40, np.abs(v)))
    bars = 1 - np.maximum(np.exp(-(u / 0.018) ** 2), np.exp(-((v - 0.05) / 0.018) ** 2))
    c += (box * bars * 13.0)[:, None] * KEY_COL[None, :]
    cf = rd @ FDIR
    u = (rd @ FA) / np.maximum(cf, 1e-3)
    v = (rd @ FB) / np.maximum(cf, 1e-3)
    box = (cf > 0) * (1 - smooth(0.07, 0.11, np.abs(u))) * (1 - smooth(0.5, 0.62, np.abs(v)))
    c += (box * 5.5)[:, None] * np.array([0.85, 0.92, 1.0], F)[None, :]
    return c


def shade(ro, rd, tex, emap, wall_noise):
    """Colour seen along rays that travel in free air: table, back wall or room."""
    N = len(ro)
    col = np.zeros((N, 3), F)
    below = ro[:, 1] <= 0.001
    tt = np.where(rd[:, 1] < -1e-6, -ro[:, 1] / np.minimum(rd[:, 1], -1e-6), 0.0)
    hx = ro[:, 0] + rd[:, 0] * tt
    hz = ro[:, 2] + rd[:, 2] * tt
    table = (below | (rd[:, 1] < -1e-6)) & (hz > WALL_Z)
    tw = (WALL_Z - ro[:, 2]) / np.minimum(rd[:, 2], -1e-6)
    wy = ro[:, 1] + rd[:, 1] * tw
    wx = ro[:, 0] + rd[:, 0] * tw
    wall = ~table & (rd[:, 2] < -1e-6) & (wy >= 0) & (wy < 9)
    other = ~table & ~wall
    if table.any():
        x = hx[table]; z = hz[table]
        alb = bilerp(tex, (x - TX0) * TPPU, (z - TZ0) * TPPU)
        eu = (x - RX0) / RSIZE * CELLS - 0.5
        ev = (z - RZ0) / RSIZE * CELLS - 0.5
        inside = (eu > 1) & (ev > 1) & (eu < CELLS - 2) & (ev < CELLS - 2)
        E = np.ones((len(x), 3), F)
        if inside.any():
            E[inside] = bilerp(emap, eu[inside], ev[inside])
        pool = 0.10 + 0.90 * np.exp(-((x - 0.7) ** 2 + (z - 0.9) ** 2) / 2.9 ** 2)
        rr = np.sqrt(x * x + z * z)
        contact = 1 - 0.55 * np.exp(-np.clip(rr - 0.40, 0, None) / 0.10)
        amb = np.array([0.55, 0.62, 0.74], F) * 0.13
        light = E * (pool * 1.2)[:, None] * KEY_COL[None, :] + (amb[None, :] * contact[:, None]) * (0.5 + 0.5 * pool[:, None])
        col[table] = alb * light
    if wall.any():
        x = wx[wall]; y = wy[wall]
        base = np.array([0.150, 0.235, 0.255], F)
        glow = 0.22 + 1.0 * np.exp(-(((x + 0.7) / 3.6) ** 2 + ((y - 1.7) / 2.3) ** 2))
        nz = bilerp(wall_noise, (x + 12) * 40, y * 40)
        low = 1 - 0.45 * np.exp(-y / 0.5)                      # the wall is darker where it meets the table
        col[wall] = base[None, :] * (glow * low * (0.9 + 0.2 * nz))[:, None] * 1.25
    if other.any():
        col[other] = room(rd[other])
    return col


def main():
    emap = photon_map()
    tex = make_table_texture()
    wall_noise = fbm((500, 1100), 60, 4, np.random.default_rng(11))
    print('maps ready %.1fs' % (time.time() - T0))

    cam = np.array([1.1, 2.2, 5.3], F)
    tgt = np.array([0.25, 0.52, 0.35], F)
    fw = norm(tgt - cam)
    rt = norm(np.cross(fw, np.array([0, 1, 0], F)))
    up = np.cross(rt, fw)
    tanh = 0.272
    Ws, Hs = W * SS, H * SS
    out = np.zeros((H, W, 3), F)
    strip = 200 * SS
    for y0 in range(0, Hs, strip):
        yy, xx = np.mgrid[y0:y0 + strip, 0:Ws].astype(F)
        u = (xx.ravel() + 0.5 - Ws / 2) / (Ws / 2) * tanh
        v = -(yy.ravel() + 0.5 - Hs / 2) / (Ws / 2) * tanh
        rd = norm(fw[None, :] + u[:, None] * rt[None, :] + v[:, None] * up[None, :]).astype(F)
        ro = np.broadcast_to(cam, rd.shape)
        te = bound_hit(ro, rd)
        m = np.isfinite(te)
        col = np.zeros((len(rd), 3), F)
        col[~m] = shade(ro[~m], rd[~m], tex, emap, wall_noise)
        if m.any():
            o = ro[m] + rd[m] * (te[m, None] - 0.004)
            po, pd, thr, refl = trace(o, rd[m], IOR_RGB[1], SIG_CAM, want_reflect=True)
            c = shade(po, pd, tex, emap, wall_noise) * thr
            rp, rdir, rf, _ = refl
            c += shade(rp + rdir * 0.01, rdir, tex, emap, wall_noise) * rf[:, None]
            col[m] = c
        col = col.reshape(strip, Ws, 3)
        out[y0 // SS:(y0 + strip) // SS] = col.reshape(strip // SS, SS, W, SS, 3).mean((1, 3))
        print('  rows %d / %d  %.1fs' % ((y0 + strip) // SS, H, time.time() - T0))

    # camera glow around the brightest points, then film-like tone curve
    hi = np.clip(out - 1.0, 0, 8)
    out = out + 0.10 * ndi.gaussian_filter(hi, (5, 5, 0)) + 0.06 * ndi.gaussian_filter(hi, (22, 22, 0))
    x = out * 0.95
    out = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)
    out = np.clip(out, 0, 1) ** (1 / 2.2)
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    vig = 1 - 0.28 * smooth(0.5, 1.2, np.hypot((xx - W * 0.5) / W, (yy - H * 0.52) / H) * 1.7)
    out = out * vig[..., None]
    out += (rng.random((H, W, 1)).astype(F) - 0.5) * 0.012
    Image.fromarray((np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()