#!/usr/bin/env python3
"""Pure-Python 1990s 35mm cel-and-gouache anime background still:
A quiet late-afternoon dining table by a tall sunlit wooden window at the exact
moment a meal has been paused—roughly a quarter to a third of simple food still
resting calmly on a stoneware plate, wooden chopsticks laid horizontally across
a clay rest, warm amber tea reflecting the window sky.

Zero image models, zero external textures, zero fonts.
Requires: numpy, opencv-python-headless (or opencv-python), pycairo, scipy, Pillow.

Usage:
    python3 paint_scene.py --out still.png --crops-dir crops/
"""

from __future__ import annotations

import argparse
import math
import time
from pathlib import Path
from typing import Sequence

import cairo
import cv2
import numpy as np
from PIL import Image
from scipy.ndimage import map_coordinates

# ---------------------------------------------------------------------------
# 1. Scene dimensions, camera constants, and unified 3D light vector
# ---------------------------------------------------------------------------

WIDTH = 2048
HEIGHT = 1152

# Right-handed metric world (+X right, +Y forward, +Z up; tabletop at Z = 0.0)
CAM_EYE = np.array([0.24, -0.32, 0.50], dtype=np.float64)
CAM_TARGET = np.array([0.04, 1.45, 0.14], dtype=np.float64)
CAM_UP = np.array([0.0, 0.0, 1.0], dtype=np.float64)
CAM_FOV_DEG = 50.0

# Single normalized 3D light travel vector streaming diagonally from upper-right
# veranda window across the timber tabletop, props, and left cream plaster wall.
_SUN_RAW = np.array([-0.56, -0.73, -0.39], dtype=np.float64)
SUN_DIR = _SUN_RAW / np.linalg.norm(_SUN_RAW)

# Architectural plane anchors (meters)
Y_BACK_WALL = 2.85
X_LEFT_WALL = -1.06
Z_FLOOR = -0.72

# Tall veranda window opening on the back wall (Y = Y_BACK_WALL)
WIN_X0 = -0.38
WIN_X1 = 2.05
WIN_Z0 = -0.04
WIN_Z1 = 1.52
WIN_V_MULLIONS = (0.16, 0.66, 1.16, 1.66)
WIN_H_MULLIONS = (0.26, 0.68, 1.18)
WIN_MULLION_W = 0.044
WIN_FRAME_W = 0.068

# Dining table geometry (Z = 0.0)
TABLE_X0 = -0.62
TABLE_X1 = 0.80
TABLE_Y0 = 0.08
TABLE_Y1 = 2.12
TABLE_THICK = 0.046

# Hero prop anchors on Z = 0.0
PLATE_CENTER = np.array([-0.055, 1.060, 0.0], dtype=np.float64)
PLATE_R_OUTER = 0.144
PLATE_R_WELL = 0.098
PLATE_H_RIM = 0.021
PLATE_H_WELL = 0.007

HASHIOKI_CENTER = np.array([-0.165, 0.808, 0.0], dtype=np.float64)
TEACUP_CENTER = np.array([0.270, 1.170, 0.0], dtype=np.float64)
TEAPOT_CENTER = np.array([0.445, 1.675, 0.0], dtype=np.float64)
NAPKIN_CENTER = np.array([-0.388, 1.210, 0.0], dtype=np.float64)


# ---------------------------------------------------------------------------
# 2. Color utilities & isotropic gouache brushwork engine
# ---------------------------------------------------------------------------

def hex_rgb(code: str) -> np.ndarray:
    code = code.lstrip("#")
    return np.array(
        [int(code[0:2], 16), int(code[2:4], 16), int(code[4:6], 16)],
        dtype=np.float32,
    ) / 255.0


def smoothstep(
    edge0: np.ndarray | float, edge1: np.ndarray | float, x: np.ndarray | float
) -> np.ndarray:
    e0 = np.asarray(edge0, dtype=np.float32)
    e1 = np.asarray(edge1, dtype=np.float32)
    xv = np.asarray(x, dtype=np.float32)
    denom = np.maximum(e1 - e0, 1e-8)
    t = np.clip((xv - e0) / denom, 0.0, 1.0)
    return (t * t * (3.0 - 2.0 * t)).astype(np.float32)


def fbm_gouache(
    h: int,
    w: int,
    octaves: Sequence[tuple[float, float, float]] = (
        (72.0, 68.0, 0.45),
        (26.0, 29.0, 0.32),
        (10.5, 9.5, 0.16),
        (4.5, 4.8, 0.07),
    ),
    seed: int = 101,
) -> np.ndarray:
    """Multi-octave bicubic-upsampled zero-mean unit-variance Gaussian mottling
    at balanced square scales (never stretched striping on painted fills)."""
    rng = np.random.default_rng(seed)
    acc = np.zeros((h, w), dtype=np.float32)
    w_sum = 0.0
    for sx, sy, weight in octaves:
        gh = max(4, int(round(h / float(sy))))
        gw = max(4, int(round(w / float(sx))))
        grid = rng.standard_normal((gh, gw)).astype(np.float32)
        up = cv2.resize(grid, (w, h), interpolation=cv2.INTER_CUBIC)
        acc += float(weight) * up
        w_sum += float(weight)
    acc /= max(w_sum, 1e-6)
    std = float(np.std(acc))
    if std > 1e-6:
        acc = (acc - float(np.mean(acc))) / std
    return acc.astype(np.float32)


def make_paper_tooth(h: int, w: int, seed: int = 707) -> np.ndarray:
    """Fine isotropic cold-press watercolor/gouache paperboard tooth."""
    fine = fbm_gouache(
        h, w, octaves=((3.6, 3.8, 0.55), (1.9, 2.0, 0.45)), seed=seed
    )
    med = fbm_gouache(h, w, octaves=((11.0, 10.5, 1.0),), seed=seed + 19)
    tooth = 0.72 * fine + 0.28 * med
    return np.clip(tooth, -2.5, 2.5).astype(np.float32)


def paint_isotropic_gouache_dabs(
    rgb: np.ndarray,
    mask: np.ndarray,
    paper_tooth: np.ndarray,
    dab_strength: float = 0.048,
    warm_bounce_in_shadow: float = 0.022,
    num_dabs: int = 94,
    tooth_weight: float = 0.016,
    seed: int = 123,
) -> np.ndarray:
    """Apply balanced square-scale gouache mottling, 85-100 randomly angled
    soft convex-polygon flat-brush dabs at 1/4 resolution, fine cold-press paper
    tooth, and warm bounce light inside deep shadows (lum < 0.28)."""
    h, w, _ = rgb.shape
    m = np.clip(mask.astype(np.float32), 0.0, 1.0)
    if float(np.max(m)) < 1e-4:
        return rgb.copy()

    mottle = fbm_gouache(
        h,
        w,
        octaves=((72.0, 68.0, 0.45), (26.0, 29.0, 0.32), (10.5, 9.5, 0.16), (4.5, 4.8, 0.07)),
        seed=seed,
    )

    sh, sw = max(64, h // 4), max(64, w // 4)
    rng = np.random.default_rng(seed + 41)
    dab_val = np.zeros((sh, sw), dtype=np.float32)
    dab_tmp = np.zeros((sh, sw), dtype=np.float32)

    for _ in range(num_dabs):
        ang = float(rng.uniform(0.0, math.pi))
        hx = float(rng.uniform(13.0, 40.0))
        hy = float(rng.uniform(5.0, 15.0))
        cx = float(rng.uniform(0.0, sw))
        cy = float(rng.uniform(0.0, sh))
        ca, sa = math.cos(ang), math.sin(ang)

        j0 = float(rng.uniform(0.86, 1.12))
        j1 = float(rng.uniform(0.86, 1.12))
        corners = np.array(
            [
                [cx - hx * ca + hy * j0 * sa, cy - hx * sa - hy * j0 * ca],
                [cx + hx * ca + hy * j1 * sa, cy + hx * sa - hy * j1 * ca],
                [cx + hx * ca - hy * j0 * sa, cy + hx * sa + hy * j0 * ca],
                [cx - hx * ca - hy * j1 * sa, cy - hx * sa + hy * j1 * ca],
            ],
            dtype=np.float32,
        )
        sig = float(rng.uniform(1.3, 2.8))
        pad = int(math.ceil(sig * 3.0)) + 2
        x0 = max(0, int(math.floor(np.min(corners[:, 0]))) - pad)
        y0 = max(0, int(math.floor(np.min(corners[:, 1]))) - pad)
        x1 = min(sw, int(math.ceil(np.max(corners[:, 0]))) + pad)
        y1 = min(sh, int(math.ceil(np.max(corners[:, 1]))) + pad)
        if x1 <= x0 or y1 <= y0:
            continue

        roi_pts = np.round(corners - np.array([[x0, y0]], dtype=np.float32)).astype(np.int32)
        dab = np.zeros((y1 - y0, x1 - x0), dtype=np.float32)
        cv2.fillConvexPoly(dab, roi_pts, 1.0, cv2.LINE_AA)
        a = cv2.GaussianBlur(dab, (0, 0), sig) * float(rng.uniform(0.18, 0.34))
        v_step = float(rng.normal(0.0, 0.42))
        t_step = float(rng.normal(0.0, 0.52))
        dab_val[y0:y1, x0:x1] = dab_val[y0:y1, x0:x1] * (1.0 - a) + v_step * a
        dab_tmp[y0:y1, x0:x1] = dab_tmp[y0:y1, x0:x1] * (1.0 - a) + t_step * a

    dv = cv2.resize(dab_val, (w, h), interpolation=cv2.INTER_LINEAR)
    dt = cv2.resize(dab_tmp, (w, h), interpolation=cv2.INTER_LINEAR)

    out = rgb.copy()
    delta = dab_strength * (0.52 * mottle + 0.48 * dv) + tooth_weight * paper_tooth
    wshift = (dab_strength * 0.36) * (0.48 * mottle + 0.52 * dt)
    out[:, :, 0] += m * (delta + wshift)
    out[:, :, 1] += m * (delta + 0.30 * wshift)
    out[:, :, 2] += m * (delta - wshift)

    lum = 0.2126 * out[:, :, 0] + 0.7152 * out[:, :, 1] + 0.0722 * out[:, :, 2]
    sh_w = np.clip((0.28 - lum) / 0.28, 0.0, 1.0) * m * np.clip(0.5 + 0.5 * dt, 0.0, 1.0)
    out[:, :, 0] += sh_w * warm_bounce_in_shadow * 1.15
    out[:, :, 1] += sh_w * warm_bounce_in_shadow * 0.72
    out[:, :, 2] += sh_w * warm_bounce_in_shadow * 0.32
    return np.clip(out, 0.0, 1.0)


def alpha_composite(dst_rgb: np.ndarray, src_rgb: np.ndarray, src_a: np.ndarray) -> np.ndarray:
    a = np.clip(src_a, 0.0, 1.0)[..., None]
    return dst_rgb * (1.0 - a) + src_rgb * a


def screen_blend(dst_rgb: np.ndarray, add_rgb: np.ndarray, strength: float = 1.0) -> np.ndarray:
    b = np.clip(add_rgb * strength, 0.0, 1.0)
    return 1.0 - (1.0 - dst_rgb) * (1.0 - b)


# ---------------------------------------------------------------------------
# 3. Metric 3D Pinhole Camera & Exact Plane-Basis UV Homography
# ---------------------------------------------------------------------------

class Camera3D:
    def __init__(
        self,
        eye: np.ndarray,
        target: np.ndarray,
        up: np.ndarray,
        fov_deg: float,
        width: int,
        height: int,
    ) -> None:
        self.eye = np.asarray(eye, dtype=np.float64)
        self.target = np.asarray(target, dtype=np.float64)
        self.up = np.asarray(up, dtype=np.float64)
        self.width = int(width)
        self.height = int(height)

        fwd = self.target - self.eye
        fwd /= np.linalg.norm(fwd)
        right = np.cross(fwd, self.up)
        right /= np.linalg.norm(right)
        down = np.cross(fwd, right)
        down /= np.linalg.norm(down)

        self.fwd = fwd
        self.right = right
        self.down = down
        self.R = np.vstack([right, down, fwd])

        self.f = (self.width * 0.5) / math.tan(math.radians(fov_deg) * 0.5)
        self.cx = self.width * 0.5
        self.cy = self.height * 0.5
        self.K = np.array(
            [[self.f, 0.0, self.cx], [0.0, self.f, self.cy], [0.0, 0.0, 1.0]],
            dtype=np.float64,
        )

        yy, xx = np.mgrid[0:self.height, 0:self.width].astype(np.float32)
        dx_cam = (xx - self.cx) / self.f
        dy_cam = (yy - self.cy) / self.f
        self.ray_len_scale = np.sqrt(dx_cam * dx_cam + dy_cam * dy_cam + 1.0).astype(np.float32)
        rt = self.R.T.astype(np.float32)
        self.ray_world_x = rt[0, 0] * dx_cam + rt[0, 1] * dy_cam + rt[0, 2]
        self.ray_world_y = rt[1, 0] * dx_cam + rt[1, 1] * dy_cam + rt[1, 2]
        self.ray_world_z = rt[2, 0] * dx_cam + rt[2, 1] * dy_cam + rt[2, 2]

        vp_y = self.project_direction(np.array([0.0, 1.0, 0.0]))
        self.horizon_y = float(vp_y[1])

    def project_points(self, pts_world: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        pts = np.asarray(pts_world, dtype=np.float64)
        single = pts.ndim == 1
        if single:
            pts = pts[None, :]
        rel = pts - self.eye[None, :]
        pc = rel @ self.R.T
        z_cam = pc[:, 2]
        safe_z = np.where(np.abs(z_cam) < 1e-6, 1e-6, z_cam)
        u = self.f * (pc[:, 0] / safe_z) + self.cx
        v = self.f * (pc[:, 1] / safe_z) + self.cy
        if single:
            return float(u[0]), float(v[0]), float(z_cam[0])
        return u, v, z_cam

    def project_direction(self, d_world: np.ndarray) -> tuple[float, float]:
        pc = self.R @ np.asarray(d_world, dtype=np.float64)
        return (
            float(self.f * (pc[0] / max(pc[2], 1e-6)) + self.cx),
            float(self.f * (pc[1] / max(pc[2], 1e-6)) + self.cy),
        )

    def clip_segment_near(
        self, p0: np.ndarray, p1: np.ndarray, z_min: float = 0.05
    ) -> tuple[np.ndarray, np.ndarray] | None:
        c0 = self.R @ (p0 - self.eye)
        c1 = self.R @ (p1 - self.eye)
        if c0[2] < z_min and c1[2] < z_min:
            return None
        q0, q1 = p0.copy(), p1.copy()
        if c0[2] < z_min:
            t = (z_min - c0[2]) / max(c1[2] - c0[2], 1e-9)
            q0 = p0 + t * (p1 - p0)
        elif c1[2] < z_min:
            t = (z_min - c1[2]) / max(c0[2] - c1[2], 1e-9)
            q1 = p1 + t * (p0 - p1)
        return q0, q1

    def plane_homography(
        self,
        p0: np.ndarray,
        e1: np.ndarray,
        e2: np.ndarray,
        span_u: float,
        span_v: float,
        uv_w: int,
        uv_h: int,
    ) -> np.ndarray:
        """Exact 3x3 UV-to-screen homography from 3D plane basis:
        K @ [R @ e1, R @ e2, R @ (p0 - eye)] @ H_uv_to_plane
        """
        e1_u = np.asarray(e1, dtype=np.float64)
        e2_u = np.asarray(e2, dtype=np.float64)
        e1_u /= np.linalg.norm(e1_u)
        e2_u /= np.linalg.norm(e2_u)
        basis = np.column_stack([self.R @ e1_u, self.R @ e2_u, self.R @ (p0 - self.eye)])
        h_uv = np.array(
            [[span_u / float(uv_w), 0.0, 0.0], [0.0, span_v / float(uv_h), 0.0], [0.0, 0.0, 1.0]],
            dtype=np.float64,
        )
        return self.K @ basis @ h_uv

    def ray_plane_hit(
        self, p0: np.ndarray, normal: np.ndarray
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        n = np.asarray(normal, dtype=np.float64)
        n /= np.linalg.norm(n)
        num = float(np.dot(p0 - self.eye, n))
        den = (
            self.ray_world_x * float(n[0])
            + self.ray_world_y * float(n[1])
            + self.ray_world_z * float(n[2])
        )
        safe_den = np.where(np.abs(den) < 1e-6, 1e-6, den)
        z_cam = (num / safe_den).astype(np.float32)
        dist = z_cam * self.ray_len_scale
        hx = float(self.eye[0]) + z_cam * self.ray_world_x
        hy = float(self.eye[1]) + z_cam * self.ray_world_y
        hz = float(self.eye[2]) + z_cam * self.ray_world_z
        return z_cam, dist, hx, hy, hz

    def warp_plane_panel(
        self,
        panel_rgb: np.ndarray,
        panel_alpha: np.ndarray,
        p0: np.ndarray,
        e1: np.ndarray,
        e2: np.ndarray,
        span_u: float,
        span_v: float,
        fog_color: np.ndarray,
        fog_start: float = 1.6,
        fog_density: float = 0.06,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Warp flat-painted RGBA panel with premultiplied alpha via exact 3x3
        plane-basis homography, near-plane mask z_cam > 0.05, and ray-distance fog."""
        uv_h, uv_w = panel_alpha.shape
        h_mat = self.plane_homography(p0, e1, e2, span_u, span_v, uv_w, uv_h)

        premul = np.empty((uv_h, uv_w, 4), dtype=np.float32)
        a_clamped = np.clip(panel_alpha.astype(np.float32), 0.0, 1.0)
        premul[:, :, :3] = panel_rgb.astype(np.float32) * a_clamped[:, :, None]
        premul[:, :, 3] = a_clamped

        warped = cv2.warpPerspective(
            premul,
            h_mat,
            (self.width, self.height),
            flags=cv2.INTER_LINEAR,
            borderMode=cv2.BORDER_CONSTANT,
            borderValue=(0.0, 0.0, 0.0, 0.0),
        )

        e1_u = np.asarray(e1, dtype=np.float64)
        e2_u = np.asarray(e2, dtype=np.float64)
        e1_u /= np.linalg.norm(e1_u)
        e2_u /= np.linalg.norm(e2_u)
        normal = np.cross(e1_u, e2_u)
        z_cam, dist, hx, hy, hz = self.ray_plane_hit(p0, normal)

        dx = hx - float(p0[0])
        dy = hy - float(p0[1])
        dz = hz - float(p0[2])
        u_m = dx * float(e1_u[0]) + dy * float(e1_u[1]) + dz * float(e1_u[2])
        v_m = dx * float(e2_u[0]) + dy * float(e2_u[1]) + dz * float(e2_u[2])
        valid = (
            (z_cam > 0.05)
            & (u_m >= -0.004)
            & (u_m <= span_u + 0.004)
            & (v_m >= -0.004)
            & (v_m <= span_v + 0.004)
        ).astype(np.float32)

        alpha = np.clip(warped[:, :, 3] * valid, 0.0, 1.0)
        safe_a = np.maximum(alpha, 1e-5)
        rgb = np.clip(warped[:, :, :3] / safe_a[:, :, None], 0.0, 1.0)

        fog_t = 1.0 - np.exp(-np.maximum(0.0, dist - float(fog_start)) * float(fog_density))
        fog_t = np.clip(fog_t, 0.0, 0.55)[:, :, None]
        rgb = rgb * (1.0 - fog_t) + fog_color[None, None, :] * fog_t
        return rgb, alpha, z_cam


# ---------------------------------------------------------------------------
# 4. Unified 3D Sunlight & Window Mullion Shadow Solver
# ---------------------------------------------------------------------------

def build_window_dapple_field(seed: int = 404) -> np.ndarray:
    """Smooth foliage canopy shadow transmission map anchored to the window plane,
    keeping the central light panes clean and warm while casting soft leafy shade
    along the upper-right and outer canopy edges."""
    h, w = 256, 384
    coarse = fbm_gouache(
        h, w, octaves=((56.0, 52.0, 0.55), (22.0, 20.0, 0.30), (9.5, 9.0, 0.15)), seed=seed
    )
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    yn = yy / float(h)
    xn = xx / float(w)
    # Overhanging courtyard branches primarily filter the top 38% of the window
    canopy_bias = (1.0 - smoothstep(0.06, 0.54, yn)) * (0.35 + 0.65 * smoothstep(0.18, 0.85, xn))
    leaf_occ = smoothstep(0.28, 0.92, coarse * 0.48 + canopy_bias * 1.05 - 0.18)
    return (1.0 - 0.34 * leaf_occ).astype(np.float32)


def trace_points_to_window_light(
    wx: np.ndarray,
    wy: np.ndarray,
    wz: np.ndarray,
    dapple_field: np.ndarray,
    penumbra_scale: float = 1.0,
) -> tuple[np.ndarray, np.ndarray]:
    """Trace arbitrary 3D world points backward along -SUN_DIR onto the back
    veranda window plane (Y = Y_BACK_WALL). Returns (sun_intensity, pane_open)."""
    t = (Y_BACK_WALL - wy) / (-float(SUN_DIR[1]))
    xh = wx - t * float(SUN_DIR[0])
    zh = wz - t * float(SUN_DIR[2])

    pen = np.clip((0.008 + 0.0095 * np.maximum(t, 0.0)) * penumbra_scale, 0.007, 0.044)

    in_x = smoothstep(WIN_X0 - pen, WIN_X0 + pen, xh) * (1.0 - smoothstep(WIN_X1 - pen, WIN_X1 + pen, xh))
    in_z = smoothstep(WIN_Z0 - pen, WIN_Z0 + pen, zh) * (1.0 - smoothstep(WIN_Z1 - pen, WIN_Z1 + pen, zh))
    pane = in_x * in_z

    half_m = WIN_MULLION_W * 0.5
    mullion_pass = np.ones_like(pane, dtype=np.float32)
    for mx in WIN_V_MULLIONS:
        mullion_pass *= smoothstep(half_m - pen * 0.55, half_m + pen * 0.95, np.abs(xh - mx))
    for mz in WIN_H_MULLIONS:
        mullion_pass *= smoothstep(half_m - pen * 0.55, half_m + pen * 0.95, np.abs(zh - mz))

    dh, dw = dapple_field.shape
    u_d = np.clip((xh - WIN_X0) / (WIN_X1 - WIN_X0), 0.0, 1.0) * (dw - 1)
    v_d = np.clip((WIN_Z1 - zh) / (WIN_Z1 - WIN_Z0), 0.0, 1.0) * (dh - 1)
    dapple = map_coordinates(dapple_field, [v_d, u_d], order=1, mode="nearest").astype(np.float32)

    valid = (t > 0.0).astype(np.float32)
    sun = np.clip(pane * mullion_pass * dapple * valid, 0.0, 1.0)
    return sun.astype(np.float32), np.clip(pane * mullion_pass * valid, 0.0, 1.0).astype(np.float32)


def shadow_xy_on_plane(pts_3d: np.ndarray, z_plane: float = 0.0) -> np.ndarray:
    """Cast 3D points along SUN_DIR onto horizontal plane Z = z_plane."""
    pts = np.asarray(pts_3d, dtype=np.float64)
    dz = np.maximum(pts[..., 2] - z_plane, 0.0)
    t = dz / (-float(SUN_DIR[2]))
    out = np.empty_like(pts)
    out[..., 0] = pts[..., 0] + t * float(SUN_DIR[0])
    out[..., 1] = pts[..., 1] + t * float(SUN_DIR[1])
    out[..., 2] = z_plane
    return out


# ---------------------------------------------------------------------------
# 5. 2x Supersampled PyCairo Ink & Organic Bezier Drawing Engine
# ---------------------------------------------------------------------------

def eval_catmull_rom(pts: np.ndarray, samples_per_seg: int = 10, closed: bool = False) -> np.ndarray:
    pts = np.asarray(pts, dtype=np.float64)
    n = len(pts)
    if n < 2:
        return pts
    if closed:
        ext = np.vstack([pts[-1:], pts, pts[:2]])
        segs = n
    else:
        ext = np.vstack([pts[:1] * 2 - pts[1:2], pts, pts[-1:] * 2 - pts[-2:-1]])
        segs = n - 1
    out = []
    ts = np.linspace(0.0, 1.0, samples_per_seg, endpoint=False)
    t2 = ts * ts
    t3 = t2 * ts
    for i in range(segs):
        p0, p1, p2, p3 = ext[i], ext[i + 1], ext[i + 2], ext[i + 3]
        c = 0.5 * (
            (2.0 * p1)[None, :]
            + (-p0 + p2)[None, :] * ts[:, None]
            + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3)[None, :] * t2[:, None]
            + (-p0 + 3.0 * p1 - 3.0 * p2 + p3)[None, :] * t3[:, None]
        )
        out.append(c)
    out.append(pts[:1] if closed else pts[-1:])
    return np.vstack(out)


class CairoLayer2x:
    """2x supersampled PyCairo drawing surface (4096 x 2304 -> Lanczos 2048 x 1152)."""

    def __init__(self, width: int = WIDTH, height: int = HEIGHT) -> None:
        self.width = width
        self.height = height
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width * 2, height * 2)
        self.ctx = cairo.Context(self.surface)
        self.ctx.scale(2.0, 2.0)
        self.ctx.set_antialias(cairo.ANTIALIAS_BEST)
        self.ctx.set_line_cap(cairo.LINE_CAP_ROUND)
        self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)

    def fill_poly(self, pts_2d: np.ndarray, rgba: tuple[float, float, float, float]) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source_rgba(*rgba)
        ctx.fill()

    def fill_poly_linear(
        self,
        pts_2d: np.ndarray,
        p_start: tuple[float, float],
        p_end: tuple[float, float],
        stops: Sequence[tuple[float, tuple[float, float, float, float]]],
    ) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        pat = cairo.LinearGradient(p_start[0], p_start[1], p_end[0], p_end[1])
        for offset, rgba in stops:
            pat.add_color_stop_rgba(offset, *rgba)
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source(pat)
        ctx.fill()

    def fill_poly_radial(
        self,
        pts_2d: np.ndarray,
        c0: tuple[float, float, float],
        c1: tuple[float, float, float],
        stops: Sequence[tuple[float, tuple[float, float, float, float]]],
    ) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        pat = cairo.RadialGradient(c0[0], c0[1], c0[2], c1[0], c1[1], c1[2])
        for offset, rgba in stops:
            pat.add_color_stop_rgba(offset, *rgba)
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source(pat)
        ctx.fill()

    def stroke_catmull_rom(
        self,
        pts_2d: np.ndarray,
        z_depths: np.ndarray | float,
        base_width: float,
        rgba: tuple[float, float, float, float],
        seed: int = 1,
        closed: bool = False,
        fade_dist: float = 2.4,
        taper_ends: float = 0.28,
        tremor: float = 0.28,
        samples_per_seg: int = 8,
    ) -> None:
        """Tapered Catmull-Rom cel-ink spline with subtle hand tremor and
        perspective width decay: clip(1 / (1 + z / (fade_dist * 0.45)), 0.25, 1.0)."""
        pts = np.asarray(pts_2d, dtype=np.float64)
        if len(pts) < 2:
            return
        curve = eval_catmull_rom(pts, samples_per_seg=samples_per_seg, closed=closed)
        n = len(curve)
        if np.ndim(z_depths) == 0:
            zs = np.full(n, float(z_depths), dtype=np.float64)
        else:
            z_arr = np.asarray(z_depths, dtype=np.float64)
            zs = np.interp(np.linspace(0.0, len(z_arr) - 1, n), np.arange(len(z_arr)), z_arr)

        d = np.gradient(curve, axis=0)
        dlen = np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-6)
        norm = np.column_stack([-d[:, 1] / dlen[:, 0], d[:, 0] / dlen[:, 0]])

        rng = np.random.default_rng(seed)
        s = np.linspace(0.0, 1.0, n)
        phase1, phase2 = rng.uniform(0.0, 2.0 * math.pi, size=2)
        wobble = tremor * (
            0.65 * np.sin(2.0 * math.pi * (3.0 * s) + phase1)
            + 0.35 * np.sin(2.0 * math.pi * (7.0 * s) + phase2)
        )
        if closed:
            wobble *= np.sin(math.pi * s)
        curve = curve + norm * wobble[:, None]

        persp = np.clip(1.0 / (1.0 + np.maximum(zs, 0.05) / (fade_dist * 0.45)), 0.25, 1.0)
        if closed:
            taper = 0.84 + 0.16 * np.sin(2.0 * math.pi * s + phase1)
        else:
            taper = (
                smoothstep(0.0, max(taper_ends, 0.05), s)
                * (1.0 - smoothstep(1.0 - max(taper_ends, 0.05), 1.0, s))
            )
            taper = 0.22 + 0.78 * taper
        widths = base_width * persp * taper

        ctx = self.ctx
        ctx.set_source_rgba(*rgba)
        half_w = widths * 0.5
        left_edge = curve + norm * half_w[:, None]
        right_edge = (curve - norm * half_w[:, None])[::-1]
        ribbon = np.vstack([left_edge, right_edge])
        ctx.new_path()
        ctx.move_to(float(ribbon[0, 0]), float(ribbon[0, 1]))
        for x, y in ribbon[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.fill()

    def finish(self) -> tuple[np.ndarray, np.ndarray]:
        """Downsample 2x surface with Lanczos filter and cleanly unpremultiply alpha."""
        buf = np.frombuffer(self.surface.get_data(), dtype=np.uint8).reshape(
            self.height * 2, self.width * 2, 4
        )
        rgba_2x = buf[:, :, [2, 1, 0, 3]]
        pil_img = Image.fromarray(rgba_2x, mode="RGBA")
        pil_1x = pil_img.resize((self.width, self.height), Image.Resampling.LANCZOS)
        arr = np.asarray(pil_1x, dtype=np.float32) / 255.0
        alpha = np.clip(arr[:, :, 3], 0.0, 1.0)
        safe_a = np.maximum(alpha, 1e-5)
        rgb = np.clip(arr[:, :, :3] / safe_a[:, :, None], 0.0, 1.0)
        return rgb, alpha


# ---------------------------------------------------------------------------
# 6. Smooth 3D Lathe Vessel Geometry Helpers (Zero Polygonal Facets!)
# ---------------------------------------------------------------------------

def project_3d_ring(
    cam: Camera3D,
    center: np.ndarray,
    rx: float,
    ry: float,
    z: float,
    n: int = 96,
    wobble_amp: float = 0.0,
    seed: int = 1,
) -> tuple[np.ndarray, np.ndarray]:
    th = np.linspace(0.0, 2.0 * math.pi, n, endpoint=False)
    wob = np.zeros_like(th)
    if wobble_amp > 0.0:
        rng = np.random.default_rng(seed)
        ph = rng.uniform(0.0, 2.0 * math.pi, size=3)
        wob = wobble_amp * (
            0.55 * np.sin(2.0 * th + ph[0])
            + 0.30 * np.sin(3.0 * th + ph[1])
            + 0.15 * np.sin(5.0 * th + ph[2])
        )
    pts = np.column_stack([
        center[0] + (rx + wob) * np.cos(th),
        center[1] + (ry + wob) * np.sin(th),
        np.full_like(th, z),
    ])
    u, v, zc = cam.project_points(pts)
    return np.column_stack([u, v]), zc


def extract_front_or_back_arc(ring_2d: np.ndarray, want_front: bool = True) -> np.ndarray:
    """Extract the clean viewer-facing front arc (lower in screen Y, curving
    downward U-shaped) or back arc (higher in screen Y) of a projected 3D ring."""
    idx_l = int(np.argmin(ring_2d[:, 0]))
    idx_r = int(np.argmax(ring_2d[:, 0]))
    n = len(ring_2d)
    rolled = np.roll(ring_2d, -idx_l, axis=0)
    span = (idx_r - idx_l) % n
    arc_a = rolled[: span + 1]
    arc_b = np.vstack([rolled[0:1], rolled[span:][::-1]])
    a_is_front = float(np.mean(arc_a[:, 1])) >= float(np.mean(arc_b[:, 1]))
    chosen = arc_a if (a_is_front == want_front) else arc_b
    # Always order from left to right in screen X
    if chosen[0, 0] > chosen[-1, 0]:
        chosen = chosen[::-1]
    return chosen


def build_smooth_lathe_silhouette(
    cam: Camera3D,
    center: np.ndarray,
    profile_rz: Sequence[tuple[float, float]],
    n_slices: int = 36,
    wobble_amp: float = 0.0,
    seed: int = 1,
) -> tuple[np.ndarray, list[np.ndarray]]:
    """Interpolate a vessel's (radius, height) profile smoothly across 36 slices
    and build a butter-smooth 2D silhouette contour (zero polygonal facets)."""
    prof = np.asarray(profile_rz, dtype=np.float64)
    dense = eval_catmull_rom(prof, samples_per_seg=max(6, n_slices // max(1, len(prof) - 1)), closed=False)

    left_edge = []
    right_edge = []
    rings = []
    for r_val, z_val in dense:
        ring, _ = project_3d_ring(cam, center, float(r_val), float(r_val), float(z_val), n=96, wobble_amp=wobble_amp, seed=seed)
        rings.append(ring)
        left_edge.append(ring[int(np.argmin(ring[:, 0]))])
        right_edge.append(ring[int(np.argmax(ring[:, 0]))])

    left_arr = np.array(left_edge)   # bottom -> top
    right_arr = np.array(right_edge)  # bottom -> top
    bot_front = extract_front_or_back_arc(rings[0], want_front=True)   # left -> right
    top_back = extract_front_or_back_arc(rings[-1], want_front=False)  # left -> right

    # Closed CW silhouette: left (top->bot) + bot_front (left->right) + right (bot->top) + top_back (right->left)
    contour = np.vstack([left_arr[::-1], bot_front[1:-1], right_arr, top_back[::-1][1:-1]])
    return contour, rings


# ---------------------------------------------------------------------------
# 7. Band 0: Golden-Hour Sky, Far Ridge, Continuous Garden Canopy & Veranda
# ---------------------------------------------------------------------------

def render_exterior_sky_and_trees(
    cam: Camera3D, paper_tooth: np.ndarray
) -> np.ndarray:
    """Paint the luminous golden-hour sky, distant misty wooded hillside and quiet
    rooftop, continuous lush mid-distance garden tree canopies, exterior wooden
    veranda overhang eave, and sinuous overhanging Japanese maple boughs."""
    yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
    yn = yy / float(HEIGHT)
    xn = xx / float(WIDTH)

    # 1. Luminous late-afternoon sky (muted pale celadon-cream zenith -> warm
    #    paper #FAF9F5 -> glowing golden-apricot horizon!)
    c_zenith = hex_rgb("#CFE0E6")
    c_mid = hex_rgb("#F7F2E4")
    c_horizon = hex_rgb("#F6D59E")
    c_sun_glow = hex_rgb("#FFF6DC")

    t_mid = smoothstep(0.0, 0.28, yn)
    t_low = smoothstep(0.10, 0.56, yn)
    sky = c_zenith[None, None, :] * (1.0 - t_mid[:, :, None]) + c_mid[None, None, :] * t_mid[:, :, None]
    sky = sky * (1.0 - t_low[:, :, None]) + c_horizon[None, None, :] * t_low[:, :, None]

    # Golden late-afternoon solar radiance streaming from upper-right sky
    sx, sy = WIDTH * 0.92, HEIGHT * 0.14
    r_sun = np.sqrt(((xx - sx) / (WIDTH * 0.52)) ** 2 + ((yy - sy) / (HEIGHT * 0.44)) ** 2)
    glow = np.exp(-(r_sun ** 2) * 1.9)
    sky = sky * (1.0 - 0.58 * glow[:, :, None]) + c_sun_glow[None, None, :] * (0.58 * glow[:, :, None])

    # Delicate hand-painted afternoon cirrus/cumulus wisps catching warm gold undersides
    cloud_n = fbm_gouache(
        HEIGHT, WIDTH,
        octaves=((128.0, 84.0, 0.52), (50.0, 38.0, 0.30), (20.0, 17.0, 0.18)),
        seed=301,
    )
    cloud_band = smoothstep(0.04, 0.18, yn) * (1.0 - smoothstep(0.26, 0.44, yn))
    cloud_m = smoothstep(0.18, 1.12, cloud_n + 0.30 * cloud_band) * cloud_band * 0.58
    c_cld_lit = hex_rgb("#FFFDF6")
    c_cld_sh = hex_rgb("#E8D6BE")
    c_t = smoothstep(0.08, 0.26, yn)
    cld_col = c_cld_sh[None, None, :] * (1.0 - c_t[:, :, None]) + c_cld_lit[None, None, :] * c_t[:, :, None]
    sky = alpha_composite(sky, cld_col, cloud_m)

    # 2. Far misty mountain/wooded ridge dissolved in warm atmospheric gold haze
    ridge_n = fbm_gouache(1, WIDTH, octaves=((150.0, 1.0, 0.65), (48.0, 1.0, 0.35)), seed=305)[0]
    ridge_y = HEIGHT * (0.365 + 0.024 * np.sin(xn[0] * 4.2 + 0.4) + 0.015 * ridge_n)
    far_mask = smoothstep(ridge_y[None, :] - 4.0, ridge_y[None, :] + 4.0, yy)
    c_far_top = hex_rgb("#B4C0B2")
    c_far_bot = hex_rgb("#8FA08D")
    t_h = smoothstep(0.34, 0.52, yn)
    far_rgb = c_far_top[None, None, :] * (1.0 - t_h[:, :, None]) + c_far_bot[None, None, :] * t_h[:, :, None]
    far_rgb = far_rgb * 0.68 + c_horizon[None, None, :] * 0.32
    sky = alpha_composite(sky, far_rgb, far_mask * 0.90)

    # 3. Continuous Lush Mid-Distance Garden Tree Canopy (solid painterly gouache
    #    crowns with sunlit golden tops & shaded sage bellies — zero sparse dots!)
    mid_canopy = CairoLayer2x()
    _draw_continuous_garden_canopy(mid_canopy, seed=317)
    mc_rgb, mc_a = mid_canopy.finish()
    mc_rgb = paint_isotropic_gouache_dabs(
        mc_rgb, mc_a, paper_tooth, dab_strength=0.044, warm_bounce_in_shadow=0.022, num_dabs=88, seed=321
    )
    # Soft atmospheric aerial haze blending mid garden trees into golden afternoon light
    mc_rgb = cv2.GaussianBlur(mc_rgb, (0, 0), 2.4)
    mc_a = cv2.GaussianBlur(mc_a, (0, 0), 2.2)
    mc_rgb = mc_rgb * 0.84 + c_horizon[None, None, :] * 0.16
    sky = alpha_composite(sky, mc_rgb, mc_a)

    # 4. Subtle Exterior Wooden Veranda Overhang Eave & Garden Rail (parallax outside glass!)
    veranda = CairoLayer2x()
    _draw_exterior_veranda_eave(veranda, cam)
    ve_rgb, ve_a = veranda.finish()
    sky = alpha_composite(sky, ve_rgb, ve_a)

    # 5. Near Overhanging Courtyard Tree Boughs & Sunlit Maple Leaves (per-instance Bezier!)
    near_foliage = CairoLayer2x()
    _draw_courtyard_tree_branches(near_foliage, seed=337)
    nf_rgb, nf_a = near_foliage.finish()
    nf_rgb = paint_isotropic_gouache_dabs(
        nf_rgb, nf_a, paper_tooth, dab_strength=0.042, warm_bounce_in_shadow=0.026, num_dabs=84, seed=349
    )
    sky = alpha_composite(sky, nf_rgb, nf_a)

    # Subtle paperboard gouache cohesion across sky
    sky = paint_isotropic_gouache_dabs(
        sky, np.ones((HEIGHT, WIDTH), dtype=np.float32), paper_tooth,
        dab_strength=0.018, warm_bounce_in_shadow=0.010, num_dabs=86, tooth_weight=0.012, seed=353,
    )
    return sky


def _draw_continuous_garden_canopy(layer: CairoLayer2x, seed: int = 317) -> None:
    """Paint lush, continuous overlapping mid-distance garden tree silhouettes with
    shaded deep-sage lower foliage, olive midtones, and glowing sunlit top crowns."""
    rng = np.random.default_rng(seed)

    # Three lush continuous garden tree crowns visible through the tall veranda window
    # (leaving a calm sunlit gap of open golden sky around x=0.52..0.68, y=0.06..0.28!)
    tree_mounds = [
        # (cx, cy_base, width, height, col_deep, col_mid, col_sun)
        (0.45, 0.56, 0.24, 0.25, "#4E664C", "#748C63", "#B9C17D"),
        (0.76, 0.56, 0.30, 0.31, "#455E44", "#6B845B", "#C0C67F"),
        (0.95, 0.54, 0.26, 0.34, "#3E563F", "#647E56", "#B6BE79"),
        (0.60, 0.57, 0.22, 0.17, "#566F54", "#7D9469", "#C5CA84"),
    ]

    # Subtle distant garden wooden fence / hedge band along bottom of exterior view
    hedge_pts = np.array([
        [WIDTH * 0.35, HEIGHT * 0.45],
        [WIDTH * 0.58, HEIGHT * 0.435],
        [WIDTH * 0.82, HEIGHT * 0.44],
        [WIDTH * 1.04, HEIGHT * 0.43],
        [WIDTH * 1.04, HEIGHT * 0.62],
        [WIDTH * 0.35, HEIGHT * 0.62],
    ])
    layer.fill_poly(hedge_pts, (0.31, 0.41, 0.30, 0.96))

    for t_idx, (cx_f, cy_f, w_f, h_f, hex_deep, hex_mid, hex_sun) in enumerate(tree_mounds):
        c_deep = hex_rgb(hex_deep)
        c_mid = hex_rgb(hex_mid)
        c_sun = hex_rgb(hex_sun)

        # Solid scalloped base silhouette of tree crown
        crown_pts = []
        n_arc = 36
        for k in range(n_arc):
            th = math.pi * (k / float(n_arc - 1))  # 0 (right) -> pi (left) over top dome
            lobe = 1.0 + 0.11 * math.sin(7.0 * th + t_idx * 1.3) + 0.06 * math.cos(13.0 * th + t_idx)
            px = (cx_f + 0.5 * w_f * math.cos(th) * lobe) * WIDTH
            py = (cy_f - h_f * (math.sin(th) ** 0.78) * lobe) * HEIGHT
            crown_pts.append([px, py])
        crown_pts.append([(cx_f - 0.55 * w_f) * WIDTH, HEIGHT * 0.60])
        crown_pts.append([(cx_f + 0.55 * w_f) * WIDTH, HEIGHT * 0.60])
        crown_arr = np.array(crown_pts)

        layer.fill_poly_linear(
            crown_arr,
            (cx_f * WIDTH, (cy_f - h_f) * HEIGHT),
            (cx_f * WIDTH - 40.0, cy_f * HEIGHT),
            [
                (0.00, (float(c_sun[0]), float(c_sun[1]), float(c_sun[2]), 0.96)),
                (0.36, (float(c_mid[0]), float(c_mid[1]), float(c_mid[2]), 0.98)),
                (0.82, (float(c_deep[0]), float(c_deep[1]), float(c_deep[2]), 0.98)),
                (1.00, (float(c_deep[0] * 0.85), float(c_deep[1] * 0.85), float(c_deep[2] * 0.88), 0.98)),
            ],
        )

        # Layered painterly foliage sub-masses (sunlit upper-right crown puffs + rich shade pockets)
        for pass_role, n_puffs, y_lo, y_hi, col_a, col_b, alpha_v in [
            ("shade", 24, 0.35, 0.88, c_deep * 0.88, c_deep, 0.68),
            ("mid", 32, 0.16, 0.68, c_mid * 0.92, c_mid * 1.08, 0.76),
            ("sun", 28, 0.04, 0.44, c_sun * 0.94, np.clip(c_sun * 1.12, 0.0, 1.0), 0.82),
        ]:
            for _ in range(n_puffs):
                u_x = float(rng.uniform(-0.46, 0.48))
                u_y = float(rng.uniform(y_lo, y_hi))
                # Shift sunlit highlights slightly toward upper-right sun direction
                if pass_role == "sun":
                    u_x += 0.08
                px = (cx_f + u_x * w_f) * WIDTH
                py = (cy_f - (1.0 - u_y) * h_f) * HEIGHT
                rx = float(rng.uniform(28.0, 62.0))
                ry = float(rng.uniform(18.0, 38.0))
                rot = float(rng.uniform(-0.45, 0.45))
                mix = float(rng.uniform(0.0, 1.0))
                col = col_a * (1.0 - mix) + col_b * mix
                pts = []
                for j in range(12):
                    a = 2.0 * math.pi * j / 12.0
                    rj = 1.0 + 0.14 * math.sin(3.0 * a + mix * 6.0)
                    lx = rx * rj * math.cos(a)
                    ly = ry * rj * math.sin(a)
                    pts.append([px + lx * math.cos(rot) - ly * math.sin(rot), py + lx * math.sin(rot) + ly * math.cos(rot)])
                layer.fill_poly(np.array(pts), (float(col[0]), float(col[1]), float(col[2]), alpha_v))


def _draw_exterior_veranda_eave(layer: CairoLayer2x, cam: Camera3D) -> None:
    """Draw a subtle exterior wooden veranda overhang beam & wooden railing outside
    the glass (Y = 3.55 m) to anchor architectural parallax beyond the window."""
    y_ver = 3.55
    # Wooden garden balustrade handrail visible low through the bottom panes (Z = 0.09..0.14)
    rail_3d = np.array([
        [WIN_X0 - 0.1, y_ver, 0.125],
        [WIN_X1 + 0.1, y_ver, 0.125],
        [WIN_X1 + 0.1, y_ver, 0.085],
        [WIN_X0 - 0.1, y_ver, 0.085],
    ])
    ru, rv, rz = cam.project_points(rail_3d)
    layer.fill_poly_linear(
        np.column_stack([ru, rv]),
        (float(ru[0]), float(rv[0])), (float(ru[0]), float(rv[3])),
        [(0.0, (0.58, 0.45, 0.34, 0.78)), (1.0, (0.34, 0.26, 0.20, 0.82))],
    )
    # Subtle slender vertical veranda balusters extending cleanly behind window sill
    for bx in np.linspace(-0.22, 1.82, 14):
        post_3d = np.array([
            [bx - 0.011, y_ver, 0.088],
            [bx + 0.011, y_ver, 0.088],
            [bx + 0.011, y_ver, -0.48],
            [bx - 0.011, y_ver, -0.48],
        ])
        pu, pv, _ = cam.project_points(post_3d)
        layer.fill_poly(np.column_stack([pu, pv]), (0.36, 0.28, 0.22, 0.76))


def _draw_courtyard_tree_branches(layer: CairoLayer2x, seed: int = 337) -> None:
    """Sinuous overhanging Japanese maple / courtyard boughs outside the window,
    with smooth organic cubic Bezier tapering and lush multi-toned translucent
    sunlit olive, chartreuse-gold, and russet-amber leaf sprays."""
    rng = np.random.default_rng(seed)
    ctx = layer.ctx

    branches = [
        # Main sweeping upper-right bough curving softly across the upper window
        ((1.03, 0.05), (0.89, 0.08), (0.76, 0.15), (0.62, 0.13), 13.5),
        ((0.86, 0.09), (0.79, 0.18), (0.71, 0.23), (0.61, 0.24), 7.8),
        ((1.03, 0.18), (0.93, 0.22), (0.85, 0.28), (0.76, 0.27), 8.5),
        ((0.36, 0.02), (0.44, 0.09), (0.51, 0.12), (0.58, 0.10), 8.2),
    ]

    bark_sh = hex_rgb("#352B23")
    bark_lit = hex_rgb("#6F5640")

    leaf_palettes = [
        (hex_rgb("#3A5534"), hex_rgb("#6D894A"), hex_rgb("#C4CB73")),  # lush sunlit olive-sage
        (hex_rgb("#486239"), hex_rgb("#8AA153"), hex_rgb("#E1D07B")),  # golden backlit foliage
        (hex_rgb("#73452E"), hex_rgb("#B5653F"), hex_rgb("#E39F62")),  # late-autumn clay-amber accent
    ]

    for b_idx, (p0, p1, p2, p3, bw) in enumerate(branches):
        q0 = np.array([p0[0] * WIDTH, p0[1] * HEIGHT])
        q1 = np.array([p1[0] * WIDTH, p1[1] * HEIGHT])
        q2 = np.array([p2[0] * WIDTH, p2[1] * HEIGHT])
        q3 = np.array([p3[0] * WIDTH, p3[1] * HEIGHT])

        ts = np.linspace(0.0, 1.0, 28)
        omt = 1.0 - ts
        pts = (
            (omt ** 3)[:, None] * q0
            + (3 * omt ** 2 * ts)[:, None] * q1
            + (3 * omt * ts ** 2)[:, None] * q2
            + (ts ** 3)[:, None] * q3
        )
        # Organic tapering branch widths (thick at base -> delicate at tip)
        layer.stroke_catmull_rom(
            pts, z_depths=3.8, base_width=bw,
            rgba=(float(bark_sh[0]), float(bark_sh[1]), float(bark_sh[2]), 0.90),
            seed=seed + b_idx * 17, taper_ends=0.48, tremor=0.75,
        )
        layer.stroke_catmull_rom(
            pts + np.array([0.0, -bw * 0.24]), z_depths=3.8, base_width=bw * 0.38,
            rgba=(float(bark_lit[0]), float(bark_lit[1]), float(bark_lit[2]), 0.56),
            seed=seed + b_idx * 17 + 3, taper_ends=0.48, tremor=0.50,
        )

        # Spawn curved drooping organic sub-twigs & dense overlapping leaf sprays
        num_twigs = 13 if bw >= 8.0 else 8
        for k in range(num_twigs):
            u = float(np.clip((k + 0.5) / float(num_twigs) + rng.uniform(-0.04, 0.04), 0.08, 0.97))
            idx = min(len(pts) - 2, int(u * (len(pts) - 1)))
            base = pts[idx]
            tang = pts[idx + 1] - pts[idx]
            base_ang = math.atan2(tang[1], tang[0])
            side = -1.0 if (k % 2 == 0) else 1.0
            twig_ang = base_ang + side * float(rng.uniform(0.35, 0.92)) + float(rng.uniform(-0.14, 0.18))
            twig_len = float(rng.uniform(34.0, 74.0)) * (1.05 - 0.38 * u)
            droop = float(rng.uniform(14.0, 32.0))

            t_p0 = base
            t_p1 = base + np.array([math.cos(twig_ang) * twig_len * 0.40, math.sin(twig_ang) * twig_len * 0.40 + droop * 0.22])
            t_p2 = base + np.array([math.cos(twig_ang) * twig_len * 0.78, math.sin(twig_ang) * twig_len * 0.78 + droop * 0.80])
            t_p3 = base + np.array([math.cos(twig_ang) * twig_len, math.sin(twig_ang) * twig_len + droop])

            ctx.new_path()
            ctx.move_to(float(t_p0[0]), float(t_p0[1]))
            ctx.curve_to(float(t_p1[0]), float(t_p1[1]), float(t_p2[0]), float(t_p2[1]), float(t_p3[0]), float(t_p3[1]))
            ctx.set_source_rgba(float(bark_sh[0]), float(bark_sh[1]), float(bark_sh[2]), 0.65)
            ctx.set_line_width(max(1.3, bw * 0.20 * (1.0 - 0.45 * u)))
            ctx.stroke()

            # Weighted palette choice (mostly sunlit olive/gold, ~18% subtle clay-amber autumn leaves)
            p_roll = float(rng.uniform(0.0, 1.0))
            pal = leaf_palettes[2] if p_roll > 0.82 else (leaf_palettes[1] if p_roll > 0.40 else leaf_palettes[0])
            n_leaves = int(rng.integers(10, 17))
            for _ in range(n_leaves):
                lt = float(rng.uniform(0.10, 1.04))
                om = 1.0 - lt
                lp = (om ** 3) * t_p0 + 3 * (om ** 2) * lt * t_p1 + 3 * om * (lt ** 2) * t_p2 + (lt ** 3) * t_p3
                lp = lp + rng.normal(0.0, 6.5, size=2)
                l_ang = twig_ang + float(rng.uniform(-1.35, 1.35))
                l_len = float(rng.uniform(20.0, 46.0))
                l_wid = l_len * float(rng.uniform(0.32, 0.50))
                l_curv = float(rng.uniform(-0.25, 0.25))

                lit = float(np.clip(0.30 + 0.62 * (1.0 - lp[1] / (HEIGHT * 0.52)) + rng.normal(0.0, 0.22), 0.0, 1.0))
                col = pal[0] * (1.0 - lit * 2.0) + pal[1] * (lit * 2.0) if lit < 0.5 else pal[1] * (1.0 - (lit - 0.5) * 2.0) + pal[2] * ((lit - 0.5) * 2.0)

                ca, sa = math.cos(l_ang), math.sin(l_ang)
                tip = lp + np.array([ca * l_len, sa * l_len])
                nrm = np.array([-sa, ca])
                c1a = lp + np.array([ca * l_len * 0.34, sa * l_len * 0.34]) + nrm * (l_wid * (0.95 + l_curv))
                c2a = lp + np.array([ca * l_len * 0.72, sa * l_len * 0.72]) + nrm * (l_wid * 0.52)
                c1b = lp + np.array([ca * l_len * 0.72, sa * l_len * 0.72]) - nrm * (l_wid * 0.50)
                c2b = lp + np.array([ca * l_len * 0.34, sa * l_len * 0.34]) - nrm * (l_wid * (0.90 - l_curv))

                ctx.new_path()
                ctx.move_to(float(lp[0]), float(lp[1]))
                ctx.curve_to(float(c1a[0]), float(c1a[1]), float(c2a[0]), float(c2a[1]), float(tip[0]), float(tip[1]))
                ctx.curve_to(float(c1b[0]), float(c1b[1]), float(c2b[0]), float(c2b[1]), float(lp[0]), float(lp[1]))
                ctx.close_path()
                ctx.set_source_rgba(float(col[0]), float(col[1]), float(col[2]), float(rng.uniform(0.76, 0.94)))
                ctx.fill()

                if lit > 0.60 and l_len > 28.0:
                    ctx.new_path()
                    ctx.move_to(float(lp[0]), float(lp[1]))
                    ctx.line_to(float(tip[0]), float(tip[1]))
                    ctx.set_source_rgba(0.99, 0.95, 0.78, 0.28)
                    ctx.set_line_width(0.85)
                    ctx.stroke()


# ---------------------------------------------------------------------------
# 8. Band 1: Architectural Room Shell (Flat UV -> Exact 3x3 Plane Homography)
# ---------------------------------------------------------------------------

def paint_left_plaster_wall_uv(dapple_field: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Calm warm lime-plaster left interior wall with exact 3D ray-traced golden
    window-mullion light patch, cedar picture rail (nageshi), and wood wainscot."""
    uv_w, uv_h = 1200, 900
    y0, y1 = 0.0, Y_BACK_WALL
    z_top, z_bot = 1.55, Z_FLOOR

    vv, uu = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    wy = y0 + (uu / float(uv_w)) * (y1 - y0)
    wz = z_top - (vv / float(uv_h)) * (z_top - z_bot)
    wx = np.full_like(wy, X_LEFT_WALL)

    plaster_n = fbm_gouache(
        uv_h, uv_w,
        octaves=((70.0, 68.0, 0.45), (26.0, 27.0, 0.32), (10.0, 10.5, 0.16), (4.5, 4.6, 0.07)),
        seed=411,
    )

    # Warm calm parchment plaster in shade vs luminous warm-paper golden sunlight patch!
    c_shade_top = hex_rgb("#ABA092")
    c_shade_bot = hex_rgb("#918577")
    c_sun_wall = hex_rgb("#F8E9CE")

    t_vert = smoothstep(0.0, 1.0, vv / float(uv_h))
    base = c_shade_top[None, None, :] * (1.0 - t_vert[:, :, None]) + c_shade_bot[None, None, :] * t_vert[:, :, None]

    # Gentle warm sky bounce near the back corner
    near_win = smoothstep(0.30, Y_BACK_WALL, wy)
    base = base + near_win[:, :, None] * np.array([0.055, 0.044, 0.028], dtype=np.float32)

    # Exact 3D ray-traced sunlight from back window onto left plaster wall!
    sun_wall, _ = trace_points_to_window_light(wx, wy, wz, dapple_field, penumbra_scale=1.25)
    rgb = base * (1.0 - 0.86 * sun_wall[:, :, None]) + c_sun_wall[None, None, :] * (0.86 * sun_wall[:, :, None])
    rgb = np.clip(rgb + plaster_n[:, :, None] * 0.011, 0.0, 1.0)

    # Subtle cedar horizontal architectural picture beam (nageshi) at Z = 0.84..0.90
    wood_sh = hex_rgb("#4A3528")
    wood_lt = hex_rgb("#8B6345")
    nageshi_m = smoothstep(0.835, 0.845, wz) * (1.0 - smoothstep(0.895, 0.905, wz))
    nag_col = wood_sh[None, None, :] * (1.0 - 0.65 * sun_wall[:, :, None]) + wood_lt[None, None, :] * (0.65 * sun_wall[:, :, None])
    rgb = alpha_composite(rgb, nag_col, nageshi_m)
    nag_ao = smoothstep(0.81, 0.838, wz) * (1.0 - smoothstep(0.838, 0.846, wz)) * 0.24
    rgb *= (1.0 - nag_ao[:, :, None])

    # Lower warm cedar chair rail at Z = -0.04..-0.10 & wainscot paneling below
    rail_m = smoothstep(-0.108, -0.095, wz) * (1.0 - smoothstep(-0.045, -0.032, wz))
    rail_col = wood_sh[None, None, :] * (1.0 - 0.65 * sun_wall[:, :, None]) + wood_lt[None, None, :] * (0.65 * sun_wall[:, :, None])
    rgb = alpha_composite(rgb, rail_col, rail_m)

    wain_m = 1.0 - smoothstep(-0.116, -0.102, wz)
    wain_rgb = hex_rgb("#3F2D22")[None, None, :] * (1.0 - 0.55 * sun_wall[:, :, None]) + hex_rgb("#78563C")[None, None, :] * (0.55 * sun_wall[:, :, None])
    rgb = alpha_composite(rgb, wain_rgb, wain_m)

    # Soft room corner ambient occlusion (Y -> Y_BACK_WALL)
    corner_ao = smoothstep(Y_BACK_WALL - 0.24, Y_BACK_WALL, wy) * 0.18
    rgb *= (1.0 - corner_ao[:, :, None])

    return np.clip(rgb, 0.0, 1.0), np.ones((uv_h, uv_w), dtype=np.float32)


def paint_back_wall_and_window_uv() -> tuple[np.ndarray, np.ndarray]:
    """Paint the back wall (quiet shaded plaster left section + tall mullioned
    cedar veranda window with translucent glass glare and sunlit inner bevels)."""
    uv_w, uv_h = 2000, 1250
    x0, x1 = X_LEFT_WALL, 2.10
    z_top, z_bot = 1.55, Z_FLOOR

    vv, uu = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    wx = x0 + (uu / float(uv_w)) * (x1 - x0)
    wz = z_top - (vv / float(uv_h)) * (z_top - z_bot)

    plaster_n = fbm_gouache(
        uv_h, uv_w,
        octaves=((68.0, 64.0, 0.45), (24.0, 26.0, 0.32), (10.0, 9.5, 0.16), (4.5, 4.5, 0.07)),
        seed=431,
    )
    wood_n = fbm_gouache(
        uv_h, uv_w,
        octaves=((40.0, 38.0, 0.50), (14.0, 15.0, 0.32), (5.5, 5.5, 0.18)),
        seed=439,
    )

    # Back plaster wall (facing away from sun -> rich serene cool-warm shade)
    c_wall_top = hex_rgb("#9B9183")
    c_wall_bot = hex_rgb("#7F7568")
    t_v = smoothstep(0.0, 1.0, vv / float(uv_h))
    rgb = c_wall_top[None, None, :] * (1.0 - t_v[:, :, None]) + c_wall_bot[None, None, :] * t_v[:, :, None]
    rgb = np.clip(rgb + plaster_n[:, :, None] * 0.011, 0.0, 1.0)
    alpha = np.ones((uv_h, uv_w), dtype=np.float32)

    c_wood_dark = hex_rgb("#2E2119")
    c_wood_mid = hex_rgb("#483326")
    c_wood_bevel = hex_rgb("#986D4B")
    c_wood_sill = hex_rgb("#8B6447")

    # Matching cedar horizontal beam (nageshi) across back plaster left of window
    nag_m = smoothstep(0.835, 0.845, wz) * (1.0 - smoothstep(0.895, 0.905, wz)) * (1.0 - smoothstep(WIN_X0 - 0.04, WIN_X0, wx))
    rgb = alpha_composite(rgb, c_wood_mid[None, None, :] + wood_n[:, :, None] * 0.016, nag_m)

    # Left vertical cedar corner post (hashira)
    post_m = 1.0 - smoothstep(X_LEFT_WALL + 0.082, X_LEFT_WALL + 0.092, wx)
    rgb = alpha_composite(rgb, np.clip(c_wood_dark[None, None, :] + wood_n[:, :, None] * 0.016, 0.0, 1.0), post_m)

    # Deep shaded cedar wainscot below window sill (gives clean separation behind table!)
    below_sill = 1.0 - smoothstep(WIN_Z0 - 0.062, WIN_Z0 - 0.046, wz)
    wain_col = hex_rgb("#35261D")[None, None, :] + wood_n[:, :, None] * 0.015
    rgb = alpha_composite(rgb, np.clip(wain_col, 0.0, 1.0), below_sill)

    # Carve out tall window aperture
    in_win = ((wx > WIN_X0) & (wx < WIN_X1) & (wz > WIN_Z0) & (wz < WIN_Z1)).astype(np.float32)

    # Subtle diagonal vintage window glass reflection sheen
    glare = np.exp(-(((wx - 0.34 * wz - 0.22) / 0.22) ** 2)) * 0.068
    glare += np.exp(-(((wx - 0.34 * wz - 1.05) / 0.18) ** 2)) * 0.052
    glass_tint = hex_rgb("#FFF6E4")
    glass_alpha = np.clip(0.032 + glare, 0.0, 0.14)

    rgb = np.where(in_win[:, :, None] > 0.5, glass_tint[None, None, :], rgb)
    alpha = np.where(in_win > 0.5, glass_alpha, alpha)

    # Outer cedar window frame casing & warm sunlit window sill
    frame_outer = (
        (wx >= WIN_X0 - WIN_FRAME_W) & (wx <= WIN_X1 + WIN_FRAME_W)
        & (wz >= WIN_Z0 - WIN_FRAME_W * 1.1) & (wz <= WIN_Z1 + WIN_FRAME_W)
        & (in_win < 0.5)
    ).astype(np.float32)
    rgb = np.where(frame_outer[:, :, None] > 0.5, np.clip(c_wood_mid[None, None, :] + wood_n[:, :, None] * 0.018, 0.0, 1.0), rgb)
    alpha = np.where(frame_outer > 0.5, 1.0, alpha)

    # Projecting cedar sill catching golden afternoon light along its top rim!
    sill_top = (
        (wx >= WIN_X0 - WIN_FRAME_W * 1.35) & (wx <= WIN_X1 + WIN_FRAME_W)
        & (wz >= WIN_Z0 - 0.052) & (wz <= WIN_Z0 + 0.010)
    ).astype(np.float32)
    sill_g = smoothstep(WIN_Z0 - 0.050, WIN_Z0 + 0.008, wz)
    sill_col = c_wood_dark[None, None, :] * (1.0 - sill_g[:, :, None]) + c_wood_sill[None, None, :] * sill_g[:, :, None]
    # Crisp bright golden rim highlight right along the top edge of the sill
    sill_rim = ((wz >= WIN_Z0 + 0.001) & (wz <= WIN_Z0 + 0.010) & (wx >= WIN_X0)).astype(np.float32)
    sill_col = sill_col * (1.0 - 0.55 * sill_rim[:, :, None]) + hex_rgb("#E2B682")[None, None, :] * (0.55 * sill_rim[:, :, None])
    rgb = np.where(sill_top[:, :, None] > 0.5, np.clip(sill_col + wood_n[:, :, None] * 0.014, 0.0, 1.0), rgb)
    alpha = np.where(sill_top > 0.5, 1.0, alpha)

    # Interior vertical and horizontal cedar mullions + sunlit inner bevel highlights
    half_m = WIN_MULLION_W * 0.5
    for mx in WIN_V_MULLIONS:
        bar = (in_win > 0.5) & (np.abs(wx - mx) <= half_m)
        bevel = (in_win > 0.5) & (wx > mx - half_m) & (wx < mx - half_m + 0.009)
        bar_col = c_wood_dark[None, None, :] * 0.85 + c_wood_mid[None, None, :] * 0.15 + wood_n[:, :, None] * 0.015
        rgb = np.where(bar[:, :, None], np.clip(bar_col, 0.0, 1.0), rgb)
        rgb = np.where(bevel[:, :, None], c_wood_bevel[None, None, :], rgb)
        alpha = np.where(bar, 1.0, alpha)

    for mz in WIN_H_MULLIONS:
        bar = (in_win > 0.5) & (np.abs(wz - mz) <= half_m * 0.88)
        top_bevel = (in_win > 0.5) & (wz > mz + half_m * 0.88 - 0.009) & (wz <= mz + half_m * 0.88)
        bar_col = c_wood_dark[None, None, :] * 0.88 + c_wood_mid[None, None, :] * 0.12 + wood_n[:, :, None] * 0.015
        rgb = np.where(bar[:, :, None], np.clip(bar_col, 0.0, 1.0), rgb)
        rgb = np.where(top_bevel[:, :, None], c_wood_bevel[None, None, :] * 1.12, rgb)
        alpha = np.where(bar, 1.0, alpha)

    jamb_bevel = (in_win > 0.5) & (wx >= WIN_X0) & (wx <= WIN_X0 + 0.012)
    rgb = np.where(jamb_bevel[:, :, None], c_wood_bevel[None, None, :] * 1.08, rgb)
    alpha = np.where(jamb_bevel, 1.0, alpha)

    return np.clip(rgb, 0.0, 1.0), np.clip(alpha, 0.0, 1.0)


def paint_floor_uv(dapple_field: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Deep calm shaded wooden interior floor visible cleanly beyond the far table edge."""
    uv_w, uv_h = 800, 800
    x0, x1 = X_LEFT_WALL, 2.05
    y0, y1 = 1.40, Y_BACK_WALL
    vv, uu = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    wx = x0 + (uu / float(uv_w)) * (x1 - x0)
    wy = y0 + (vv / float(uv_h)) * (y1 - y0)
    wz = np.full_like(wx, Z_FLOOR)

    n_fl = fbm_gouache(uv_h, uv_w, octaves=((50.0, 48.0, 0.55), (18.0, 18.0, 0.30), (6.0, 6.0, 0.15)), seed=461)
    sun_fl, _ = trace_points_to_window_light(wx, wy, wz, dapple_field, penumbra_scale=1.4)
    c_sh = hex_rgb("#3B2B21")
    c_lit = hex_rgb("#78573C")
    rgb = c_sh[None, None, :] * (1.0 - 0.65 * sun_fl[:, :, None]) + c_lit[None, None, :] * (0.65 * sun_fl[:, :, None])
    return np.clip(rgb + n_fl[:, :, None] * 0.016, 0.0, 1.0), np.ones((uv_h, uv_w), dtype=np.float32)


# ---------------------------------------------------------------------------
# 9. Band 2: Sunlit Hand-Oiled Cedar Dining Tabletop + Unified 3D Cast Shadows
# ---------------------------------------------------------------------------

def paint_tabletop_uv(dapple_field: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Paint 6 solid oiled cedar/walnut dining planks flat in UV (u along +X,
    v along +Y), with organic cathedral timber grain, exact 3D ray-traced window
    sunlight & mullion shadows, and unified 3D cast shadows + contact AO."""
    uv_w, uv_h = 1600, 2200
    vv, uu = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    wx = TABLE_X0 + (uu / float(uv_w)) * (TABLE_X1 - TABLE_X0)
    wy = TABLE_Y0 + (vv / float(uv_h)) * (TABLE_Y1 - TABLE_Y0)
    wz = np.zeros_like(wx)

    # 6 longitudinal solid timber planks running toward VP (+Y at ~62.4% width)
    plank_edges = np.array([-0.62, -0.39, -0.15, 0.08, 0.32, 0.56, 0.80], dtype=np.float32)
    plank_idx = np.clip(np.searchsorted(plank_edges, wx, side="right") - 1, 0, len(plank_edges) - 2)

    rng_p = np.random.default_rng(509)
    plank_tone = np.array([-0.032, 0.024, -0.016, 0.028, -0.022, 0.018], dtype=np.float32)
    plank_warm = np.array([0.015, -0.012, 0.018, 0.008, -0.015, 0.012], dtype=np.float32)
    plank_off = rng_p.uniform(0.0, 7.0, size=6).astype(np.float32)
    plank_freq = rng_p.uniform(7.5, 11.5, size=6).astype(np.float32)

    # Smooth organic wood cathedral growth rings (balanced smooth warp — zero striping!)
    grain_warp = fbm_gouache(
        uv_h, uv_w,
        octaves=((130.0, 160.0, 0.55), (48.0, 60.0, 0.30), (18.0, 22.0, 0.15)),
        seed=521,
    )
    soft_sheen = fbm_gouache(
        uv_h, uv_w,
        octaves=((72.0, 68.0, 0.50), (26.0, 28.0, 0.35), (10.5, 10.0, 0.15)),
        seed=523,
    )
    local_x = (wx - plank_edges[plank_idx]) / (plank_edges[plank_idx + 1] - plank_edges[plank_idx])
    # Gentle cathedral arch curves along each plank
    arch_center = 0.5 + 0.22 * np.sin(plank_off[plank_idx])
    ring_coord = (
        np.abs(local_x - arch_center) * plank_freq[plank_idx]
        + 0.42 * np.sin(wy * 1.45 + plank_off[plank_idx])
        + 0.95 * grain_warp
    )
    rings_main = (0.5 + 0.5 * np.sin(ring_coord * math.pi)) ** 1.4 - 0.5
    rings_fine = (0.5 + 0.5 * np.sin(ring_coord * 2.7 * math.pi + 0.5)) - 0.5
    wood_grain = 0.036 * rings_main + 0.014 * rings_fine + 0.012 * soft_sheen

    # Refined hand-fitted plank bevel seams
    dist_seam = np.minimum(
        np.abs(wx - plank_edges[plank_idx]),
        np.abs(wx - plank_edges[plank_idx + 1]),
    )
    seam_dark = (1.0 - smoothstep(0.0010, 0.0038, dist_seam)) * 0.36
    # Delicate warm micro-highlight kissing the sunlit right lip of each plank bevel
    bevel_lip = smoothstep(0.0025, 0.0045, np.abs(wx - plank_edges[plank_idx])) * (
        1.0 - smoothstep(0.0045, 0.0095, np.abs(wx - plank_edges[plank_idx]))
    )

    # Rich warm aged cedar/oak timber palette: deep walnut-amber in shade,
    # luminous golden honey-cedar in direct afternoon sunlight!
    c_wood_shade = hex_rgb("#5A3F2D")
    c_wood_lit = hex_rgb("#D69E68")
    c_wood_spec = hex_rgb("#F7DCAC")

    # Exact 3D ray-traced sunlight & mullion bar shadows on tabletop Z = 0.0
    sun_tab, pane_open = trace_points_to_window_light(wx, wy, wz, dapple_field, penumbra_scale=1.08)

    amb_grad = smoothstep(TABLE_Y0, TABLE_Y1, wy)
    base_shade = c_wood_shade[None, None, :] * (0.84 + 0.30 * amb_grad[:, :, None])

    p_tone = plank_tone[plank_idx][:, :, None]
    p_warm = plank_warm[plank_idx][:, :, None]
    g_mod = wood_grain[:, :, None]

    wood_sh = base_shade + p_tone + g_mod * 0.85
    wood_sh[:, :, 0] += p_warm[:, :, 0]
    wood_sh[:, :, 2] -= p_warm[:, :, 0] * 0.85

    wood_lt = c_wood_lit[None, None, :] + p_tone * 1.15 + g_mod * 1.10
    wood_lt[:, :, 0] += p_warm[:, :, 0] * 1.15
    wood_lt[:, :, 2] -= p_warm[:, :, 0] * 0.70

    rgb = wood_sh * (1.0 - sun_tab[:, :, None]) + wood_lt * sun_tab[:, :, None]
    rgb += bevel_lip[:, :, None] * sun_tab[:, :, None] * np.array([0.045, 0.032, 0.018], dtype=np.float32)

    # Soft grazing specular oil sheen along sunlit timber facing the window
    spec_band = smoothstep(0.65, 2.08, wy) * smoothstep(-0.28, 0.62, wx) * pane_open
    rgb = rgb + c_wood_spec[None, None, :] * (0.14 * spec_band[:, :, None])

    # Crisp warm golden rim highlight right along the far beveled edge of the table (Y -> TABLE_Y1)
    far_rim = smoothstep(TABLE_Y1 - 0.022, TABLE_Y1 - 0.002, wy) * (0.35 + 0.65 * pane_open)
    rgb = rgb + hex_rgb("#F3D5A3")[None, None, :] * (0.18 * far_rim[:, :, None])

    rgb *= (1.0 - seam_dark[:, :, None])
    front_vig = 1.0 - 0.14 * (1.0 - smoothstep(0.15, 0.65, wy))
    rgb *= front_vig[:, :, None]

    # -----------------------------------------------------------------------
    # Unified 3D Cast Shadows & Contact Ambient Occlusion onto Z = 0.0
    # -----------------------------------------------------------------------
    cast_shadow = np.zeros((uv_h, uv_w), dtype=np.float32)
    contact_ao = np.zeros((uv_h, uv_w), dtype=np.float32)

    def xy_to_uv(pts_xy: np.ndarray) -> np.ndarray:
        u_px = (pts_xy[:, 0] - TABLE_X0) / (TABLE_X1 - TABLE_X0) * uv_w
        v_px = (pts_xy[:, 1] - TABLE_Y0) / (TABLE_Y1 - TABLE_Y0) * uv_h
        return np.round(np.column_stack([u_px, v_px])).astype(np.int32)

    def add_projected_shadow_poly(pts_3d: np.ndarray, blur_sigma: float, opacity: float) -> None:
        sh_pts = shadow_xy_on_plane(pts_3d, z_plane=0.0)
        poly_uv = xy_to_uv(sh_pts[:, :2])
        tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
        cv2.fillPoly(tmp, [poly_uv], 1.0, cv2.LINE_AA)
        if blur_sigma > 0.5:
            tmp = cv2.GaussianBlur(tmp, (0, 0), blur_sigma)
        np.maximum(cast_shadow, tmp * opacity, out=cast_shadow)

    def add_contact_ellipse(cx_m: float, cy_m: float, rx_m: float, ry_m: float, blur_sigma: float, opacity: float) -> None:
        th_e = np.linspace(0.0, 2.0 * math.pi, 48, endpoint=False)
        pts = np.column_stack([cx_m + rx_m * np.cos(th_e), cy_m + ry_m * np.sin(th_e)])
        poly_uv = xy_to_uv(pts)
        tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
        cv2.fillPoly(tmp, [poly_uv], 1.0, cv2.LINE_AA)
        tmp = cv2.GaussianBlur(tmp, (0, 0), blur_sigma)
        np.maximum(contact_ao, tmp * opacity, out=contact_ao)

    th = np.linspace(0.0, 2.0 * math.pi, 64, endpoint=False)

    # 1) Stoneware ceramic plate shadow
    plate_rim_3d = np.column_stack([
        PLATE_CENTER[0] + PLATE_R_OUTER * np.cos(th),
        PLATE_CENTER[1] + PLATE_R_OUTER * np.sin(th),
        np.full_like(th, PLATE_H_RIM * 0.94),
    ])
    plate_base_3d = np.column_stack([
        PLATE_CENTER[0] + (PLATE_R_OUTER * 0.72) * np.cos(th),
        PLATE_CENTER[1] + (PLATE_R_OUTER * 0.72) * np.sin(th),
        np.zeros_like(th),
    ])
    sh_plate_all = np.vstack([shadow_xy_on_plane(plate_rim_3d, 0.0)[:, :2], plate_base_3d[:, :2]])
    hull_uv = cv2.convexHull(xy_to_uv(sh_plate_all))
    tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
    cv2.fillConvexPoly(tmp, hull_uv, 1.0, cv2.LINE_AA)
    np.maximum(cast_shadow, cv2.GaussianBlur(tmp, (0, 0), 8.5) * 0.90, out=cast_shadow)
    add_contact_ellipse(PLATE_CENTER[0], PLATE_CENTER[1], PLATE_R_OUTER * 0.86, PLATE_R_OUTER * 0.86, 7.0, 0.66)

    # 2) Clay hashioki & lifted wooden chopsticks exact 3D cast shadows!
    #    Crisp shadow gap visibly detaches underneath the elevated left chopstick tips!
    hx, hy = HASHIOKI_CENTER[0], HASHIOKI_CENTER[1]
    hash_box = np.array([
        [hx - 0.022, hy - 0.010, 0.014],
        [hx + 0.022, hy - 0.010, 0.014],
        [hx + 0.022, hy + 0.010, 0.014],
        [hx - 0.022, hy + 0.010, 0.014],
    ])
    add_projected_shadow_poly(hash_box, blur_sigma=3.2, opacity=0.86)
    add_contact_ellipse(hx, hy, 0.023, 0.011, 3.0, 0.68)

    for p_tip, p_end in get_chopstick_segments_3d():
        vec = p_end - p_tip
        perp = np.array([-vec[1], vec[0], 0.0])
        perp /= np.linalg.norm(perp)
        quad = np.array([
            p_tip + perp * 0.0020,
            p_end + perp * 0.0044,
            p_end - perp * 0.0044,
            p_tip - perp * 0.0020,
        ])
        add_projected_shadow_poly(quad, blur_sigma=3.0, opacity=0.84)
        add_contact_ellipse(p_end[0], p_end[1], 0.013, 0.0055, 2.4, 0.48)

    # 3) Stoneware teacup diagonal shadow
    tc_x, tc_y = TEACUP_CENTER[0], TEACUP_CENTER[1]
    cup_r_top, cup_r_bot, cup_h = 0.050, 0.036, 0.080
    cup_top_3d = np.column_stack([tc_x + cup_r_top * np.cos(th), tc_y + cup_r_top * np.sin(th), np.full_like(th, cup_h)])
    cup_bot_3d = np.column_stack([tc_x + cup_r_bot * np.cos(th), tc_y + cup_r_bot * np.sin(th), np.zeros_like(th)])
    sh_cup_all = np.vstack([shadow_xy_on_plane(cup_top_3d, 0.0)[:, :2], cup_bot_3d[:, :2]])
    hull_cup = cv2.convexHull(xy_to_uv(sh_cup_all))
    tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
    cv2.fillConvexPoly(tmp, hull_cup, 1.0, cv2.LINE_AA)
    np.maximum(cast_shadow, cv2.GaussianBlur(tmp, (0, 0), 10.0) * 0.88, out=cast_shadow)
    add_contact_ellipse(tc_x, tc_y, cup_r_bot * 1.08, cup_r_bot * 1.08, 5.2, 0.72)

    # 4) Cast-iron teapot shadow
    tp_x, tp_y = TEAPOT_CENTER[0], TEAPOT_CENTER[1]
    tp_r, tp_h = 0.076, 0.106
    tp_mid_3d = np.column_stack([tp_x + tp_r * np.cos(th), tp_y + tp_r * np.sin(th), np.full_like(th, tp_h * 0.72)])
    tp_bot_3d = np.column_stack([tp_x + (tp_r * 0.80) * np.cos(th), tp_y + (tp_r * 0.80) * np.sin(th), np.zeros_like(th)])
    sh_tp_all = np.vstack([shadow_xy_on_plane(tp_mid_3d, 0.0)[:, :2], tp_bot_3d[:, :2]])
    hull_tp = cv2.convexHull(xy_to_uv(sh_tp_all))
    tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
    cv2.fillConvexPoly(tmp, hull_tp, 1.0, cv2.LINE_AA)
    np.maximum(cast_shadow, cv2.GaussianBlur(tmp, (0, 0), 11.0) * 0.86, out=cast_shadow)
    add_contact_ellipse(tp_x, tp_y, tp_r * 0.94, tp_r * 0.94, 5.8, 0.68)

    # 5) Folded warm linen napkin shadow
    nap_pts = get_napkin_polygon_3d(z_top=0.015)
    add_projected_shadow_poly(nap_pts, blur_sigma=6.5, opacity=0.74)
    nap_base_uv = xy_to_uv(nap_pts[:, :2])
    tmp = np.zeros((uv_h, uv_w), dtype=np.float32)
    cv2.fillPoly(tmp, [nap_base_uv], 1.0, cv2.LINE_AA)
    np.maximum(contact_ao, cv2.GaussianBlur(tmp, (0, 0), 6.0) * 0.52, out=contact_ao)

    # Composite unified cast shadows in rich warm-umber tint
    sh_eff = cast_shadow * (0.34 + 0.58 * sun_tab)
    shadow_tint = hex_rgb("#412C24")
    rgb = rgb * (1.0 - sh_eff[:, :, None] * 0.64) + (rgb * shadow_tint[None, None, :]) * (sh_eff[:, :, None] * 0.64)
    rgb *= (1.0 - contact_ao[:, :, None] * 0.56)

    return np.clip(rgb, 0.0, 1.0), np.ones((uv_h, uv_w), dtype=np.float32)


def paint_table_apron_uv() -> tuple[np.ndarray, np.ndarray]:
    uv_w, uv_h = 900, 80
    n_ap = fbm_gouache(uv_h, uv_w, octaves=((36.0, 16.0, 0.6), (12.0, 8.0, 0.4)), seed=557)
    c_top = hex_rgb("#4B3324")
    c_bot = hex_rgb("#261912")
    t = np.linspace(0.0, 1.0, uv_h, dtype=np.float32)[:, None, None]
    rgb = c_top[None, None, :] * (1.0 - t) + c_bot[None, None, :] * t + n_ap[:, :, None] * 0.014
    return np.clip(rgb, 0.0, 1.0), np.ones((uv_h, uv_w), dtype=np.float32)


# ---------------------------------------------------------------------------
# 10. Shared 3D Prop Geometry Helpers
# ---------------------------------------------------------------------------

def get_chopstick_segments_3d() -> list[tuple[np.ndarray, np.ndarray]]:
    """Two wooden chopsticks resting horizontally across the clay hashioki in front
    of the plate—tips gently elevated on the left, handles touching the timber on the right."""
    hx, hy = HASHIOKI_CENTER[0], HASHIOKI_CENTER[1]
    s1_tip = np.array([hx - 0.066, hy - 0.011, 0.0175], dtype=np.float64)
    s1_end = np.array([hx + 0.168, hy + 0.004, 0.0038], dtype=np.float64)
    s2_tip = np.array([hx - 0.063, hy + 0.009, 0.0175], dtype=np.float64)
    s2_end = np.array([hx + 0.170, hy + 0.022, 0.0038], dtype=np.float64)
    return [(s1_tip, s1_end), (s2_tip, s2_end)]


def get_napkin_polygon_3d(z_top: float = 0.014) -> np.ndarray:
    """Softly rounded folded warm linen napkin footprint to the back-left of plate."""
    cx, cy = NAPKIN_CENTER[0], NAPKIN_CENTER[1]
    ang = math.radians(16.0)
    ca, sa = math.cos(ang), math.sin(ang)
    # Rounded-corner soft rectangle (24 points) so cloth never reads as sharp paper!
    hx, hy, r = 0.082, 0.112, 0.018
    corners = [(-hx + r, -hy + r, math.pi, 1.5 * math.pi),
               (hx - r, -hy + r, 1.5 * math.pi, 2.0 * math.pi),
               (hx - r, hy - r, 0.0, 0.5 * math.pi),
               (-hx + r, hy - r, 0.5 * math.pi, math.pi)]
    pts = []
    for ox, oy, a0, a1 in corners:
        for a in np.linspace(a0, a1, 5):
            lx = ox + r * math.cos(a)
            ly = oy + r * math.sin(a)
            pts.append([cx + lx * ca - ly * sa, cy + lx * sa + ly * ca, z_top])
    return np.array(pts, dtype=np.float64)


# ---------------------------------------------------------------------------
# 11. Band 3: Far & Midground Tabletop Props (Teapot, Napkin, Teacup + Fresnel)
# ---------------------------------------------------------------------------

def draw_teapot(layer: CairoLayer2x, cam: Camera3D) -> np.ndarray:
    """Smooth 36-slice lathe cast-iron / dark-stoneware teapot (tetsubin) on a
    low cedar trivet, with sculpted tapered spout and arched bamboo handle."""
    glints = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    cx, cy = TEAPOT_CENTER[0], TEAPOT_CENTER[1]
    ink = (0.11, 0.09, 0.08, 0.88)

    # Low wooden trivet beneath teapot (smooth front-facing skirt + sunlit top)
    triv_top, triv_z = project_3d_ring(cam, TEAPOT_CENTER, 0.084, 0.084, 0.010, n=72)
    triv_bot, _ = project_3d_ring(cam, TEAPOT_CENTER, 0.086, 0.086, 0.000, n=72)
    t_top_front = extract_front_or_back_arc(triv_top, want_front=True)
    t_bot_front = extract_front_or_back_arc(triv_bot, want_front=True)
    skirt = np.vstack([t_top_front, t_bot_front[::-1]])
    layer.fill_poly(skirt, (0.26, 0.17, 0.12, 1.0))
    layer.fill_poly(triv_top, (0.45, 0.32, 0.21, 1.0))
    layer.stroke_catmull_rom(triv_top, triv_z, 1.4, ink, seed=601, closed=True)

    # Sculpted 3D tapered cast-iron S-spout (thick base -> fine angled pouring lip!)
    sp_spine = np.array([
        [cx - 0.058, cy - 0.006, 0.044],
        [cx - 0.086, cy - 0.014, 0.056],
        [cx - 0.112, cy - 0.020, 0.082],
        [cx - 0.128, cy - 0.024, 0.104],
    ])
    sp_curve = eval_catmull_rom(sp_spine, samples_per_seg=8, closed=False)
    sp_rads = np.linspace(0.016, 0.0055, len(sp_curve))
    up_edge = sp_curve + np.column_stack([np.zeros_like(sp_rads), np.zeros_like(sp_rads), sp_rads])
    dn_edge = sp_curve - np.column_stack([np.zeros_like(sp_rads), np.zeros_like(sp_rads), sp_rads * 0.92])
    uu_s, vu_s, zu_s = cam.project_points(up_edge)
    ud_s, vd_s, _ = cam.project_points(dn_edge)
    spout_poly = np.vstack([np.column_stack([uu_s, vu_s]), np.column_stack([ud_s, vd_s])[::-1]])
    layer.fill_poly_linear(
        spout_poly,
        (float(uu_s[-1]), float(vu_s[-1])), (float(ud_s[0]), float(vd_s[0])),
        [(0.0, (0.42, 0.36, 0.31, 1.0)), (0.45, (0.22, 0.19, 0.18, 1.0)), (1.0, (0.14, 0.12, 0.12, 1.0))],
    )
    layer.stroke_catmull_rom(np.column_stack([uu_s, vu_s]) + np.array([0.0, 2.0]), zu_s, 2.2, (0.55, 0.46, 0.37, 0.55), seed=603, taper_ends=0.35)
    layer.stroke_catmull_rom(spout_poly, zu_s[0], 1.7, ink, seed=604, closed=True, tremor=0.18)

    # Smooth 36-slice lathe rounded tetsubin body (ZERO polygonal corners!)
    profile = [
        (0.056, 0.010),
        (0.072, 0.024),
        (0.079, 0.048),
        (0.075, 0.072),
        (0.062, 0.090),
        (0.045, 0.100),
    ]
    body_contour, rings = build_smooth_lathe_silhouette(cam, TEAPOT_CENTER, profile, n_slices=38)

    u_c, v_c, z_c = cam.project_points(np.array([cx, cy, 0.055]))
    u_lit, v_lit, _ = cam.project_points(np.array([cx + 0.044, cy + 0.022, 0.076]))
    layer.fill_poly_radial(
        body_contour,
        (u_lit, v_lit, 5.0),
        (u_c - 12.0, v_c + 10.0, 102.0),
        [
            (0.00, (0.58, 0.49, 0.40, 1.0)),  # warm golden window highlight
            (0.24, (0.31, 0.28, 0.26, 1.0)),
            (0.62, (0.19, 0.18, 0.18, 1.0)),
            (0.88, (0.15, 0.14, 0.15, 1.0)),
            (1.00, (0.20, 0.17, 0.16, 1.0)),  # subtle warm tabletop bounce on underside
        ],
    )

    # Subtle decorative cast-iron equatorial shoulder line (front arc only!)
    eq_ring, _ = project_3d_ring(cam, TEAPOT_CENTER, 0.078, 0.078, 0.054, n=84)
    eq_front = extract_front_or_back_arc(eq_ring, want_front=True)
    layer.stroke_catmull_rom(eq_front, z_c, 1.3, (0.36, 0.31, 0.27, 0.35), seed=609, tremor=0.15)

    rim_u, rim_v, _ = cam.project_points(np.array([cx + 0.058, cy + 0.015, 0.066]))
    cv2.circle(glints, (int(rim_u), int(rim_v)), 5, 0.62, -1, cv2.LINE_AA)

    # Recessed fitted lid & sculpted cast-iron finial knob
    lid_ring, lid_z = project_3d_ring(cam, TEAPOT_CENTER, 0.042, 0.042, 0.103, n=64)
    layer.fill_poly_linear(
        lid_ring,
        (u_c - 32, v_c - 34), (u_c + 34, v_c - 42),
        [(0.0, (0.17, 0.16, 0.16, 1.0)), (0.65, (0.33, 0.29, 0.25, 1.0)), (1.0, (0.56, 0.47, 0.38, 1.0))],
    )
    knob_profile = [(0.008, 0.104), (0.014, 0.112), (0.012, 0.118), (0.005, 0.121)]
    knob_c, _ = build_smooth_lathe_silhouette(cam, TEAPOT_CENTER, knob_profile, n_slices=16)
    layer.fill_poly(knob_c, (0.34, 0.28, 0.24, 1.0))

    layer.stroke_catmull_rom(body_contour, z_c, 2.0, ink, seed=605, closed=True, tremor=0.18)
    layer.stroke_catmull_rom(lid_ring, lid_z, 1.4, ink, seed=606, closed=True, tremor=0.14)
    layer.stroke_catmull_rom(knob_c, z_c, 1.2, ink, seed=610, closed=True, tremor=0.10)

    # Graceful arched bent-bamboo handle with bronze lugs
    handle_t = np.linspace(0.0, math.pi, 26)
    h_pts_3d = np.column_stack([
        cx + 0.058 * np.cos(handle_t),
        cy + 0.014 * np.sin(handle_t),
        0.090 + 0.082 * np.sin(handle_t),
    ])
    hu, hv, hz = cam.project_points(h_pts_3d)
    h_2d = np.column_stack([hu, hv])
    layer.stroke_catmull_rom(h_2d, hz, 6.4, (0.21, 0.15, 0.11, 1.0), seed=607, taper_ends=0.06, tremor=0.22)
    layer.stroke_catmull_rom(h_2d + np.array([1.2, -1.2]), hz, 2.1, (0.62, 0.48, 0.34, 0.72), seed=608, taper_ends=0.16, tremor=0.14)
    return glints


def draw_linen_napkin(layer: CairoLayer2x, cam: Camera3D) -> None:
    """Softly folded plush oatmeal-ivory linen napkin resting calmly left of plate."""
    top_3d = get_napkin_polygon_3d(z_top=0.015)
    mid_3d = get_napkin_polygon_3d(z_top=0.008)
    bot_3d = get_napkin_polygon_3d(z_top=0.001)

    tu, tv, tz = cam.project_points(top_3d)
    mu, mv, _ = cam.project_points(mid_3d)
    bu, bv, bz = cam.project_points(bot_3d)
    top_2d = np.column_stack([tu, tv])
    mid_2d = np.column_stack([mu, mv])
    bot_2d = np.column_stack([bu, bv])

    # Soft folded cloth thickness layers
    layer.fill_poly(bot_2d, (0.64, 0.59, 0.52, 1.0))
    layer.fill_poly(mid_2d, (0.76, 0.71, 0.63, 1.0))

    # Top folded cloth surface catching warm sunlit gradient on right corner
    u_l, v_l = float(np.min(top_2d[:, 0])), float(np.max(top_2d[:, 1]))
    u_r, v_r = float(np.max(top_2d[:, 0])), float(np.min(top_2d[:, 1]))
    layer.fill_poly_linear(
        top_2d,
        (u_l, v_l), (u_r, v_r),
        [
            (0.00, (0.76, 0.71, 0.63, 1.0)),
            (0.45, (0.87, 0.83, 0.75, 1.0)),
            (0.85, (0.95, 0.91, 0.83, 1.0)),
            (1.00, (0.98, 0.94, 0.86, 1.0)),
        ],
    )

    # Subtle woven linen fabric texture & soft natural drape crease
    cx, cy = NAPKIN_CENTER[0], NAPKIN_CENTER[1]
    crease_3d = np.array([
        [cx - 0.068, cy - 0.025, 0.016],
        [cx + 0.002, cy - 0.006, 0.018],
        [cx + 0.068, cy + 0.024, 0.015],
    ])
    cu, cv, cz = cam.project_points(crease_3d)
    crease_2d = np.column_stack([cu, cv])
    layer.stroke_catmull_rom(crease_2d + np.array([0.0, 3.8]), cz, 9.0, (0.62, 0.56, 0.48, 0.30), seed=625, tremor=0.35)
    layer.stroke_catmull_rom(crease_2d, cz, 2.4, (0.98, 0.95, 0.89, 0.45), seed=626, tremor=0.20)

    # Subtle natural stitched hem stripe near lower fold edge
    ang = math.radians(16.0)
    ca, sa = math.cos(ang), math.sin(ang)
    hem_3d = np.array([
        [cx + (-0.072) * ca - (-0.086) * sa, cy + (-0.072) * sa + (-0.086) * ca, 0.0155],
        [cx + (0.070) * ca - (-0.086) * sa, cy + (0.070) * sa + (-0.086) * ca, 0.0155],
    ])
    hu, hv, hz = cam.project_points(hem_3d)
    layer.stroke_catmull_rom(np.column_stack([hu, hv]), hz, 1.8, (0.68, 0.56, 0.47, 0.42), seed=627, tremor=0.18)

    ink = (0.28, 0.23, 0.19, 0.68)
    bot_front = extract_front_or_back_arc(bot_2d, want_front=True)
    layer.stroke_catmull_rom(bot_front, bz[0], 1.65, ink, seed=628, tremor=0.32)
    layer.stroke_catmull_rom(top_2d, tz[0], 1.55, ink, seed=629, closed=True, tremor=0.32)


def draw_teacup_and_fresnel_tea(
    base_canvas: np.ndarray,
    cam: Camera3D,
    exterior_bg: np.ndarray,
    dapple_field: np.ndarray,
    paper_tooth: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    """Smooth 36-slice stoneware teacup (`yunomi`) with true downward-curving
    terracotta clay foot band, rich translucent roasted amber tea, unmistakable
    3D Fresnel window/mullion/sky reflection, capillary micro-ripples, and curling
    Bezier steam wisps."""
    glints = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    layer = CairoLayer2x()
    cx, cy = TEACUP_CENTER[0], TEACUP_CENTER[1]
    cup_h = 0.080
    tea_z = 0.070
    r_top = 0.050
    ink = (0.17, 0.13, 0.11, 0.86)

    # 1. Smooth 36-slice hand-thrown ceramic lathe profile (ZERO polygonal kinks!)
    profile = [
        (0.035, 0.000),
        (0.038, 0.010),
        (0.044, 0.022),
        (0.051, 0.044),
        (0.052, 0.064),
        (r_top, cup_h),
    ]
    body_contour, _ = build_smooth_lathe_silhouette(
        cam, TEACUP_CENTER, profile, n_slices=38, wobble_amp=0.0005, seed=640
    )

    u_c, v_c, z_c = cam.project_points(np.array([cx, cy, 0.042]))
    u_l, v_l, _ = cam.project_points(np.array([cx - 0.058, cy - 0.01, 0.042]))
    u_r, v_r, _ = cam.project_points(np.array([cx + 0.058, cy + 0.01, 0.042]))

    # Muted kiln-ash / celadon stoneware body glaze
    layer.fill_poly_linear(
        body_contour,
        (u_l, v_l), (u_r, v_r),
        [
            (0.00, (0.29, 0.30, 0.27, 1.0)),  # cool-warm shaded left wall
            (0.28, (0.39, 0.41, 0.37, 1.0)),
            (0.60, (0.55, 0.56, 0.51, 1.0)),
            (0.84, (0.78, 0.76, 0.67, 1.0)),  # golden afternoon sunlight wrap
            (1.00, (0.91, 0.85, 0.74, 1.0)),  # luminous window rim catch
        ],
    )

    # TRUE 3D downward-curving (U-shaped) unglazed terracotta clay foot band!
    # Built strictly from the front-facing arcs of the lower rings so perspective is exact!
    foot_bot_ring, _ = project_3d_ring(cam, TEACUP_CENTER, 0.035, 0.035, 0.000, n=96, wobble_amp=0.0004, seed=640)
    foot_mid_ring, _ = project_3d_ring(cam, TEACUP_CENTER, 0.0385, 0.0385, 0.011, n=96, wobble_amp=0.0004, seed=640)
    # Organic hand-dipped wavy glaze line at z ≈ 0.019 m along the front of the cup
    th_f = np.linspace(0.0, 2.0 * math.pi, 96, endpoint=False)
    glaze_drip_z = 0.0185 + 0.0022 * np.sin(3.0 * th_f + 0.8) + 0.0012 * np.cos(7.0 * th_f)
    glaze_r = 0.0415 + (glaze_drip_z - 0.018) * 0.38
    drip_pts_3d = np.column_stack([cx + glaze_r * np.cos(th_f), cy + glaze_r * np.sin(th_f), glaze_drip_z])
    du, dv, _ = cam.project_points(drip_pts_3d)
    drip_ring = np.column_stack([du, dv])

    bot_front = extract_front_or_back_arc(foot_bot_ring, want_front=True)
    mid_front_l = extract_front_or_back_arc(foot_mid_ring, want_front=True)
    drip_front = extract_front_or_back_arc(drip_ring, want_front=True)

    # Combine strictly the viewer-facing bottom curve + front glaze drip boundary -> downward U band!
    foot_band = np.vstack([drip_front, mid_front_l[-1:], bot_front[::-1], mid_front_l[0:1]])
    layer.fill_poly_linear(
        foot_band,
        (u_l, v_l), (u_r, v_r),
        [
            (0.00, (0.43, 0.24, 0.18, 1.0)),  # shaded terracotta clay
            (0.48, (0.65, 0.37, 0.27, 1.0)),  # #BA6348 warm clay accent
            (0.88, (0.82, 0.49, 0.36, 1.0)),  # sunlit terracotta clay
            (1.00, (0.88, 0.56, 0.41, 1.0)),
        ],
    )
    # Subtle glaze-thickness drip shadow right along the wavy glaze boundary
    layer.stroke_catmull_rom(drip_front + np.array([0.0, 1.2]), z_c, 1.5, (0.32, 0.19, 0.14, 0.48), seed=648, tremor=0.18)

    # Subtle hand-thrown wheel ribs (front-facing downward U arcs!)
    for rib_idx, (rib_z, rib_r) in enumerate([(0.032, 0.0478), (0.049, 0.0515), (0.065, 0.0516)]):
        rr, _ = project_3d_ring(cam, TEACUP_CENTER, rib_r, rib_r, rib_z, n=84, wobble_amp=0.0004, seed=641)
        f_arc = extract_front_or_back_arc(rr, want_front=True)
        layer.stroke_catmull_rom(f_arc[4:-4], z_c, 1.15, (0.26, 0.26, 0.23, 0.22), seed=642 + rib_idx, tremor=0.15)

    # Top ceramic lip rim (thick handmade stoneware + subtle iron-brown glaze edge)
    outer_rim, outer_z = project_3d_ring(cam, TEACUP_CENTER, r_top, r_top, cup_h, n=96, wobble_amp=0.0005, seed=643)
    inner_rim, inner_z = project_3d_ring(cam, TEACUP_CENTER, r_top - 0.0054, r_top - 0.0054, cup_h - 0.001, n=96, wobble_amp=0.0004, seed=643)

    layer.fill_poly_linear(
        outer_rim,
        (u_l, v_l), (u_r, v_r),
        [(0.0, (0.46, 0.42, 0.37, 1.0)), (0.5, (0.68, 0.63, 0.55, 1.0)), (1.0, (0.89, 0.83, 0.72, 1.0))],
    )
    layer.fill_poly_linear(
        inner_rim,
        (u_l, v_l), (u_r, v_r),
        [(0.0, (0.64, 0.59, 0.52, 1.0)), (0.5, (0.42, 0.40, 0.36, 1.0)), (1.0, (0.25, 0.23, 0.21, 1.0))],
    )

    # Crisp tapered cel ink outlines
    layer.stroke_catmull_rom(body_contour, z_c, 2.2, ink, seed=644, closed=True, tremor=0.22)
    layer.stroke_catmull_rom(outer_rim, outer_z, 2.0, (0.31, 0.21, 0.16, 0.85), seed=645, closed=True, tremor=0.18)
    layer.stroke_catmull_rom(inner_rim, inner_z, 1.2, (0.22, 0.17, 0.14, 0.58), seed=646, closed=True, tremor=0.16)

    # Ceramic glaze vertical specular gleam on sunlit right curve
    spec_u, spec_v, _ = cam.project_points(np.array([cx + 0.039, cy + 0.012, 0.050]))
    spec_pts = np.array([[spec_u - 1.5, spec_v - 19.0], [spec_u + 1.8, spec_v], [spec_u - 1.2, spec_v + 15.0]])
    layer.stroke_catmull_rom(spec_pts, z_c, 4.6, (0.99, 0.95, 0.85, 0.76), seed=647, taper_ends=0.38, tremor=0.12)
    cv2.circle(glints, (int(spec_u), int(spec_v - 6)), 6, 0.78, -1, cv2.LINE_AA)

    cup_rgb, cup_a = layer.finish()
    cup_rgb = paint_isotropic_gouache_dabs(
        cup_rgb, cup_a, paper_tooth, dab_strength=0.030, warm_bounce_in_shadow=0.020, num_dabs=80, seed=649
    )
    out = alpha_composite(base_canvas, cup_rgb, cup_a)

    # -----------------------------------------------------------------------
    # 2. Jewel-Like Amber Tea + Crisp 3D Fresnel Window Sky & Mullion Reflection
    # -----------------------------------------------------------------------
    tea_ring, _ = project_3d_ring(cam, TEACUP_CENTER, r_top - 0.0056, r_top - 0.0056, tea_z, n=96, wobble_amp=0.0003, seed=650)
    tea_mask = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    cv2.fillPoly(tea_mask, [np.round(tea_ring).astype(np.int32)], 1.0, cv2.LINE_AA)
    inner_mask = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    cv2.fillPoly(inner_mask, [np.round(inner_rim).astype(np.int32)], 1.0, cv2.LINE_AA)
    tea_mask = np.minimum(tea_mask, inner_mask)

    ys, xs = np.nonzero(tea_mask > 0.01)
    if len(xs) > 0:
        x0, x1 = max(0, int(xs.min()) - 4), min(WIDTH, int(xs.max()) + 5)
        y0, y1 = max(0, int(ys.min()) - 4), min(HEIGHT, int(ys.max()) + 5)
        roi_h, roi_w = y1 - y0, x1 - x0
        roi_m = tea_mask[y0:y1, x0:x1]

        _, _, hx_all, hy_all, _ = cam.ray_plane_hit(
            np.array([cx, cy, tea_z]), np.array([0.0, 0.0, 1.0])
        )
        hx = hx_all[y0:y1, x0:x1]
        hy = hy_all[y0:y1, x0:x1]

        rad = np.sqrt((hx - cx) ** 2 + (hy - cy) ** 2) / (r_top - 0.0056)
        # Rich deep roasted hojicha / oolong amber liquid base (vibrant warm mahogany -> honey!)
        c_tea_deep = hex_rgb("#3D1605")
        c_tea_mid = hex_rgb("#963F10")
        c_tea_lit = hex_rgb("#DF8A26")
        sun_bias = np.clip(0.50 - 0.70 * (hx - cx) / r_top - 0.40 * (hy - cy) / r_top, 0.0, 1.0)
        tea_base = (
            c_tea_deep[None, None, :] * (1.0 - smoothstep(0.18, 0.94, rad)[:, :, None])
            + c_tea_mid[None, None, :] * smoothstep(0.18, 0.94, rad)[:, :, None]
        )
        tea_base = tea_base * (1.0 - 0.60 * sun_bias[:, :, None]) + c_tea_lit[None, None, :] * (0.60 * sun_bias[:, :, None])

        # Non-periodic capillary micro-ripples (stretched noise strictly on liquid surface)
        rip_x = fbm_gouache(roi_h, roi_w, octaves=((16.0, 5.2, 0.55), (6.5, 2.5, 0.45)), seed=651)
        rip_y = fbm_gouache(roi_h, roi_w, octaves=((13.0, 4.8, 0.55), (5.5, 2.3, 0.45)), seed=652)

        rx = cam.ray_world_x[y0:y1, x0:x1] + 0.014 * rip_x
        ry = cam.ray_world_y[y0:y1, x0:x1] + 0.010 * rip_y
        rz = -cam.ray_world_z[y0:y1, x0:x1] + 0.012 * rip_y

        t_win = (Y_BACK_WALL - hy) / np.maximum(ry, 0.05)
        wx_ref = hx + t_win * rx
        wz_ref = tea_z + t_win * rz

        ref_pts = np.stack([wx_ref, np.full_like(wx_ref, Y_BACK_WALL), wz_ref], axis=-1).reshape(-1, 3)
        ru, rv, _ = cam.project_points(ref_pts)
        map_x = np.clip(ru.reshape(roi_h, roi_w), 0.0, WIDTH - 1.0).astype(np.float32)
        map_y = np.clip(rv.reshape(roi_h, roi_w), 0.0, HEIGHT - 1.0).astype(np.float32)
        sky_refl = cv2.remap(exterior_bg, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)

        # Crisp reflected bright window pane + cedar mullion bar silhouette across tea!
        in_win_ref = (
            smoothstep(WIN_X0 - 0.015, WIN_X0 + 0.015, wx_ref)
            * (1.0 - smoothstep(WIN_X1 - 0.015, WIN_X1 + 0.015, wx_ref))
            * smoothstep(WIN_Z0 - 0.015, WIN_Z0 + 0.015, wz_ref)
            * (1.0 - smoothstep(WIN_Z1 - 0.015, WIN_Z1 + 0.015, wz_ref))
        )
        mull_ref = np.ones_like(in_win_ref)
        for mx in WIN_V_MULLIONS:
            mull_ref *= smoothstep(WIN_MULLION_W * 0.45, WIN_MULLION_W * 0.82, np.abs(wx_ref - mx))
        for mz in WIN_H_MULLIONS:
            mull_ref *= smoothstep(WIN_MULLION_W * 0.45, WIN_MULLION_W * 0.82, np.abs(wz_ref - mz))

        c_mull_dark = hex_rgb("#26170F")
        # Boost luminous sky contrast inside the window reflection so window & mullions read crisply!
        sky_gloss = np.clip(sky_refl * 1.28 + 0.08, 0.0, 1.0)
        win_refl_rgb = c_mull_dark[None, None, :] * (1.0 - (in_win_ref * mull_ref)[:, :, None]) + sky_gloss * (in_win_ref * mull_ref)[:, :, None]

        # Fresnel grazing-angle weighting: transparent deep amber looking steep down (front),
        # crisp bright window-sky mirror across the grazing back-right liquid surface!
        yy_roi = np.arange(y0, y1, dtype=np.float32)[:, None]
        dist_t = np.clip((yy_roi - cam.horizon_y) / max(1.0, float(HEIGHT) - cam.horizon_y), 0.0, 1.0)
        fresnel_base = 0.24 + (0.82 - 0.24) * ((1.0 - dist_t) ** 1.4)
        local_back = 1.0 - np.clip((yy_roi - y0) / max(roi_h, 1.0), 0.0, 1.0)
        fresnel_cup = np.clip(fresnel_base * (0.42 + 1.12 * (local_back ** 1.05)), 0.16, 0.88)

        tea_final = tea_base * (1.0 - fresnel_cup[:, :, None]) + win_refl_rgb * fresnel_cup[:, :, None]

        # Glassy curved meniscus highlight hugging front-left sunlit inner stoneware wall
        meniscus = smoothstep(0.84, 0.985, rad) * (0.35 + 0.65 * sun_bias)
        tea_final = np.clip(tea_final + hex_rgb("#FFF4D2")[None, None, :] * (0.55 * meniscus[:, :, None]), 0.0, 1.0)

        # Tiny delicate rippled specular glint on the liquid surface
        glint_patch = np.exp(-(((hx - (cx + 0.012)) / 0.014) ** 2 + ((hy - (cy + 0.008)) / 0.006) ** 2))
        glint_patch *= np.clip(0.5 + 0.6 * rip_y, 0.0, 1.0) * mull_ref
        tea_final = np.clip(tea_final + hex_rgb("#FFFBF0")[None, None, :] * (0.38 * glint_patch[:, :, None]), 0.0, 1.0)

        out[y0:y1, x0:x1] = alpha_composite(out[y0:y1, x0:x1], tea_final, roi_m)

        tea_lum = 0.2126 * tea_final[:, :, 0] + 0.7152 * tea_final[:, :, 1] + 0.0722 * tea_final[:, :, 2]
        glints[y0:y1, x0:x1] = np.maximum(
            glints[y0:y1, x0:x1],
            np.clip((tea_lum - 0.64) * 2.4, 0.0, 0.98) * roi_m,
        )

    # -----------------------------------------------------------------------
    # 3. Delicate Seeded Cubic Bezier Steam Wisps Drifting into the Sunbeam
    # -----------------------------------------------------------------------
    steam_layer = CairoLayer2x()
    rng_st = np.random.default_rng(661)
    u_tea, v_tea, _ = cam.project_points(np.array([cx, cy, tea_z + 0.008]))

    for s_idx in range(4):
        ox = float(rng_st.uniform(-24.0, 24.0))
        oy = float(rng_st.uniform(-3.0, 3.0))
        h_rise = float(rng_st.uniform(125.0, 215.0))
        drift = float(rng_st.uniform(-38.0, -12.0))
        sway = float(rng_st.uniform(18.0, 34.0)) * (1.0 if s_idx % 2 == 0 else -1.0)

        p0 = np.array([u_tea + ox, v_tea + oy])
        p1 = p0 + np.array([sway, -h_rise * 0.34])
        p2 = p0 + np.array([drift - sway * 0.75, -h_rise * 0.70])
        p3 = p0 + np.array([drift * 1.25 + sway * 0.25, -h_rise])

        ts = np.linspace(0.0, 1.0, 30)
        om = 1.0 - ts
        wisp = (
            (om ** 3)[:, None] * p0
            + (3 * om ** 2 * ts)[:, None] * p1
            + (3 * om * ts ** 2)[:, None] * p2
            + (ts ** 3)[:, None] * p3
        )
        steam_layer.stroke_catmull_rom(
            wisp, z_depths=1.4, base_width=float(rng_st.uniform(10.0, 16.0)),
            rgba=(1.0, 0.97, 0.89, 0.16), seed=665 + s_idx, taper_ends=0.42, tremor=0.9,
        )
        steam_layer.stroke_catmull_rom(
            wisp + np.array([2.2, 0.0]), z_depths=1.4, base_width=float(rng_st.uniform(3.4, 5.6)),
            rgba=(1.0, 0.99, 0.94, 0.30), seed=675 + s_idx, taper_ends=0.45, tremor=0.55,
        )

    st_rgb, st_a = steam_layer.finish()
    st_rgb = cv2.GaussianBlur(st_rgb, (0, 0), 2.2)
    st_a = cv2.GaussianBlur(st_a, (0, 0), 2.4)
    out = screen_blend(out, st_rgb * st_a[:, :, None], strength=0.92)
    return out, glints


# ---------------------------------------------------------------------------
# 12. Band 4: Near-Midground Hero — Handmade Stoneware Plate, Calmly Untouched
#     Food Portion (~30%), Clay Hashioki, and Horizontally Resting Chopsticks
# ---------------------------------------------------------------------------

def draw_hero_plate_and_paused_meal(
    base_canvas: np.ndarray,
    cam: Camera3D,
    paper_tooth: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    """Render the handmade stoneware plate (warm cream glaze + #BA6348 clay rim),
    unified soft ray-cast food shadows, cleanly visible ~30% untouched portion of
    roasted kabocha squash slices, steamed rice, and blanched greens on the right arc,
    and sculpted terracotta hashioki + horizontally resting wooden chopsticks."""
    glints = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    plate_layer = CairoLayer2x()
    cx, cy = PLATE_CENTER[0], PLATE_CENTER[1]
    ink_dark = (0.18, 0.13, 0.10, 0.86)
    ink_soft = (0.31, 0.23, 0.18, 0.56)

    # 1. Smooth 3D wheel-thrown stoneware plate profile (ZERO interior crossing lines!)
    foot_ring, _ = project_3d_ring(cam, PLATE_CENTER, 0.094, 0.094, 0.000, n=120, wobble_amp=0.0006, seed=701)
    belly_ring, _ = project_3d_ring(cam, PLATE_CENTER, 0.128, 0.128, 0.009, n=120, wobble_amp=0.0009, seed=701)
    rim_outer, rim_z = project_3d_ring(cam, PLATE_CENTER, PLATE_R_OUTER, PLATE_R_OUTER, PLATE_H_RIM, n=120, wobble_amp=0.0010, seed=701)
    rim_crest, _ = project_3d_ring(cam, PLATE_CENTER, PLATE_R_OUTER - 0.0058, PLATE_R_OUTER - 0.0058, PLATE_H_RIM + 0.0005, n=120, wobble_amp=0.0009, seed=701)
    well_edge, well_z = project_3d_ring(cam, PLATE_CENTER, PLATE_R_WELL, PLATE_R_WELL, PLATE_H_WELL + 0.001, n=108, wobble_amp=0.0008, seed=701)

    # Smooth convex hull of dense 120-pt rings gives the exact exterior plate silhouette!
    outer_hull = cv2.convexHull(np.vstack([foot_ring, belly_ring, rim_outer]).astype(np.float32)).reshape(-1, 2)

    u_l, v_l, _ = cam.project_points(np.array([cx - PLATE_R_OUTER, cy - 0.02, PLATE_H_RIM]))
    u_r, v_r, _ = cam.project_points(np.array([cx + PLATE_R_OUTER, cy + 0.02, PLATE_H_RIM]))
    u_f, v_f, _ = cam.project_points(np.array([cx, cy - PLATE_R_OUTER, 0.0]))
    u_b, v_b, _ = cam.project_points(np.array([cx, cy + PLATE_R_OUTER, PLATE_H_RIM]))
    u_c, v_c, z_c = cam.project_points(np.array([cx, cy, PLATE_H_WELL]))

    # Richly shaded curved outer ceramic underside (front-left in warm-cool shadow!)
    plate_layer.fill_poly_linear(
        outer_hull,
        (u_l, v_f), (u_r, v_b),
        [
            (0.00, (0.48, 0.39, 0.34, 1.0)),  # deep warm-shaded front underside
            (0.32, (0.64, 0.51, 0.43, 1.0)),
            (0.68, (0.78, 0.65, 0.55, 1.0)),
            (1.00, (0.87, 0.78, 0.68, 1.0)),
        ],
    )

    # Terracotta / clay #BA6348 outer lip band circling the stoneware rim
    c_clay_lit = hex_rgb("#CE7556")
    c_clay_mid = hex_rgb("#BA6348")
    c_clay_sh = hex_rgb("#823D2B")
    plate_layer.fill_poly_linear(
        rim_outer,
        (u_l, v_f), (u_r, v_b),
        [
            (0.00, (float(c_clay_sh[0]), float(c_clay_sh[1]), float(c_clay_sh[2]), 1.0)),
            (0.45, (float(c_clay_mid[0]), float(c_clay_mid[1]), float(c_clay_mid[2]), 1.0)),
            (1.00, (float(c_clay_lit[0]), float(c_clay_lit[1]), float(c_clay_lit[2]), 1.0)),
        ],
    )

    # Sloping stoneware rim (sunlit warm cream glaze with subtle cel-shadow depth on back-right slope!)
    plate_layer.fill_poly_linear(
        rim_crest,
        (u_l, v_f), (u_r, v_b),
        [
            (0.00, (0.94, 0.90, 0.83, 1.0)),  # front-left inner rim slope faces directly toward sun!
            (0.38, (0.96, 0.93, 0.86, 1.0)),
            (0.75, (0.87, 0.82, 0.75, 1.0)),  # back-right inner slope turns gently into self-shadow
            (1.00, (0.80, 0.74, 0.67, 1.0)),
        ],
    )

    # Concave interior plate well (sunlit clean cream expanse on open left-front 70%!)
    plate_layer.fill_poly_radial(
        well_edge,
        (u_c - 42.0, v_c + 12.0, 22.0),
        (u_c + 24.0, v_c - 12.0, 200.0),
        [
            (0.00, (0.96, 0.93, 0.86, 1.0)),
            (0.55, (0.92, 0.88, 0.81, 1.0)),
            (0.84, (0.83, 0.78, 0.71, 1.0)),
            (1.00, (0.76, 0.70, 0.64, 1.0)),
        ],
    )

    # Kiln iron-fleck speckles subtly baked into the stoneware glaze
    rng_sp = np.random.default_rng(709)
    ctx_p = plate_layer.ctx
    for _ in range(56):
        ang = float(rng_sp.uniform(0.0, 2.0 * math.pi))
        rad = math.sqrt(float(rng_sp.uniform(0.04, 0.96))) * (PLATE_R_OUTER - 0.009)
        z_sp = PLATE_H_WELL if rad < PLATE_R_WELL else PLATE_H_WELL + (PLATE_H_RIM - PLATE_H_WELL) * ((rad - PLATE_R_WELL) / (PLATE_R_OUTER - PLATE_R_WELL))
        su, sv, _ = cam.project_points(np.array([cx + rad * math.cos(ang), cy + rad * math.sin(ang), z_sp]))
        ctx_p.arc(su, sv, float(rng_sp.uniform(0.55, 1.45)), 0, 2.0 * math.pi)
        ctx_p.set_source_rgba(0.36, 0.27, 0.22, float(rng_sp.uniform(0.12, 0.30)))
        ctx_p.fill()

    # Very subtle hint of warm amber glaze & 3 stray toasted sesame seeds on the open 70%
    glaze_p = np.array([
        [cx - 0.056, cy - 0.016, PLATE_H_WELL + 0.0005],
        [cx - 0.024, cy - 0.028, PLATE_H_WELL + 0.0005],
        [cx + 0.004, cy - 0.010, PLATE_H_WELL + 0.0005],
        [cx - 0.024, cy + 0.010, PLATE_H_WELL + 0.0005],
    ])
    gu, gv, _ = cam.project_points(glaze_p)
    plate_layer.fill_poly(np.column_stack([gu, gv]), (0.85, 0.76, 0.62, 0.13))
    for sx_o, sy_o in [(-0.042, -0.015), (-0.018, -0.028), (-0.054, 0.010)]:
        su, sv, _ = cam.project_points(np.array([cx + sx_o, cy + sy_o, PLATE_H_WELL + 0.0008]))
        ctx_p.save()
        ctx_p.translate(su, sv)
        ctx_p.rotate(float(rng_sp.uniform(0, 3.14)))
        ctx_p.scale(1.65, 0.88)
        ctx_p.arc(0, 0, 1.45, 0, 2 * math.pi)
        ctx_p.restore()
        ctx_p.set_source_rgba(0.22, 0.16, 0.13, 0.74)
        ctx_p.fill()

    # Tapered warm cel-ink contours (strictly around exterior hull, clay rim, and inner well!)
    plate_layer.stroke_catmull_rom(outer_hull, z_c, 2.35, ink_dark, seed=711, closed=True, tremor=0.20)
    plate_layer.stroke_catmull_rom(rim_outer, rim_z, 1.85, (0.42, 0.22, 0.16, 0.72), seed=712, closed=True, tremor=0.18)
    plate_layer.stroke_catmull_rom(well_edge, well_z, 1.10, ink_soft, seed=713, closed=True, tremor=0.16)

    # Luminous sunlit rim highlight kissing the upper-right ceramic lip
    spec_rim = rim_crest[10:28]
    plate_layer.stroke_catmull_rom(spec_rim, z_c, 3.2, (1.0, 0.98, 0.90, 0.82), seed=714, taper_ends=0.38, tremor=0.12)
    for pt in spec_rim[::4]:
        cv2.circle(glints, (int(pt[0]), int(pt[1])), 5, 0.66, -1, cv2.LINE_AA)

    plate_rgb, plate_a = plate_layer.finish()
    plate_rgb = paint_isotropic_gouache_dabs(
        plate_rgb, plate_a, paper_tooth, dab_strength=0.028, warm_bounce_in_shadow=0.018, num_dabs=86, seed=715
    )
    out = alpha_composite(base_canvas, plate_rgb, plate_a)

    # -----------------------------------------------------------------------
    # 2. Untouched ~30% Food Portion + Unified Soft Ray-Cast Food Shadow
    #    Layout (back-right arc, leaving open left 70% calm and clear):
    #      - Back-left of cluster: glistening dark-emerald blanched greens
    #      - Upper-center-right & back-right: TWO full visible golden roasted
    #        kabocha squash wedges (zero occlusion by rice!)
    #      - Front-right of cluster: neat compact pearl steamed rice mound
    #        with scalloped grain contour and black sesame seeds
    # -----------------------------------------------------------------------
    food_layer = CairoLayer2x()
    _draw_blanched_greens(food_layer, cam)
    _draw_kabocha_slice(
        food_layer, cam, glints,
        origin=np.array([cx + 0.010, cy + 0.036, PLATE_H_WELL]),
        yaw_deg=-12.0, r_outer=0.046, r_inner=0.020, thick=0.0155, seed=731,
    )
    _draw_kabocha_slice(
        food_layer, cam, glints,
        origin=np.array([cx + 0.044, cy + 0.024, PLATE_H_WELL + 0.0015]),
        yaw_deg=-28.0, r_outer=0.045, r_inner=0.019, thick=0.0155, seed=737,
    )
    _draw_steamed_rice_mound(
        food_layer, cam, glints,
        center=np.array([cx + 0.054, cy - 0.025, PLATE_H_WELL]),
        seed=743,
    )
    food_rgb, food_a = food_layer.finish()
    food_rgb = paint_isotropic_gouache_dabs(
        food_rgb, food_a, paper_tooth, dab_strength=0.026, warm_bounce_in_shadow=0.024, num_dabs=80, seed=751
    )

    # Compute ONE smooth unified 3D ray-cast food shadow from food_a shifted strictly
    # along the screen projection of SUN_DIR on Z = PLATE_H_WELL (ZERO double-oval edges!)
    p_ref0 = np.array([cx + 0.03, cy + 0.01, PLATE_H_WELL + 0.014])
    p_ref_sh = shadow_xy_on_plane(p_ref0, z_plane=PLATE_H_WELL)
    u0_s, v0_s, _ = cam.project_points(p_ref0)
    u1_s, v1_s, _ = cam.project_points(p_ref_sh)
    dx_sh, dy_sh = float(u1_s - u0_s), float(v1_s - v0_s)

    m_cast = np.array([[1.0, 0.0, dx_sh], [0.0, 1.0, dy_sh]], dtype=np.float32)
    m_ao = np.array([[1.0, 0.0, dx_sh * 0.22], [0.0, 1.0, dy_sh * 0.22 + 2.0]], dtype=np.float32)
    sh_cast = cv2.warpAffine(food_a, m_cast, (WIDTH, HEIGHT), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
    sh_ao = cv2.warpAffine(food_a, m_ao, (WIDTH, HEIGHT), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
    sh_soft = cv2.GaussianBlur(sh_cast, (0, 0), 5.2) * 0.34
    ao_tight = cv2.GaussianBlur(sh_ao, (0, 0), 1.8) * 0.42

    # Restrict food shadow cleanly inside the stoneware plate well!
    well_clip = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
    cv2.fillPoly(well_clip, [np.round(well_edge).astype(np.int32)], 1.0, cv2.LINE_AA)
    plate_food_sh = np.clip(np.maximum(sh_soft, ao_tight), 0.0, 0.56) * well_clip

    sh_plate_col = hex_rgb("#48382F")
    out = out * (1.0 - plate_food_sh[:, :, None]) + (out * sh_plate_col[None, None, :]) * plate_food_sh[:, :, None]
    out = alpha_composite(out, food_rgb, food_a)

    # -----------------------------------------------------------------------
    # 3. Sculpted Terracotta Clay Hashioki & Horizontally Resting Chopsticks
    # -----------------------------------------------------------------------
    chop_layer = CairoLayer2x()
    _draw_hashioki_and_chopsticks(chop_layer, cam, glints)
    chop_rgb, chop_a = chop_layer.finish()
    chop_rgb = paint_isotropic_gouache_dabs(
        chop_rgb, chop_a, paper_tooth, dab_strength=0.022, warm_bounce_in_shadow=0.018, num_dabs=72, seed=761
    )
    out = alpha_composite(out, chop_rgb, chop_a)

    return out, glints


def _draw_blanched_greens(layer: CairoLayer2x, cam: Camera3D) -> None:
    """Tidy folded bundle of glistening dark-emerald blanched spinach/komatsuna
    leaves tucked gracefully beside the roasted kabocha squash."""
    cx, cy = PLATE_CENTER[0], PLATE_CENTER[1]
    base = np.array([cx - 0.018, cy + 0.026, PLATE_H_WELL + 0.002])
    ink = (0.10, 0.16, 0.10, 0.84)

    leaf_specs = [
        (-0.024, -0.010, 0.003, 0.038, 0.016, 30.0, 0.05),
        (-0.011, 0.009, 0.005, 0.040, 0.017, -6.0, 0.22),
        (0.006, 0.015, 0.007, 0.038, 0.016, -26.0, 0.40),
        (-0.020, 0.004, 0.008, 0.036, 0.015, 18.0, 0.54),
        (-0.013, -0.002, 0.010, 0.035, 0.015, 8.0, 0.68),
        (0.000, -0.006, 0.011, 0.033, 0.014, -14.0, 0.80),
        (-0.007, 0.006, 0.013, 0.030, 0.013, 14.0, 0.92),
        (0.007, 0.003, 0.0145, 0.027, 0.012, -8.0, 1.00),
    ]
    c_sh = hex_rgb("#213923")
    c_mid = hex_rgb("#396139")
    c_lit = hex_rgb("#79A35F")

    for idx, (dx, dy, dz, l_len, l_wid, ang_deg, lit) in enumerate(leaf_specs):
        ang = math.radians(ang_deg)
        ca, sa = math.cos(ang), math.sin(ang)
        p0 = base + np.array([dx, dy, dz])
        pts_3d = []
        for k in range(18):
            th = 2.0 * math.pi * k / 18.0
            lx = (l_len * 0.5) * math.cos(th)
            ly = (l_wid * 0.5) * math.sin(th) * (1.0 + 0.18 * math.sin(2.0 * th))
            lz = 0.0040 * math.sin(math.pi * (0.5 + 0.5 * math.cos(th)))
            pts_3d.append(p0 + np.array([lx * ca - ly * sa, lx * sa + ly * ca, lz]))
        u, v, zc = cam.project_points(np.array(pts_3d))
        poly_2d = np.column_stack([u, v])

        col = c_sh * (1.0 - lit / 0.55) + c_mid * (lit / 0.55) if lit < 0.55 else c_mid * (1.0 - (lit - 0.55) / 0.45) + c_lit * ((lit - 0.55) / 0.45)
        layer.fill_poly(poly_2d, (float(col[0]), float(col[1]), float(col[2]), 0.98))
        if lit > 0.42:
            ridge_3d = np.array([
                p0 + np.array([-l_len * 0.28 * ca, -l_len * 0.28 * sa, 0.0045]),
                p0 + np.array([0.0, 0.0, 0.0062]),
                p0 + np.array([l_len * 0.28 * ca, l_len * 0.28 * sa, 0.0045]),
            ])
            ru, rv, rz = cam.project_points(ridge_3d)
            layer.stroke_catmull_rom(
                np.column_stack([ru, rv]), rz, 2.5, (0.82, 0.93, 0.68, 0.58),
                seed=728 + idx, taper_ends=0.42, tremor=0.18,
            )
        layer.stroke_catmull_rom(poly_2d, zc, 1.35, ink, seed=729 + idx, closed=True, tremor=0.20)

    # 3 tiny golden toasted sesame seeds resting atop the blanched greens
    ctx = layer.ctx
    for sx_g, sy_g, sz_g in [(-0.008, 0.004, 0.015), (0.004, 0.001, 0.015), (-0.014, -0.002, 0.013)]:
        su, sv, _ = cam.project_points(base + np.array([sx_g, sy_g, sz_g]))
        ctx.save()
        ctx.translate(su, sv)
        ctx.rotate(0.6)
        ctx.scale(1.6, 0.9)
        ctx.arc(0, 0, 1.5, 0, 2 * math.pi)
        ctx.restore()
        ctx.set_source_rgba(0.95, 0.85, 0.62, 0.92)
        ctx.fill()


def _draw_kabocha_slice(
    layer: CairoLayer2x,
    cam: Camera3D,
    glints: np.ndarray,
    origin: np.ndarray,
    yaw_deg: float,
    r_outer: float,
    r_inner: float,
    thick: float,
    seed: int,
) -> None:
    """Tender, gently beveled 3D crescent wedge of roasted glazed kabocha squash:
    dark forest-jade rind with subtle sage ribs, luscious saffron-gold flesh,
    caramelized glaze edges, specular mirin gleam, and crisp warm-brown cel ink."""
    yaw = math.radians(yaw_deg)
    ca, sa = math.cos(yaw), math.sin(yaw)

    def to_world(lx: float, ly: float, lz: float) -> np.ndarray:
        return origin + np.array([lx * ca - ly * sa, lx * sa + ly * ca, lz], dtype=np.float64)

    angs = np.linspace(math.radians(-64.0), math.radians(64.0), 22)
    # Softly rounded crescent ends (organic tender roasted squash, not sharp triangles!)
    end_round = np.sin(np.linspace(0.0, math.pi, len(angs))) ** 0.35
    r_in_curve = r_inner + (r_outer - r_inner) * 0.24 * (1.0 - end_round)

    outer_bot = np.array([to_world(r_outer * math.cos(a) - 0.022, r_outer * math.sin(a), 0.0) for a in angs])
    outer_top = np.array([to_world(r_outer * math.cos(a) - 0.022, r_outer * math.sin(a), thick * (0.86 + 0.14 * er)) for a, er in zip(angs, end_round)])
    inner_bot = np.array([to_world(ri * math.cos(a) - 0.017, ri * math.sin(a), 0.0) for a, ri in zip(angs[::-1], r_in_curve[::-1])])
    inner_top = np.array([to_world(ri * math.cos(a) - 0.017, ri * math.sin(a), thick * (0.78 + 0.16 * er)) for a, ri, er in zip(angs[::-1], r_in_curve[::-1], end_round[::-1])])

    r_rind = r_outer - 0.0048
    rind_top = np.array([to_world(r_rind * math.cos(a) - 0.022, r_rind * math.sin(a), thick * (0.88 + 0.12 * er)) for a, er in zip(angs, end_round)])

    def p2d(arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        u, v, zc = cam.project_points(arr)
        return np.column_stack([u, v]), zc

    ob_2d, _ = p2d(outer_bot)
    ot_2d, ot_z = p2d(outer_top)
    ib_2d, _ = p2d(inner_bot)
    it_2d, it_z = p2d(inner_top)
    rt_2d, _ = p2d(rind_top)

    # 1. Outer dark forest-jade skin wall (visible on back-right curve)
    outer_wall = np.vstack([ot_2d, ob_2d[::-1]])
    layer.fill_poly_linear(
        outer_wall,
        (float(ot_2d[0, 0]), float(ot_2d[0, 1])), (float(ot_2d[-1, 0]), float(ot_2d[-1, 1])),
        [(0.0, (0.14, 0.24, 0.13, 1.0)), (0.52, (0.24, 0.37, 0.20, 1.0)), (1.0, (0.17, 0.28, 0.15, 1.0))],
    )

    # 2. Inner cut concave side wall (warm caramelized honey-amber shadow!)
    inner_wall = np.vstack([it_2d, ib_2d[::-1]])
    layer.fill_poly_linear(
        inner_wall,
        (float(it_2d[0, 0]), float(it_2d[0, 1])), (float(it_2d[-1, 0]), float(it_2d[-1, 1])),
        [
            (0.00, (0.66, 0.36, 0.12, 1.0)),
            (0.42, (0.82, 0.49, 0.17, 1.0)),
            (0.78, (0.76, 0.44, 0.15, 1.0)),
            (1.00, (0.58, 0.31, 0.10, 1.0)),
        ],
    )

    # 3. Top lush saffron-gold roasted squash flesh surface
    top_flesh = np.vstack([rt_2d, it_2d])
    u_tl, v_tl = float(np.min(top_flesh[:, 0])), float(np.max(top_flesh[:, 1]))
    u_tr, v_tr = float(np.max(top_flesh[:, 0])), float(np.min(top_flesh[:, 1]))
    layer.fill_poly_linear(
        top_flesh,
        (u_tl, v_tl), (u_tr, v_tr),
        [
            (0.00, (0.82, 0.49, 0.16, 1.0)),
            (0.38, (0.93, 0.63, 0.21, 1.0)),
            (0.78, (0.97, 0.75, 0.30, 1.0)),
            (1.00, (0.99, 0.84, 0.46, 1.0)),
        ],
    )

    # Subtle toasted caramelized roast mark near the inner bevel edge
    roast_pts = it_2d[5:16] + np.array([1.5, -2.5])
    layer.stroke_catmull_rom(roast_pts, it_z[0], 3.8, (0.64, 0.31, 0.10, 0.36), seed=seed + 9, taper_ends=0.45, tremor=0.35)

    # 4. Dark mottled forest-green kabocha skin rim strip along outer top arc
    top_rind = np.vstack([ot_2d, rt_2d[::-1]])
    layer.fill_poly(top_rind, (0.19, 0.33, 0.17, 1.0))
    # Characteristic pale sage kabocha skin fleck accent
    layer.stroke_catmull_rom(ot_2d[6:15], ot_z[0], 1.8, (0.48, 0.62, 0.39, 0.45), seed=seed + 8, taper_ends=0.45, tremor=0.20)

    # Glossy mirin-soy glaze highlight curve across the golden top face (classic anime gleam!)
    mid_top = to_world((r_rind + r_inner) * 0.45 - 0.019, 0.001, thick)
    mu, mv, mz = cam.project_points(mid_top)
    glaze_pts = np.array([[mu - 14.0, mv - 2.0], [mu - 1.0, mv - 5.5], [mu + 12.0, mv - 1.5]])
    layer.stroke_catmull_rom(glaze_pts, mz, 3.8, (1.0, 0.96, 0.78, 0.82), seed=seed + 1, taper_ends=0.42, tremor=0.18)
    cv2.circle(glints, (int(mu), int(mv - 4)), 4, 0.68, -1, cv2.LINE_AA)

    ink = (0.23, 0.13, 0.08, 0.84)
    top_all = np.vstack([ot_2d, it_2d])
    layer.stroke_catmull_rom(top_all, ot_z[0], 1.70, ink, seed=seed + 2, closed=True, tremor=0.20)
    layer.stroke_catmull_rom(ib_2d, it_z[0], 1.50, ink, seed=seed + 3, tremor=0.18)
    layer.stroke_catmull_rom(ob_2d, ot_z[0], 1.45, ink, seed=seed + 4, tremor=0.18)


def _draw_steamed_rice_mound(
    layer: CairoLayer2x,
    cam: Camera3D,
    glints: np.ndarray,
    center: np.ndarray,
    seed: int = 743,
) -> None:
    """Neat compact mound of glistening steamed short-grain rice:
    scalloped organic grain-bumped perimeter, clean warm-pearl cel shading with
    soft lavender-taupe lower shadow band (zero polka-dot speckles!), crisp pearl
    grain specular glints, and roasted black sesame seeds (`gomashio`)."""
    rng = np.random.default_rng(seed)
    ctx = layer.ctx
    rx, ry, rz = 0.033, 0.025, 0.022

    # Build a true scalloped organic grain-bumped 2D dome silhouette!
    u_c, v_c, z_c = cam.project_points(center + np.array([0.0, 0.0, rz * 0.45]))
    u_l, v_l, _ = cam.project_points(center + np.array([-rx, 0.0, 0.002]))
    u_r, v_r, _ = cam.project_points(center + np.array([rx, 0.0, 0.002]))
    u_top, v_top, _ = cam.project_points(center + np.array([0.004, 0.002, rz]))
    u_bot, v_bot, _ = cam.project_points(center + np.array([0.0, -ry, 0.001]))

    rx_px = abs(u_r - u_l) * 0.52
    ry_top = abs(v_c - v_top) * 1.32
    ry_bot = abs(v_bot - v_c) * 1.06

    # Scalloped rice-grain silhouette polygon (64 points with delicate plump rice-grain bumps)
    ths = np.linspace(0.0, 2.0 * math.pi, 64, endpoint=False)
    sil_pts = []
    for th in ths:
        sy = math.sin(th)
        ry_loc = ry_top if sy < 0.0 else ry_bot
        grain_scallop = 1.0 + 0.034 * abs(math.sin(11.0 * th + 0.4)) + 0.020 * math.cos(17.0 * th)
        px = u_c + rx_px * math.cos(th) * grain_scallop
        py = v_c + ry_loc * sy * grain_scallop
        sil_pts.append([px, py])
    sil_arr = np.array(sil_pts)

    # 1. Clean warm-pearl cel-shaded base dome with sculpted lower-left shadow crescent
    layer.fill_poly_radial(
        sil_arr,
        (u_top + 12.0, v_top + 6.0, 4.0),
        (u_c - 12.0, v_c + 14.0, rx_px * 1.38),
        [
            (0.00, (1.00, 0.98, 0.94, 1.0)),  # luminous sunlit pearl crown
            (0.42, (0.96, 0.94, 0.89, 1.0)),
            (0.72, (0.85, 0.81, 0.76, 1.0)),  # warm-cool cel shadow crescent
            (1.00, (0.74, 0.69, 0.65, 1.0)),  # grounded shaded lower-left base
        ],
    )

    # 2. Delicate overlapping translucent individual rice grains (warm cream on lit crown,
    #    soft warm-ivory on midtone — subtle texture without dark dots!)
    grains = []
    for _ in range(95):
        u_s = float(rng.uniform(-0.92, 0.92))
        v_s = float(rng.uniform(-0.88, 0.88))
        if u_s * u_s + v_s * v_s > 0.86:
            continue
        sy = v_s
        ry_loc = ry_top if sy < 0.0 else ry_bot
        gx = u_c + rx_px * u_s * 0.94
        gy = v_c + ry_loc * sy * 0.92
        # Smooth Lambertian lighting matching upper-right sun
        lit = float(np.clip(0.55 + 0.42 * u_s - 0.45 * v_s, 0.0, 1.0))
        grains.append((gy, gx, lit, float(rng.uniform(0.0, math.pi))))
    grains.sort(key=lambda g: g[0])

    for gy, gx, lit, ang in grains:
        c_sh = hex_rgb("#DED7CC")
        c_lt = hex_rgb("#FFFEFA")
        col = c_sh * (1.0 - lit) + c_lt * lit
        ctx.save()
        ctx.translate(gx, gy)
        ctx.rotate(ang)
        ctx.scale(1.65, 0.90)
        ctx.arc(0.0, 0.0, float(rng.uniform(2.8, 3.8)), 0.0, 2.0 * math.pi)
        ctx.restore()
        ctx.set_source_rgba(float(col[0]), float(col[1]), float(col[2]), 0.72)
        ctx.fill()

        # Whisper-delicate grain boundary arc (barely darker ivory, never dark gray!)
        ctx.save()
        ctx.translate(gx - 0.4, gy + 0.7)
        ctx.rotate(ang)
        ctx.scale(1.6, 0.88)
        ctx.arc(0.0, 0.0, 3.0, 0.25, 2.75)
        ctx.restore()
        ctx.set_source_rgba(0.68, 0.63, 0.58, 0.22)
        ctx.set_line_width(0.65)
        ctx.stroke()

        # Tiny bright wet steamed-rice sparkle on sunlit crown grains
        if lit > 0.78 and rng.uniform(0.0, 1.0) > 0.42:
            ctx.arc(gx + 0.8, gy - 0.8, 1.15, 0.0, 2.0 * math.pi)
            ctx.set_source_rgba(1.0, 1.0, 0.98, 0.90)
            ctx.fill()
            cv2.circle(glints, (int(gx), int(gy)), 2, 0.36, -1, cv2.LINE_AA)

    # 3. Crisp roasted black sesame seeds (`gomashio`) scattered naturally across crown
    sesame_offsets = [
        (-0.34, -0.46), (-0.12, -0.58), (0.16, -0.52), (0.38, -0.36),
        (-0.42, -0.18), (-0.18, -0.26), (0.08, -0.22), (0.30, -0.10),
        (-0.04, -0.40), (0.24, -0.34), (-0.28, -0.02), (0.14, 0.06),
    ]
    for u_s, v_s in sesame_offsets:
        sx_px = u_c + rx_px * u_s * 0.84
        sy_px = v_c + ry_top * v_s * 0.84
        ang = float(rng.uniform(0.0, math.pi))
        ctx.save()
        ctx.translate(sx_px, sy_px)
        ctx.rotate(ang)
        ctx.scale(1.80, 0.88)
        ctx.arc(0.0, 0.0, 1.50, 0.0, 2.0 * math.pi)
        ctx.restore()
        ctx.set_source_rgba(0.15, 0.12, 0.10, 0.92)
        ctx.fill()
        ctx.arc(sx_px + 0.5, sy_px - 0.5, 0.55, 0.0, 2.0 * math.pi)
        ctx.set_source_rgba(0.95, 0.90, 0.80, 0.55)
        ctx.fill()

    # Soft delicate warm-taupe cel outline hugging scalloped rice silhouette
    layer.stroke_catmull_rom(sil_arr, z_c, 1.35, (0.36, 0.30, 0.26, 0.54), seed=seed + 5, closed=True, tremor=0.28)


def _draw_hashioki_and_chopsticks(layer: CairoLayer2x, cam: Camera3D, glints: np.ndarray) -> None:
    """Organic handmade terracotta-clay chopstick rest (`hashioki`) and two tapered
    walnut/cedar chopsticks resting horizontally side-by-side across its saddle."""
    hx, hy = HASHIOKI_CENTER[0], HASHIOKI_CENTER[1]
    ink = (0.15, 0.10, 0.08, 0.88)

    # 1. Sculpted rounded terracotta clay pebble-bar hashioki (#BA6348 family!)
    th = np.linspace(0.0, 2.0 * math.pi, 48, endpoint=False)
    # Softly rounded pill shape (superellipse n=3.2) with gentle concave saddle on top
    rx_h, ry_h = 0.023, 0.011
    cx_p = np.sign(np.cos(th)) * (np.abs(np.cos(th)) ** 0.68) * rx_h
    cy_p = np.sign(np.sin(th)) * (np.abs(np.sin(th)) ** 0.68) * ry_h
    z_saddle = 0.0145 - 0.0030 * np.exp(-((cx_p / 0.011) ** 2))

    top_3d = np.column_stack([hx + cx_p * 0.92, hy + cy_p * 0.88, z_saddle])
    mid_3d = np.column_stack([hx + cx_p, hy + cy_p, z_saddle * 0.52])
    bot_3d = np.column_stack([hx + cx_p * 0.96, hy + cy_p * 0.94, np.zeros_like(th)])

    tu, tv, tz = cam.project_points(top_3d)
    mu, mv, _ = cam.project_points(mid_3d)
    bu, bv, _ = cam.project_points(bot_3d)
    top_2d = np.column_stack([tu, tv])
    mid_2d = np.column_stack([mu, mv])
    bot_2d = np.column_stack([bu, bv])

    body_hull = cv2.convexHull(np.vstack([top_2d, mid_2d, bot_2d]).astype(np.float32)).reshape(-1, 2)
    u_hl, v_hl = float(np.min(body_hull[:, 0])), float(np.max(body_hull[:, 1]))
    u_hr, v_hr = float(np.max(body_hull[:, 0])), float(np.min(body_hull[:, 1]))

    layer.fill_poly_linear(
        body_hull,
        (u_hl, v_hl), (u_hr, v_hr),
        [
            (0.00, (0.45, 0.22, 0.16, 1.0)),  # deep terracotta shade
            (0.45, (0.62, 0.33, 0.23, 1.0)),
            (1.00, (0.78, 0.44, 0.32, 1.0)),
        ],
    )
    layer.fill_poly_linear(
        top_2d,
        (u_hl, v_hl), (u_hr, v_hr),
        [
            (0.00, (0.68, 0.37, 0.27, 1.0)),
            (0.55, (0.77, 0.44, 0.32, 1.0)),  # canonical clay #BA6348 sunlit
            (1.00, (0.88, 0.56, 0.41, 1.0)),
        ],
    )
    # Soft sunlit ceramic rim gleam along back-right crest of hashioki
    top_back = extract_front_or_back_arc(top_2d, want_front=False)
    layer.stroke_catmull_rom(top_back[len(top_back) // 3 :], tz[0], 2.0, (0.96, 0.78, 0.65, 0.55), seed=764, taper_ends=0.4)
    layer.stroke_catmull_rom(body_hull, tz[0], 1.7, ink, seed=762, closed=True, tremor=0.18)
    layer.stroke_catmull_rom(top_2d, tz[0], 1.2, (0.38, 0.19, 0.13, 0.55), seed=763, closed=True, tremor=0.16)

    # 2. Two finely tapered walnut/cedar wooden chopsticks resting horizontally across saddle
    segs = get_chopstick_segments_3d()
    for idx, (p_tip, p_end) in enumerate(reversed(segs)):
        n_steps = 24
        ts = np.linspace(0.0, 1.0, n_steps)
        centerline = p_tip[None, :] * (1.0 - ts[:, None]) + p_end[None, :] * ts[:, None]
        rads = 0.0015 + (0.0044 - 0.0015) * (ts ** 0.85)

        vec = p_end - p_tip
        vec /= np.linalg.norm(vec)
        side_xy = np.array([-vec[1], vec[0], 0.0])
        side_xy /= np.linalg.norm(side_xy)
        up_z = np.array([0.0, 0.0, 1.0])

        top_back = centerline + side_xy[None, :] * rads[:, None] + up_z[None, :] * rads[:, None]
        top_front = centerline - side_xy[None, :] * rads[:, None] + up_z[None, :] * rads[:, None]
        bot_front = centerline - side_xy[None, :] * rads[:, None] - up_z[None, :] * rads[:, None]

        tbu, tbv, tbz = cam.project_points(top_back)
        tfu, tfv, tfz = cam.project_points(top_front)
        bfu, bfv, _ = cam.project_points(bot_front)

        tb_2d = np.column_stack([tbu, tbv])
        tf_2d = np.column_stack([tfu, tfv])
        bf_2d = np.column_stack([bfu, bfv])

        # Shaded vertical front wood face (subtle natural cedar eating tip -> dark walnut shaft!)
        front_face = np.vstack([tf_2d, bf_2d[::-1]])
        layer.fill_poly_linear(
            front_face,
            (float(tfu[0]), float(tfv[0])), (float(tfu[-1]), float(tfv[-1])),
            [
                (0.00, (0.38, 0.25, 0.16, 1.0)),  # slightly lighter raw cedar eating tips
                (0.24, (0.24, 0.15, 0.10, 1.0)),
                (1.00, (0.19, 0.11, 0.07, 1.0)),
            ],
        )

        # Sunlit top bevel catching warm afternoon sunlight
        top_face = np.vstack([tb_2d, tf_2d[::-1]])
        layer.fill_poly_linear(
            top_face,
            (float(tbu[0]), float(tbv[0])), (float(tbu[-1]), float(tbv[-1])),
            [
                (0.00, (0.64, 0.45, 0.30, 1.0)),
                (0.25, (0.50, 0.32, 0.21, 1.0)),
                (0.75, (0.43, 0.27, 0.17, 1.0)),
                (1.00, (0.55, 0.36, 0.23, 1.0)),
            ],
        )

        # Crisp oiled-wood highlight line along sunlit upper ridge
        layer.stroke_catmull_rom(
            (tb_2d + tf_2d) * 0.5, tbz, 1.75, (0.96, 0.84, 0.66, 0.58),
            seed=768 + idx * 5, taper_ends=0.22, tremor=0.10,
        )
        cv2.circle(glints, (int(tbu[15]), int(tbv[15])), 3, 0.42, -1, cv2.LINE_AA)

        full_outline = np.vstack([tb_2d, bf_2d[::-1]])
        layer.stroke_catmull_rom(full_outline, tfz[0], 1.70, ink, seed=770 + idx * 5, closed=True, tremor=0.16)


# ---------------------------------------------------------------------------
# 13. Band 5: Volumetric Diagonal Sunbeam, Dust Motes & Foreground Disc Bokeh
# ---------------------------------------------------------------------------

def apply_volumetric_sunbeam_and_dust(
    canvas: np.ndarray, cam: Camera3D, seed: int = 809
) -> np.ndarray:
    """Project bright upper-right window pane openings forward along SUN_DIR to build
    distinct luminous diagonal volumetric sunbeams + floating golden dust motes."""
    beam_acc = np.zeros((HEIGHT, WIDTH), dtype=np.float32)

    x_spans = [
        (WIN_X0 + 0.03, WIN_V_MULLIONS[0] - 0.03),
        (WIN_V_MULLIONS[0] + 0.03, WIN_V_MULLIONS[1] - 0.03),
        (WIN_V_MULLIONS[1] + 0.03, WIN_V_MULLIONS[2] - 0.03),
        (WIN_V_MULLIONS[2] + 0.03, WIN_V_MULLIONS[3] - 0.03),
    ]
    z_spans = [
        (WIN_H_MULLIONS[0] + 0.03, WIN_H_MULLIONS[1] - 0.03),
        (WIN_H_MULLIONS[1] + 0.03, WIN_H_MULLIONS[2] - 0.03),
    ]

    for bx0, bx1 in x_spans:
        for bz0, bz1 in z_spans:
            p_win = np.array([
                [bx0, Y_BACK_WALL, bz0],
                [bx1, Y_BACK_WALL, bz0],
                [bx1, Y_BACK_WALL, bz1],
                [bx0, Y_BACK_WALL, bz1],
            ], dtype=np.float64)
            p_far = p_win + 2.45 * SUN_DIR[None, :]
            all_3d = np.vstack([p_win, p_far])
            u, v, zc = cam.project_points(all_3d)
            valid = zc > 0.15
            if np.count_nonzero(valid) < 4:
                continue
            pts_2d = np.column_stack([u[valid], v[valid]]).astype(np.float32)
            hull = cv2.convexHull(pts_2d).astype(np.int32)
            tmp = np.zeros((HEIGHT, WIDTH), dtype=np.float32)
            cv2.fillConvexPoly(tmp, hull, 1.0, cv2.LINE_AA)
            # Separate pane shafts softly before summing so distinct light ribbons read!
            beam_acc += cv2.GaussianBlur(tmp, (0, 0), 22.0) * 0.25

    beam_soft = np.clip(beam_acc, 0.0, 1.0)

    # Sculpt subtle parallel diagonal light-ray ribbons strictly aligned to the 2D screen
    # projection of SUN_DIR (upper-right window panes streaming diagonally down-left!)
    p_orig = np.array([0.65, Y_BACK_WALL, 0.72])
    p_step = p_orig + SUN_DIR * 1.2
    u_a, v_a, _ = cam.project_points(p_orig)
    u_b, v_b, _ = cam.project_points(p_step)
    ray_2d = np.array([u_b - u_a, v_b - v_a], dtype=np.float32)
    ray_2d /= max(float(np.linalg.norm(ray_2d)), 1e-6)
    perp_2d = np.array([-ray_2d[1], ray_2d[0]], dtype=np.float32)

    yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
    s_perp = (xx * perp_2d[0] + yy * perp_2d[1]) / 135.0
    shaft_rays = 0.64 + 0.36 * (
        0.55 * np.sin(s_perp * 2.1 + 0.4)
        + 0.30 * np.sin(s_perp * 4.7 + 1.8)
        + 0.15 * np.cos(s_perp * 8.3)
    )
    shaft_rays = np.clip(shaft_rays, 0.28, 1.0)

    # Stronger glowing haze near upper-right window, tapering delicately across room air
    dist_fade = smoothstep(0.08, 0.88, (xx / WIDTH) * 0.58 + (1.0 - yy / HEIGHT) * 0.62)
    beam_mask = np.clip(beam_soft * shaft_rays * (0.35 + 0.65 * dist_fade), 0.0, 1.0)

    beam_tint = hex_rgb("#FFE5B4")
    out = screen_blend(canvas, beam_tint[None, None, :] * beam_mask[:, :, None], strength=0.26)

    # Luminous floating dust motes strictly inside the diagonal sunlit air beam
    rng = np.random.default_rng(seed)
    dust_rgb = np.zeros((HEIGHT, WIDTH, 3), dtype=np.float32)
    dust_col = hex_rgb("#FFF5D8")
    placed = 0
    for _ in range(1100):
        if placed >= 115:
            break
        px = int(rng.integers(int(WIDTH * 0.12), int(WIDTH * 0.96)))
        py = int(rng.integers(int(HEIGHT * 0.05), int(HEIGHT * 0.76)))
        bval = float(beam_mask[py, px])
        if bval < 0.15 or rng.uniform(0.0, 1.0) > bval * 1.45:
            continue
        placed += 1
        rad = int(rng.choice([1, 1, 2, 2, 3]))
        inten = float(rng.uniform(0.28, 0.82)) * min(1.0, bval * 2.3)
        cv2.circle(
            dust_rgb,
            (px, py),
            rad,
            (float(dust_col[0] * inten), float(dust_col[1] * inten), float(dust_col[2] * inten)),
            -1,
            cv2.LINE_AA,
        )
    dust_rgb = cv2.GaussianBlur(dust_rgb, (0, 0), 1.3)
    out = screen_blend(out, dust_rgb, strength=0.88)
    return out


def make_disc_kernel(radius: float) -> np.ndarray:
    """Normalized circular iris bokeh PSF kernel with a subtle spherical-aberration rim."""
    rad = max(1, int(round(float(radius))))
    ky, kx = np.mgrid[-rad : rad + 1, -rad : rad + 1].astype(np.float32)
    kr = np.sqrt(kx * kx + ky * ky) / max(float(radius), 1.0)
    rim = 0.86 + 0.24 * np.exp(-((kr - 0.84) ** 2) / 0.016)
    disc = np.clip((1.04 - kr) / 0.16, 0.0, 1.0) * rim
    return (disc / max(float(np.sum(disc)), 1e-6)).astype(np.float32)


def composite_foreground_disc_bokeh(canvas: np.ndarray) -> np.ndarray:
    """Frame the extreme bottom-right foreground corner with the softly blurred
    curved dark-walnut top rail of a pushed-back wooden dining chair, convolved in
    premultiplied RGBA with make_disc_kernel + ~1 px opposite R/B lateral shift."""
    fg_layer = CairoLayer2x()
    ctx = fg_layer.ctx

    ctx.new_path()
    ctx.move_to(WIDTH * 0.76, HEIGHT * 1.04)
    ctx.curve_to(WIDTH * 0.78, HEIGHT * 0.86, WIDTH * 0.85, HEIGHT * 0.76, WIDTH * 1.04, HEIGHT * 0.72)
    ctx.line_to(WIDTH * 1.04, HEIGHT * 1.04)
    ctx.close_path()
    pat = cairo.LinearGradient(WIDTH * 0.79, HEIGHT * 0.74, WIDTH * 0.96, HEIGHT * 1.00)
    pat.add_color_stop_rgba(0.00, 0.36, 0.25, 0.17, 1.0)  # warm sunlit top-edge rim catch
    pat.add_color_stop_rgba(0.14, 0.15, 0.10, 0.08, 1.0)
    pat.add_color_stop_rgba(1.00, 0.08, 0.06, 0.05, 1.0)
    ctx.set_source(pat)
    ctx.fill()

    ctx.set_operator(cairo.OPERATOR_CLEAR)
    ctx.new_path()
    ctx.move_to(WIDTH * 0.85, HEIGHT * 1.03)
    ctx.curve_to(WIDTH * 0.86, HEIGHT * 0.92, WIDTH * 0.90, HEIGHT * 0.86, WIDTH * 0.97, HEIGHT * 0.84)
    ctx.line_to(WIDTH * 0.96, HEIGHT * 1.03)
    ctx.close_path()
    ctx.fill()
    ctx.set_operator(cairo.OPERATOR_OVER)

    ctx.new_path()
    ctx.move_to(WIDTH * 0.915, HEIGHT * 0.82)
    ctx.line_to(WIDTH * 0.902, HEIGHT * 1.04)
    ctx.set_source_rgba(0.13, 0.09, 0.07, 1.0)
    ctx.set_line_width(18.0)
    ctx.stroke()

    fg_rgb, fg_a = fg_layer.finish()

    kernel = make_disc_kernel(radius=8.4)
    premul = np.empty((HEIGHT, WIDTH, 4), dtype=np.float32)
    premul[:, :, :3] = fg_rgb * fg_a[:, :, None]
    premul[:, :, 3] = fg_a

    blurred = np.empty_like(premul)
    for c in range(4):
        blurred[:, :, c] = cv2.filter2D(premul[:, :, c], -1, kernel, borderType=cv2.BORDER_CONSTANT)

    m_red = np.array([[1.0, 0.0, 1.05], [0.0, 1.0, -0.35]], dtype=np.float32)
    m_blue = np.array([[1.0, 0.0, -1.05], [0.0, 1.0, 0.35]], dtype=np.float32)
    blurred[:, :, 0] = cv2.warpAffine(blurred[:, :, 0], m_red, (WIDTH, HEIGHT), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
    blurred[:, :, 2] = cv2.warpAffine(blurred[:, :, 2], m_blue, (WIDTH, HEIGHT), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

    out_a = np.clip(blurred[:, :, 3], 0.0, 1.0)[:, :, None]
    out = canvas * (1.0 - out_a) + np.clip(blurred[:, :, :3], 0.0, 1.0)
    return np.clip(out, 0.0, 1.0)


# ---------------------------------------------------------------------------
# 14. Band 6: 35mm Film Optics & Restrained Analog Transfer Finish (float32)
# ---------------------------------------------------------------------------

def finish_35mm_optics(rgb: np.ndarray, specular_glints: np.ndarray, seed: int = 909) -> np.ndarray:
    """Float32 35mm cinema film optics + subtle analog transfer patina:
    1) 3-scale warm highlight halation (sigma = 6.5, 24, 72 px)
    2) Radial corner chromatic aberration + gentle optical vignette
    3) Linear shadow black lift + C1-continuous tanh highlight shoulder (knee=0.80, ceiling=0.965)
    4) Luminance-weighted silver-halide grain
    5) Faint BORDER_REFLECT_101 horizontal YIQ chroma softening, sub-pixel jitter, <=0.8% scanlines
    """
    img = np.clip(rgb.astype(np.float32), 0.0, 1.0)

    # 1. Three-scale warm highlight halation (sigma = 6.5, 24.0, 72.0 px)
    lum = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    bright = np.clip((lum - 0.72) / 0.28, 0.0, 1.0) ** 1.30
    bright = np.clip(bright + specular_glints * 0.88, 0.0, 1.38)

    hal_tint = np.array([1.00, 0.90, 0.74], dtype=np.float32)
    h_src = bright[:, :, None] * hal_tint[None, None, :]
    h1 = cv2.GaussianBlur(h_src, (0, 0), 6.5)
    h2 = cv2.GaussianBlur(h_src, (0, 0), 24.0)
    h3 = cv2.GaussianBlur(h_src, (0, 0), 72.0)
    halation = 0.17 * h1 + 0.16 * h2 + 0.14 * h3
    img = screen_blend(img, halation, strength=1.0)

    # 2. Radial corner chromatic aberration + gentle optical vignette
    yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32)
    nx = (xx - WIDTH * 0.5) / (WIDTH * 0.5)
    ny = (yy - HEIGHT * 0.5) / (HEIGHT * 0.5)
    r2 = nx * nx + ny * ny

    ca_scale = 0.00085
    map_rx = (xx + (xx - WIDTH * 0.5) * r2 * ca_scale).astype(np.float32)
    map_ry = (yy + (yy - HEIGHT * 0.5) * r2 * ca_scale).astype(np.float32)
    map_bx = (xx - (xx - WIDTH * 0.5) * r2 * ca_scale).astype(np.float32)
    map_by = (yy - (yy - HEIGHT * 0.5) * r2 * ca_scale).astype(np.float32)
    img[:, :, 0] = cv2.remap(img[:, :, 0], map_rx, map_ry, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
    img[:, :, 2] = cv2.remap(img[:, :, 2], map_bx, map_by, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)

    vig = 1.0 - 0.155 * np.clip(r2 - 0.16, 0.0, 2.0)
    img *= vig[:, :, None]

    # 3. Linear shadow black lift + C1-continuous tanh highlight shoulder (knee=0.80, ceiling=0.965)
    black_lift = np.array([0.018, 0.016, 0.022], dtype=np.float32)
    img = black_lift[None, None, :] + img * (1.0 - black_lift[None, None, :])
    knee = 0.80
    ceiling = 0.965
    span = ceiling - knee
    above = np.maximum(img - knee, 0.0)
    img = np.where(img > knee, knee + span * np.tanh(above / span), img)

    # 4. Luminance-weighted silver-halide film grain
    rng = np.random.default_rng(seed)
    lum2 = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    env = np.clip(1.12 - 0.95 * (np.clip(lum2, 0.0, 1.0) ** 1.55), 0.12, 1.12)

    g_fine = rng.standard_normal((HEIGHT, WIDTH)).astype(np.float32)
    g_clump = cv2.resize(
        rng.standard_normal((HEIGHT // 2, WIDTH // 2)).astype(np.float32),
        (WIDTH, HEIGHT),
        interpolation=cv2.INTER_LINEAR,
    )
    g_luma = 0.58 * g_fine + 0.42 * g_clump
    g_chroma = cv2.resize(
        rng.standard_normal((HEIGHT // 2, WIDTH // 2, 3)).astype(np.float32),
        (WIDTH, HEIGHT),
        interpolation=cv2.INTER_LINEAR,
    )
    img += (0.0150 * g_luma[:, :, None] + 0.0042 * g_chroma) * env[:, :, None]
    img = np.clip(img, 0.0, 1.0)

    # 5. Faint analog transfer patina: BORDER_REFLECT_101 horizontal YIQ chroma softening,
    #    sub-pixel per-line jitter, and <= 0.65% scanline modulation
    r_ch, g_ch, b_ch = img[:, :, 0], img[:, :, 1], img[:, :, 2]
    y_ch = 0.299 * r_ch + 0.587 * g_ch + 0.114 * b_ch
    i_ch = 0.596 * r_ch - 0.274 * g_ch - 0.322 * b_ch
    q_ch = 0.211 * r_ch - 0.523 * g_ch + 0.312 * b_ch

    i_soft = cv2.GaussianBlur(i_ch, (0, 0), sigmaX=1.05, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    q_soft = cv2.GaussianBlur(q_ch, (0, 0), sigmaX=1.15, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    y_blur = cv2.GaussianBlur(y_ch, (0, 0), sigmaX=0.85, sigmaY=0.05, borderType=cv2.BORDER_REFLECT_101)
    y_out = np.clip(y_ch + 0.07 * (y_ch - y_blur), 0.0, 1.0)

    out = np.empty_like(img)
    out[:, :, 0] = y_out + 0.956 * i_soft + 0.621 * q_soft
    out[:, :, 1] = y_out - 0.272 * i_soft - 0.647 * q_soft
    out[:, :, 2] = y_out - 1.106 * i_soft + 1.703 * q_soft
    out = np.clip(out, 0.0, 1.0)

    row_shift = rng.normal(0.0, 0.072, size=HEIGHT).astype(np.float32)
    row_shift = cv2.GaussianBlur(row_shift[:, None], (1, 5), 0.9)[:, 0]
    map_jx = (xx + row_shift[:, None]).astype(np.float32)
    out = cv2.remap(out, map_jx, yy, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)

    scan = 1.0 - 0.0065 * (0.5 - 0.5 * np.cos(math.pi * yy))
    return np.clip(out * scan[:, :, None], 0.0, 1.0)


# ---------------------------------------------------------------------------
# 15. Full Pipeline Assembly & 1:1 Macro Audit Crops
# ---------------------------------------------------------------------------

def render_scene() -> np.ndarray:
    t0 = time.perf_counter()
    cam = Camera3D(CAM_EYE, CAM_TARGET, CAM_UP, CAM_FOV_DEG, WIDTH, HEIGHT)
    paper_tooth = make_paper_tooth(HEIGHT, WIDTH, seed=707)
    dapple_field = build_window_dapple_field(seed=404)

    # Band 0: Golden-hour sky & depth-layered sunlit courtyard foliage
    exterior = render_exterior_sky_and_trees(cam, paper_tooth)
    canvas = exterior.copy()

    # Band 1: Architectural room shell warped via exact 3x3 plane-basis UV homography
    fog_col = hex_rgb("#F2E5CF")

    fl_rgb, fl_a = paint_floor_uv(dapple_field)
    w_fl_rgb, w_fl_a, _ = cam.warp_plane_panel(
        fl_rgb, fl_a,
        p0=np.array([X_LEFT_WALL, 1.40, Z_FLOOR]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 1.0, 0.0]),
        span_u=2.05 - X_LEFT_WALL,
        span_v=Y_BACK_WALL - 1.40,
        fog_color=fog_col, fog_start=2.0, fog_density=0.05,
    )
    canvas = alpha_composite(canvas, w_fl_rgb, w_fl_a)

    bw_rgb, bw_a = paint_back_wall_and_window_uv()
    w_bw_rgb, w_bw_a, _ = cam.warp_plane_panel(
        bw_rgb, bw_a,
        p0=np.array([X_LEFT_WALL, Y_BACK_WALL, 1.55]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 0.0, -1.0]),
        span_u=2.10 - X_LEFT_WALL,
        span_v=1.55 - Z_FLOOR,
        fog_color=fog_col, fog_start=2.2, fog_density=0.04,
    )
    w_bw_rgb = paint_isotropic_gouache_dabs(
        w_bw_rgb, w_bw_a, paper_tooth, dab_strength=0.026, warm_bounce_in_shadow=0.020, num_dabs=90, tooth_weight=0.013, seed=481
    )
    canvas = alpha_composite(canvas, w_bw_rgb, w_bw_a)

    lw_rgb, lw_a = paint_left_plaster_wall_uv(dapple_field)
    w_lw_rgb, w_lw_a, _ = cam.warp_plane_panel(
        lw_rgb, lw_a,
        p0=np.array([X_LEFT_WALL, 0.0, 1.55]),
        e1=np.array([0.0, 1.0, 0.0]),
        e2=np.array([0.0, 0.0, -1.0]),
        span_u=Y_BACK_WALL,
        span_v=1.55 - Z_FLOOR,
        fog_color=fog_col, fog_start=1.9, fog_density=0.035,
    )
    w_lw_rgb = paint_isotropic_gouache_dabs(
        w_lw_rgb, w_lw_a, paper_tooth, dab_strength=0.028, warm_bounce_in_shadow=0.022, num_dabs=94, tooth_weight=0.014, seed=487
    )
    canvas = alpha_composite(canvas, w_lw_rgb, w_lw_a)

    arch_ink = CairoLayer2x()
    _stroke_architecture_ink(arch_ink, cam)
    ai_rgb, ai_a = arch_ink.finish()
    canvas = alpha_composite(canvas, ai_rgb, ai_a)

    # Band 2: Solid timber tabletop + far vertical wood apron via exact UV homography
    ap_rgb, ap_a = paint_table_apron_uv()
    w_ap_rgb, w_ap_a, _ = cam.warp_plane_panel(
        ap_rgb, ap_a,
        p0=np.array([TABLE_X0, TABLE_Y1, 0.0]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 0.0, -1.0]),
        span_u=TABLE_X1 - TABLE_X0,
        span_v=TABLE_THICK,
        fog_color=fog_col, fog_start=2.0, fog_density=0.04,
    )
    canvas = alpha_composite(canvas, w_ap_rgb, w_ap_a)

    tab_rgb, tab_a = paint_tabletop_uv(dapple_field)
    w_tab_rgb, w_tab_a, _ = cam.warp_plane_panel(
        tab_rgb, tab_a,
        p0=np.array([TABLE_X0, TABLE_Y0, 0.0]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 1.0, 0.0]),
        span_u=TABLE_X1 - TABLE_X0,
        span_v=TABLE_Y1 - TABLE_Y0,
        fog_color=fog_col, fog_start=2.0, fog_density=0.035,
    )
    w_tab_rgb = paint_isotropic_gouache_dabs(
        w_tab_rgb, w_tab_a, paper_tooth, dab_strength=0.030, warm_bounce_in_shadow=0.022, num_dabs=96, tooth_weight=0.015, seed=587
    )
    canvas = alpha_composite(canvas, w_tab_rgb, w_tab_a)

    tab_ink = CairoLayer2x()
    e_l = np.array([TABLE_X0, TABLE_Y1, 0.0])
    e_r = np.array([TABLE_X1, TABLE_Y1, 0.0])
    u_e, v_e, z_e = cam.project_points(np.vstack([e_l, e_r]))
    tab_ink.stroke_catmull_rom(
        np.column_stack([u_e, v_e]), z_e, 1.85, (0.20, 0.14, 0.10, 0.72), seed=593, taper_ends=0.05, tremor=0.18
    )
    ti_rgb, ti_a = tab_ink.finish()
    canvas = alpha_composite(canvas, ti_rgb, ti_a)

    # Band 3: Far & midground tabletop props (teapot, folded linen napkin, teacup + Fresnel tea)
    glints = np.zeros((HEIGHT, WIDTH), dtype=np.float32)

    mid_props = CairoLayer2x()
    gl_pot = draw_teapot(mid_props, cam)
    draw_linen_napkin(mid_props, cam)
    mp_rgb, mp_a = mid_props.finish()
    mp_rgb = paint_isotropic_gouache_dabs(
        mp_rgb, mp_a, paper_tooth, dab_strength=0.028, warm_bounce_in_shadow=0.020, num_dabs=84, seed=635
    )
    canvas = alpha_composite(canvas, mp_rgb, mp_a)
    np.maximum(glints, gl_pot, out=glints)

    canvas, gl_cup = draw_teacup_and_fresnel_tea(canvas, cam, exterior, dapple_field, paper_tooth)
    np.maximum(glints, gl_cup, out=glints)

    # Band 4: Near-midground hero — stoneware plate, untouched food portion, hashioki & chopsticks
    canvas, gl_plate = draw_hero_plate_and_paused_meal(canvas, cam, paper_tooth)
    np.maximum(glints, gl_plate, out=glints)

    # Band 5: Diagonal volumetric sunbeam + dust motes + foreground circular disc bokeh
    canvas = apply_volumetric_sunbeam_and_dust(canvas, cam, seed=809)
    canvas = composite_foreground_disc_bokeh(canvas)

    # Band 6: 35mm cinema film optics & restrained analog transfer patina
    final_rgb = finish_35mm_optics(canvas, glints, seed=909)

    elapsed = time.perf_counter() - t0
    print(f"Rendered {WIDTH}x{HEIGHT} frame in {elapsed:.2f}s")
    return final_rgb


def _stroke_architecture_ink(layer: CairoLayer2x, cam: Camera3D) -> None:
    ink = (0.16, 0.11, 0.08, 0.65)
    segs = [
        (np.array([X_LEFT_WALL, Y_BACK_WALL, -0.35]), np.array([X_LEFT_WALL, Y_BACK_WALL, 1.48])),
        (np.array([WIN_X0, Y_BACK_WALL, WIN_Z0]), np.array([WIN_X0, Y_BACK_WALL, WIN_Z1])),
        (np.array([WIN_X0 - WIN_FRAME_W, Y_BACK_WALL, WIN_Z0]), np.array([WIN_X1, Y_BACK_WALL, WIN_Z0])),
    ]
    for mx in WIN_V_MULLIONS:
        segs.append((np.array([mx - WIN_MULLION_W * 0.5, Y_BACK_WALL, WIN_Z0]), np.array([mx - WIN_MULLION_W * 0.5, Y_BACK_WALL, WIN_Z1])))
        segs.append((np.array([mx + WIN_MULLION_W * 0.5, Y_BACK_WALL, WIN_Z0]), np.array([mx + WIN_MULLION_W * 0.5, Y_BACK_WALL, WIN_Z1])))
    for mz in WIN_H_MULLIONS:
        segs.append((np.array([WIN_X0, Y_BACK_WALL, mz + WIN_MULLION_W * 0.44]), np.array([WIN_X1, Y_BACK_WALL, mz + WIN_MULLION_W * 0.44])))

    for idx, (p0, p1) in enumerate(segs):
        clipped = cam.clip_segment_near(p0, p1, z_min=0.05)
        if clipped is None:
            continue
        q0, q1 = clipped
        pts = np.vstack([q0, (q0 + q1) * 0.5, q1])
        u, v, zc = cam.project_points(pts)
        layer.stroke_catmull_rom(np.column_stack([u, v]), zc, 1.80, ink, seed=491 + idx, taper_ends=0.04, tremor=0.20)


def save_image(rgb_float: np.ndarray, out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    u8 = np.round(np.clip(rgb_float, 0.0, 1.0) * 255.0).astype(np.uint8)
    img = Image.fromarray(u8, mode="RGB")
    ext = out_path.suffix.lower()
    if ext == ".webp":
        img.save(out_path, format="WEBP", quality=90, method=6)
    else:
        img.save(out_path, format="PNG", compress_level=6)


def save_audit_crops(rgb_float: np.ndarray, crops_dir: Path) -> None:
    """Save three 1:1 (600 x 450) actual-pixel audit crops:
    1) Window aperture, exterior foliage & volumetric sunbeam
    2) Complete ceramic plate with untouched food portion, clay hashioki & resting chopsticks
    3) Teacup Fresnel reflection, teapot & sunlit tabletop gouache brushwork
    """
    crops_dir.mkdir(parents=True, exist_ok=True)
    cam = Camera3D(CAM_EYE, CAM_TARGET, CAM_UP, CAM_FOV_DEG, WIDTH, HEIGHT)
    u_plate, v_plate, _ = cam.project_points(PLATE_CENTER)
    u_hash, v_hash, _ = cam.project_points(HASHIOKI_CENTER)
    u_cup, v_cup, _ = cam.project_points(TEACUP_CENTER + np.array([0.0, 0.0, 0.055]))

    cw, ch = 600, 450

    def clamp_box(cx_px: float, cy_px: float) -> tuple[int, int, int, int]:
        x0 = int(np.clip(round(cx_px - cw * 0.5), 0, WIDTH - cw))
        y0 = int(np.clip(round(cy_px - ch * 0.5), 0, HEIGHT - ch))
        return x0, y0, x0 + cw, y0 + ch

    specs = [
        ("crop_1_window_sunbeam.png", clamp_box(WIDTH * 0.65, HEIGHT * 0.25)),
        ("crop_2_plate_chopsticks.png", clamp_box(0.62 * u_plate + 0.38 * u_hash, 0.55 * v_plate + 0.45 * v_hash)),
        ("crop_3_teacup_tabletop.png", clamp_box(u_cup + 10.0, v_cup - 18.0)),
    ]
    for name, (x0, y0, x1, y1) in specs:
        crop = rgb_float[y0:y1, x0:x1]
        save_image(crop, crops_dir / name)
        print(f"Saved 1:1 crop {name}: [{x0}:{x1}, {y0}:{y1}]")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Render a 2048x1152 1990s 35mm cel-and-gouache still of a paused meal."
    )
    parser.add_argument("--out", required=True, help="Output image path (.png or .webp)")
    parser.add_argument(
        "--crops-dir",
        default=None,
        help="Optional directory to export three 1:1 (600x450) audit crops.",
    )
    parser.add_argument(
        "--png-copy",
        default=None,
        help="Optional secondary lossless PNG output path.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    rgb = render_scene()
    out_path = Path(args.out)
    save_image(rgb, out_path)
    print(f"Wrote {out_path}")
    if args.png_copy:
        png_path = Path(args.png_copy)
        save_image(rgb, png_path)
        print(f"Wrote lossless PNG copy {png_path}")
    if args.crops_dir:
        save_audit_crops(rgb, Path(args.crops_dir))


if __name__ == "__main__":
    main()
