# PinturaNo9

the straight edges of 1969, after Pintura No. 9.

Run it with `swift run --package-path Examples Example-Recreations-KazuyaSakai-PinturaNo9`.

```swift
//  Recreation after Kazuya Sakai - Pintura No. 9 (1969, acrylic on canvas),
//  from his years in Mexico, shown in the Central Pavilion of the 60th
//  Venice Biennale in 2024. A homage, not a reproduction, and not affiliated
//  with or endorsed by the artist or his estate.
//  https://www.labiennale.org/en/art/2024/abstractions/kazuya-sakai
//  https://4columns.org/d-souza-aruna/venice-biennale-2024
//
//  An original Ollin interpretation. The parts and their proportions are
//  measured off the Biennale's picture of the painting. How it was painted
//  comes from Sonia Becce's note for the Biennale. He laid several layers of
//  acrylic resin on some sections. He put masking tape over the black and
//  white ones to keep the resin off them. No published account gives the
//  order of the work, so the order shown here is a guess from that note.
//  Nothing was ported: the work is acrylic on canvas.

import Foundation
import Ollin

/// Pintura No. 9 (Kazuya Sakai, Mexico, 1969). **Press** to deal another
/// canvas.
///
/// By the end of the 1960s he had put the brush stroke away. This square
/// canvas is built from straight edges alone. A blue frame runs around a
/// white ground. Inside it stands a shape like a house. It has a lavender
/// outline, a roof of nested stripes around a bare triangle, and a black box
/// cut by a red V. A yellow mast runs down the middle, from the top edge to
/// the foot of the V. Under the house a column of bars rises from the bottom edge.
/// Each bar bends into a slanted band, and the bands lie together like a
/// sheaf. Beside them is a ramp of thin black stripes. Small boxes hang at
/// the corners. Each box is a flat front with one or two slanted faces. The
/// slanted edges are all it takes for flat paint to read as a solid.
///
/// The Biennale's note says how the surface was made. He laid several layers
/// of acrylic resin on some sections. He kept the resin off the black and
/// white ones with masking tape. So the paint is thick in some places and
/// thin in others.
///
/// A lap opens on the finished painting. Then the canvas clears and the work
/// is done again. The black and white go on first, and tape goes over them.
/// The colors follow one coat at a time, and the tape comes off at the end.
/// That order is this sketch's guess. In the picture the frame's blue looks thinner than the roof's. So
/// the frame and the bars at the right edge stop after one coat here, and
/// stay a shade paler.
///
/// Try it: `chevrons` is the stripes on each slope of the roof. `stripes` is
/// the black stripes in the ramp, and `bars` the bars in the column. `depth`
/// is how far the boxes reach back, and at 0 they are flat squares. `coats`
/// is how many coats the thick colors get. The seed deals the proportions,
/// the boxes, and which colors the bands take.
@main
final class PinturaNo9: Sketch {
    /// Stripes on each slope of the roof, between the outline and the bare triangle.
    @Param(1 ... 5, icon: "chevron.up") var chevrons = 3
    /// Black stripes in the ramp under the house.
    @Param(3 ... 18, icon: "line.3.horizontal") var stripes = 11
    /// Bars in the column, each one bending into a slanted band.
    @Param(2 ... 6, icon: "chart.bar") var bars = 4
    /// How far the boxes reach back, as a share of the painting's own. At 0 they are flat.
    @Param(0 ... 2, icon: "cube") var depth = 1.0
    /// Coats of paint the thick colors get. The thin ones always get one.
    @Param(1 ... 4, icon: "paintbrush") var coats = 3
    /// Seconds for one lap: the finished painting, a bare canvas, and the painting again.
    @Param(12 ... 30, icon: "timer") var seconds = 24.0

    override var canvasSize: CanvasSize { .square(1080) }
    override var loopDuration: Double? { seconds }

    // The paints, sampled from the picture of the painting.
    private let ground = Color(hex: 0xECEAE7)
    private let bare = Color(hex: 0xF1EADB)
    private let white = Color(hex: 0xF7F4EF)
    private let black = Color(hex: 0x0A050B)
    private let frameBlue = Color(hex: 0x00168A)
    private let flagBlue = Color(hex: 0x0748C7)
    private let lavender = Color(hex: 0x635BC0)
    private let maroon = Color(hex: 0x720F50)
    private let blue = Color(hex: 0x0424AE)
    private let red = Color(hex: 0xCB0513)
    private let yellow = Color(hex: 0xFBC205)
    private let violet = Color(hex: 0x583B84)
    private let lightBlue = Color(hex: 0x0279D6)
    private let orange = Color(hex: 0xF87E04)
    private let brightRed = Color(hex: 0xDC2315)
    private let darkPurple = Color(hex: 0x1E0E38)
    private let navy = Color(hex: 0x031336)
    private let lemon = Color(hex: 0xFDDB0D)
    private let purple = Color(hex: 0x380E72)
    private let barBlue = Color(hex: 0x02178E)
    private let paleLavender = Color(hex: 0x9277D1)
    private let tape = Color(hex: 0xD9C38F)
    private let tapeShade = Color(hex: 0xCDB47C)

    /// One flat area of paint: a convex outline in canvas points.
    private struct Part {
        var points: [Vector2]
        var paint: Color
        /// Coats this part gets. Black and white get one and then sit under tape.
        var layers: Int
        /// The way the brush travels across it.
        var wipe: Vector2
        /// Its place in the order of work, from 0 to 1.
        var turn = 0.0
    }

    /// One length of masking tape.
    private struct Strip {
        var points: [Vector2]
        var along: Vector2
        var shaded: Bool
        var turn = 0.0
    }

    private struct Plan {
        var colors: [Part] = []
        var masked: [Part] = []
        var tape: [Strip] = []
    }

    private var plan = Plan()
    private var built = ""
    private var dealt = 0

    override func mousePressed() {
        dealt += 1
    }

    // MARK: - The frame

    override func draw() {
        let key = "\(variation)/\(dealt)/\(chevrons)/\(stripes)/\(bars)/\(depth)/\(coats)"
        if key != built {
            plan = deal(seed: variation &+ dealt &* 7919)
            built = key
        }

        let (done, shown) = stage(at: loopProgress(over: seconds))
        background(ground)
        noStroke()

        paintTheColors(done: done)
        paintTheBlackAndWhite(done: done)
        layTheTape(done: done)

        if shown < 1 {
            fill(ground.withAlpha(1 - shown))
            drawRect(0, 0, width, height)
        }
    }

    /// Where the lap is: how much of the work is done (0 to 1) and how much
    /// of it shows. The lap opens on the finished painting, clears to a bare
    /// canvas, and paints it again.
    private func stage(at lap: Double) -> (done: Double, shown: Double) {
        let hold = 0.1, clear = 0.16, finished = 0.92
        if lap < hold { return (1, 1) }
        if lap < clear {
            return (1, 1 - smoothstep(0, 1, (lap - hold) / (clear - hold)))
        }
        return (min(1, (lap - clear) / (finished - clear)), 1)
    }

    // The work has four stretches, given as shares of the whole. They are
    // the black and white, the tape going on, the coats of color, and the
    // tape coming off.
    private static let maskedEnds = 0.1
    private static let tapedEnds = 0.2
    private static let coatsEnd = 0.86

    /// How far a stretch from `a` to `b` has run at `x`, from 0 to 1.
    private static func share(_ x: Double, _ a: Double, _ b: Double) -> Double {
        min(max((x - a) / (b - a), 0), 1)
    }

    /// How far one part's own move has run when its stretch is at `x`. The
    /// parts take turns, each move lasting `length` of the stretch.
    private static func move(_ x: Double, turn: Double, length: Double) -> Double {
        share(x, turn * (1 - length), turn * (1 - length) + length)
    }

    /// How much of the ground a coat count hides. The first coat does most of it.
    private func cover(_ count: Int) -> Double {
        func hidden(_ k: Int) -> Double { 1 - 0.12 * pow(0.35, Double(k - 1)) }
        return count < 1 ? 0 : hidden(count) / hidden(max(coats, 1))
    }

    private func paintTheColors(done: Double) {
        // The first pass covers bare canvas and takes longer than the rest.
        let passes = max(coats, 1)
        let first = 1.5
        let x = Self.share(done, Self.tapedEnds, Self.coatsEnd) * (first + Double(passes - 1))
        let pass = x < first ? 0 : min(passes - 1, 1 + Int(x - first))
        let within = x < first ? x / first : min(1, x - first - Double(pass - 1))
        let finished = done >= Self.coatsEnd

        for part in plan.colors {
            let layers = min(part.layers, passes)
            let whole = finished ? layers : min(pass, layers)
            if whole > 0 {
                fill(ground.mixed(with: part.paint, cover(whole)))
                drawPolygon(part.points)
            }
            guard !finished, pass < layers else { continue }
            let brushed = Self.move(within, turn: part.turn, length: 0.25)
            guard brushed > 0 else { continue }
            fill(ground.mixed(with: part.paint, cover(whole + 1)))
            drawShare(of: part.points, along: part.wipe, from: 0, to: brushed)
        }
    }

    private func paintTheBlackAndWhite(done: Double) {
        let x = Self.share(done, 0, Self.maskedEnds)
        for part in plan.masked {
            let brushed = Self.move(x, turn: part.turn, length: 0.3)
            guard brushed > 0 else { continue }
            fill(part.paint)
            drawShare(of: part.points, along: part.wipe, from: 0, to: brushed)
        }
    }

    private func layTheTape(done: Double) {
        guard done > Self.maskedEnds, done < 1 else { return }
        let laying = Self.share(done, Self.maskedEnds, Self.tapedEnds)
        let pulling = Self.share(done, Self.coatsEnd, 1)
        for strip in plan.tape {
            let laid = Self.move(laying, turn: strip.turn, length: 0.2)
            let pulled = Self.move(pulling, turn: strip.turn, length: 0.2)
            guard laid > pulled else { continue }
            fill(strip.shaded ? tapeShade : tape)
            drawShare(of: strip.points, along: strip.along, from: pulled, to: laid)
        }
    }

    /// Draws the part of a convex outline that lies between two shares of
    /// its own extent along a direction. This is a brush or a strip of tape
    /// partway across.
    private func drawShare(of points: [Vector2], along: Vector2, from: Double, to: Double) {
        var low = Double.infinity, high = -Double.infinity
        for p in points {
            low = min(low, p.dot(along))
            high = max(high, p.dot(along))
        }
        var kept = points
        if to < 1 { kept = Self.cut(kept, normal: along, limit: low + (high - low) * to) }
        if from > 0 { kept = Self.cut(kept, normal: along * -1, limit: -(low + (high - low) * from)) }
        if kept.count >= 3 { drawPolygon(kept) }
    }

    /// The part of a convex outline on the near side of a line: the points
    /// `p` with `p . normal <= limit`.
    private static func cut(_ points: [Vector2], normal: Vector2, limit: Double) -> [Vector2] {
        var kept: [Vector2] = []
        for i in points.indices {
            let a = points[i], b = points[(i + 1) % points.count]
            let da = a.dot(normal) - limit, db = b.dot(normal) - limit
            if da <= 0 { kept.append(a) }
            if (da < 0 && db > 0) || (da > 0 && db < 0) {
                kept.append(a + (b - a) * (da / (da - db)))
            }
        }
        return kept
    }

    // MARK: - Dealing the canvas

    /// Lays out every part. The lengths are in hundredths of the side, the
    /// unit the painting was measured in. Everything comes from the seed.
    private func deal(seed: Int) -> Plan {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(seed &* 1_000_003 &+ 1969)))
        func roll() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func roll(_ a: Double, _ b: Double) -> Double { a + (b - a) * roll() }
        func pick<T>(_ items: [T]) -> T { items[min(items.count - 1, Int(roll() * Double(items.count)))] }

        let u = width / 100
        let right = Vector2(1, 0), down = Vector2(0, 1), up = Vector2(0, -1)
        var plan = Plan()

        func rect(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double) -> [Vector2] {
            [Vector2(x0, y0), Vector2(x1, y0), Vector2(x1, y1), Vector2(x0, y1)]
        }
        func lay(_ points: [Vector2], _ paint: Color, layers: Int, wipe: Vector2) {
            guard points.count >= 3 else { return }
            plan.colors.append(Part(points: points.map { $0 * u }, paint: paint, layers: layers, wipe: wipe))
        }
        func layMasked(_ points: [Vector2], _ paint: Color, wipe: Vector2) {
            plan.masked.append(Part(points: points.map { $0 * u }, paint: paint, layers: 1, wipe: wipe))
        }
        func layTape(_ points: [Vector2], along: Vector2) {
            guard points.count >= 3 else { return }
            plan.tape.append(Strip(points: points.map { $0 * u }, along: along, shaded: plan.tape.count % 2 == 1))
        }
        /// A slanted face of a box: the edge from `a` to `b` carried back by `reach`.
        func face(_ a: Vector2, _ b: Vector2, reach: Vector2) -> [Vector2] {
            depth > 0.02 ? [a, b, b + reach * depth, a + reach * depth] : []
        }
        /// Keeps the part of an outline between two heights.
        func between(_ points: [Vector2], _ top: Double, _ bottom: Double) -> [Vector2] {
            Self.cut(Self.cut(points, normal: down, limit: bottom), normal: up, limit: -top)
        }
        func unit(_ v: Vector2) -> Vector2 { v / v.length }
        let thick = coats

        // 1. The measures. The house stands on the middle axis.
        let middle = 50.0
        let half = 36.9 + roll(-2.2, 1.2)
        let eaves = 43.6 + roll(-3, 2.5)
        let floorLine = 71.8 + roll(-2, 1.5)
        let pitch = (51.7 + roll(-4, 3)) * Double.pi / 180
        let rise = tan(pitch)
        let mast = 3.9 + roll(-0.3, 0.4)
        let outline = 3.0
        let wall = outline / sin(pitch)
        let floorBand = 3.2
        let (frameLeft, frameRight, frameTop, frameBottom, frameBand) = (4.8, 94.8, 6.7, 97.4, 4.7)
        let (stackLeft, stackFront, stackSide) = (13.2, 7.8, 3.1)
        /// Where the stack's widest front ends, and how far right a face of it can reach.
        let stackEdge = stackLeft + stackFront + 0.3 + stackSide
        let stackRight = stackLeft + stackFront + 0.4 + stackSide * max(depth, 1)
        let columnTop = 86.8 + roll(-1.5, 1)
        let columnLeft = 35.8 + roll(-1.5, 1.5)
        /// Where the roof's outer line is at a height, on the left slope.
        func roofLeft(_ y: Double) -> Double { min(middle - half + (eaves - y) / rise, middle - mast / 2) }

        // 2. The column: its bars, widest second, as in the painting.
        var barWidths: [Double] = []
        for i in 0 ..< 6 {
            // Six are dealt whatever `bars` is, so changing it moves nothing else.
            let dealtWidth = [4.8, 8.0, 5.0, 5.5][i % 4] * roll(0.9, 1.1) * 4 / Double(max(bars, 4))
            if i < bars { barWidths.append(dealtWidth) }
        }
        let columnRight = columnLeft + barWidths.reduce(0, +)

        // 3. The frame, in the pieces the other parts leave of it. It is thin paint.
        lay(rect(frameLeft, frameTop, frameLeft + frameBand, frameBottom), frameBlue, layers: 1, wipe: down)
        lay(rect(frameLeft + frameBand, frameTop, stackLeft, frameTop + frameBand), frameBlue, layers: 1, wipe: right)
        let (bandTop, bandBottom) = (frameTop, frameTop + frameBand)
        if roofLeft(bandBottom) > stackRight {
            lay([Vector2(stackRight, bandTop), Vector2(max(roofLeft(bandTop), stackRight), bandTop),
                   Vector2(roofLeft(bandBottom), bandBottom), Vector2(stackRight, bandBottom)],
                  frameBlue, layers: 1, wipe: right)
        }
        lay([Vector2(2 * middle - roofLeft(bandTop), bandTop), Vector2(frameRight - frameBand, bandTop),
               Vector2(frameRight - frameBand, bandBottom), Vector2(2 * middle - roofLeft(bandBottom), bandBottom)],
              frameBlue, layers: 1, wipe: right)
        lay(rect(frameRight - frameBand, frameTop, frameRight, frameBottom), frameBlue, layers: 1, wipe: down)
        lay(rect(frameLeft + frameBand, frameBottom - frameBand, columnLeft, frameBottom), frameBlue, layers: 1, wipe: right)
        lay(rect(columnRight, frameBottom - frameBand, frameRight - frameBand, frameBottom), frameBlue, layers: 1, wipe: right)
        let stub = 78.8 + roll(-6, 3)
        lay(rect(frameRight, stub, 100, stub + 6), frameBlue, layers: 1, wipe: right)
        lay([Vector2(frameRight, frameTop), Vector2(100, frameTop), Vector2(frameRight, frameTop + frameBand)],
              flagBlue, layers: thick, wipe: right)

        // 4. The house's outline: two slopes, two walls, and a floor.
        let boxLeft = middle - half + wall, boxRight = middle + half - wall
        let boxTop = eaves + 0.2, boxBottom = floorLine - floorBand
        let mastLeft = middle - mast / 2, mastRight = middle + mast / 2
        /// The roof line pushed in by `inset`, at the mast's left edge.
        func ridge(_ inset: Double) -> Double { eaves - (mastLeft - (middle - half + inset / sin(pitch))) * rise }
        /// A stripe of the left slope between two insets, down to the eaves.
        func slope(_ a: Double, _ b: Double, base: Double) -> [Vector2] {
            let x0 = middle - half + a / sin(pitch) + (eaves - base) / rise
            let x1 = min(middle - half + b / sin(pitch) + (eaves - base) / rise, mastLeft)
            guard x0 < mastLeft else { return [] }
            return [Vector2(x0, base), Vector2(x1, base), Vector2(mastLeft, min(ridge(b), base)), Vector2(mastLeft, ridge(a))]
        }
        func mirrored(_ points: [Vector2]) -> [Vector2] { points.reversed().map { Vector2(2 * middle - $0.x, $0.y) } }
        let alongLeft = Vector2(cos(pitch), -sin(pitch)), alongRight = Vector2(cos(pitch), sin(pitch))
        lay(rect(middle - half, eaves, boxLeft, boxBottom), lavender, layers: 2, wipe: up)
        lay(slope(0, outline, base: eaves), lavender, layers: 2, wipe: alongLeft)
        lay(mirrored(slope(0, outline, base: eaves)), lavender, layers: 2, wipe: alongRight)
        lay(rect(boxRight, eaves, middle + half, boxBottom), lavender, layers: 2, wipe: down)
        lay(rect(middle - half, boxBottom, middle + half, floorLine), lavender, layers: 2, wipe: right)

        // 5. The roof: stripes in from the outline, then the bare triangle.
        let stripeBase = eaves - 0.9
        let room = (half - mast / 2) * sin(pitch) - outline
        let stripe = min(4.3, 0.62 * room / Double(chevrons))
        let roofPaints = [maroon, blue, red]
        var inset = outline
        for i in 0 ..< chevrons {
            let paint = roofPaints[i % 3]
            lay(slope(inset, inset + stripe, base: stripeBase), paint, layers: thick, wipe: alongLeft)
            lay(mirrored(slope(inset, inset + stripe, base: stripeBase)), paint, layers: thick, wipe: alongRight)
            inset += stripe
        }
        let bareLeft = middle - half + inset / sin(pitch) + (eaves - stripeBase) / rise
        let bareHalf = [Vector2(bareLeft, stripeBase), Vector2(mastLeft, stripeBase), Vector2(mastLeft, ridge(inset))]
        lay(bareHalf, bare, layers: 1, wipe: up)
        lay(mirrored(bareHalf), bare, layers: 1, wipe: up)

        // 6. The V in the box, from its top corners to the foot of the mast.
        let arm = 8.8 + roll(-1.2, 1.2)
        let run = arm * (mastLeft - boxLeft) / (boxBottom - boxTop)
        let leftArm = [Vector2(boxLeft, boxTop), Vector2(boxLeft + run, boxTop),
                       Vector2(mastLeft, boxBottom - arm), Vector2(mastLeft, boxBottom)]
        lay(leftArm, red, layers: thick, wipe: unit(Vector2(mastLeft - boxLeft, boxBottom - boxTop)))
        lay(mirrored(leftArm), red, layers: thick, wipe: unit(Vector2(boxLeft - mastLeft, boxBottom - boxTop)))
        lay(rect(mastLeft, 0, mastRight, boxBottom), yellow, layers: thick, wipe: down)

        // 7. The column of bars, and the slanted band each bar bends into.
        // A band is its bar's top edge carried up and to the right, so the
        // sheaf lands on the house's floor.
        let coolPaints = [purple, barBlue, navy, lightBlue]
        let warmFirst = roll() < 0.8
        let lift = columnTop - floorLine
        var x = columnLeft
        let boxFront = columnRight + 4.4
        // The box stands low enough that only the last band runs into it.
        let boxFrontTop = max(floorLine + 4.4 + roll(-1, 1.5), columnTop - 4.2 - (barWidths.last ?? 5))
        for (i, w) in barWidths.enumerated() {
            lay(rect(x, columnTop, x + w, 100), coolPaints[i % 4], layers: thick, wipe: up)
            let isWarm = (i % 2 == 0) == warmFirst
            let paint = isWarm ? red : (i % 4 < 2 ? purple : blue)
            var band = [Vector2(x, columnTop), Vector2(x + w, columnTop), Vector2(x + w + lift, floorLine), Vector2(x + lift, floorLine)]
            // The last band stops at the box that stands in its way: at its
            // top, and at its near side.
            if i == bars - 1 {
                band = Self.cut(between(band, boxFrontTop, columnTop), normal: right, limit: boxFront - 0.2)
            }
            lay(band, paint, layers: thick, wipe: Vector2(1, -1) / 2.0.squareRoot())
            x += w
        }

        // 8. The ramp of stripes beside the sheaf, black on the white ground.
        // It is cut on a slant at the top left and along the sheaf at the bottom.
        let rampLeft = columnLeft - 6.3
        let rampRight = columnLeft + lift - 2.5
        let period = (rampRight - rampLeft) / Double(stripes)
        func rampTop(_ x: Double) -> Double { max(floorLine, floorLine + 5.2 - (x - rampLeft) * 1.4) }
        func rampBottom(_ x: Double) -> Double {
            min(columnLeft + columnTop - x - 1.3, frameBottom - frameBand - 0.6)
        }
        for i in 0 ..< stripes {
            let x0 = rampLeft + Double(i) * period, x1 = x0 + period * 0.36
            guard rampBottom(x1) > rampTop(x1) else { continue }
            layMasked([Vector2(x0, rampTop(x0)), Vector2(x1, rampTop(x1)), Vector2(x1, rampBottom(x1)), Vector2(x0, rampBottom(x0))],
                   black, wipe: down)
        }

        // 9. The black of the box, in the four triangles the V and the mast
        // leave, and the white line under the eaves.
        let blacks = [
            [Vector2(boxLeft, boxTop), Vector2(mastLeft, boxBottom), Vector2(boxLeft, boxBottom)],
            [Vector2(boxLeft + run, boxTop), Vector2(mastLeft, boxTop), Vector2(mastLeft, boxBottom - arm)],
        ]
        for triangle in blacks + blacks.map(mirrored) {
            layMasked(triangle, black, wipe: down)
        }
        // The line starts where the slope's outline ends, so it lies on no paint.
        let lineLeft = boxLeft + (eaves - stripeBase) / rise
        layMasked(rect(lineLeft, stripeBase, mastLeft, eaves + 0.1), white, wipe: right)
        layMasked(rect(mastRight, stripeBase, 2 * middle - lineLeft, eaves + 0.1), white, wipe: right)

        // 10. The tape: lengths side by side over the black triangles, along
        // the ramp, and one over the white line.
        let tapeWidth = 2.6
        for triangle in blacks + blacks.map(mirrored) {
            var y = boxTop
            while y < boxBottom {
                layTape(between(triangle, y, min(y + tapeWidth, boxBottom)), along: right)
                y += tapeWidth
            }
        }
        // Where the ramp's slanted top meets the floor: a strip that spans
        // that corner takes a point there, so no stripe shows above its tape.
        let rampCorner = rampLeft + 5.2 / 1.4
        var tapeX = rampLeft - 0.4
        while tapeX < rampRight {
            let x1 = min(tapeX + tapeWidth, rampRight + 0.2)
            var length = [Vector2(tapeX, rampTop(tapeX) - 0.4)]
            if tapeX < rampCorner, rampCorner < x1 { length.append(Vector2(rampCorner, floorLine - 0.4)) }
            length += [Vector2(x1, rampTop(x1) - 0.4), Vector2(x1, rampBottom(x1) + 0.4), Vector2(tapeX, rampBottom(tapeX) + 0.4)]
            layTape(length, along: down)
            tapeX += tapeWidth
        }
        layTape(rect(lineLeft, stripeBase - 0.5, mastLeft, eaves + 0.6), along: right)
        layTape(rect(mastRight, stripeBase - 0.5, 2 * middle - lineLeft, eaves + 0.6), along: right)

        // 11. The stack of boxes at the top left. Each box is a flat front
        // and one or two slanted faces, and each leans its own way.
        let fronts = [lightBlue, darkPurple, navy, lightBlue, navy]
        let sides = [brightRed, lemon, orange]
        var order = [0, 1, 2]
        if roll() < 0.5 { order.swapAt(0, 2) }
        if roll() < 0.3 { order.swapAt(1, 2) }
        var heights = [roll(5.2, 6.4), roll(7.4, 8.6), roll(4.8, 5.8) + roll(6.4, 7.6)]
        // The stack ends where the roof's slope comes down over it.
        let under = 3.5 * max(depth, 0.15)
        let needed = heights.reduce(0, +) + 0.4 + under + 1.8
        let stackRoom = eaves - (stackLeft + stackFront - (middle - half)) * rise - 2
        let fit = min(1, (stackRoom - 0.4 - under - 1.8) / (needed - 0.4 - under - 1.8))
        heights = heights.map { $0 * fit }
        /// Keeps a part of the stack inside its own strip and clear of the
        /// roof's slope. A part that would cross either is cut flat there.
        func clear(_ points: [Vector2]) -> [Vector2] {
            let kept = Self.cut(points, normal: Vector2(-1, 0), limit: -stackLeft)
            return Self.cut(kept, normal: Vector2(rise, 1), limit: eaves + rise * (middle - half) - 1.5)
        }
        var y = 0.5
        for kind in order {
            let x0 = stackLeft, x1 = stackLeft + stackFront, x2 = stackEdge
            let h = heights[kind]
            switch kind {
            case 0:
                // A front with a side that falls away to the right, cut flat below.
                lay(clear(rect(x0, y, x1, y + h)), pick(fronts), layers: thick, wipe: right)
                let side = face(Vector2(x1 + 0.3, y - 0.3), Vector2(x1 + 0.3, y + h), reach: Vector2(stackSide, 2.4))
                lay(clear(between(side, y - 0.3, y + h)), pick(sides), layers: thick, wipe: down)
                y += h + 0.5
            case 1:
                // A front seen from below: a face on its left and its underside.
                let split = x0 + 4.1
                lay(clear(rect(split, y, x2, y + h)), darkPurple, layers: thick, wipe: right)
                let leftFace = face(Vector2(split - 0.2, y + h + 0.3), Vector2(split - 0.2, y - 4), reach: Vector2(-3.9, 3.5))
                lay(clear(between(leftFace, y, y + h + 0.3 + under)), orange, layers: thick, wipe: down)
                let underside = face(Vector2(x2, y + h + 0.4), Vector2(split - 0.2, y + h + 0.4), reach: Vector2(-3.7, 3.5))
                lay(clear(underside), brightRed, layers: thick, wipe: right)
                y += h + 0.4 + under + 0.5
            default:
                // Two fronts, and the lower one's side rising beside the upper.
                let h0 = h * 0.42, h1 = h * 0.58
                lay(clear(rect(x0, y, x1, y + h0)), lightBlue, layers: thick, wipe: right)
                lay(clear(rect(x0, y + h0 + 0.3, x1, y + h0 + 0.3 + h1)), navy, layers: thick, wipe: right)
                let side = face(Vector2(x1 + 0.4, y + h0 + 0.3 + h1), Vector2(x1 + 0.4, y + h0 - 0.1), reach: Vector2(stackSide - 0.2, -3.3))
                // The side may not rise past the top of its own pair of fronts.
                lay(clear(between(side, y, 100)), lemon, layers: thick, wipe: up)
                y += h + 0.3 + 0.5
            }
        }

        // 12. Two small cubes under the house's left corner, and the box
        // that stops the sheaf: red over orange, with a dark side.
        let cubeLeft = rampLeft - 8.3
        var cubeTop = floorLine
        for paint in [lightBlue, navy] {
            lay(rect(cubeLeft, cubeTop, cubeLeft + 5.6, cubeTop + 4.7), paint, layers: thick, wipe: right)
            let side = face(Vector2(cubeLeft + 5.6, cubeTop + 4.7), Vector2(cubeLeft + 5.6, cubeTop), reach: Vector2(1.2, -0.9))
            lay(between(side, floorLine, 100), navy, layers: thick, wipe: up)
            cubeTop += 5.6
        }
        let boxFrontBottom = boxFrontTop + 6.1
        lay(rect(columnRight, columnTop, boxFront - 0.2, frameBottom - frameBand - 0.3), coolPaints[(bars - 1) % 4],
            layers: thick, wipe: right)
        lay(rect(boxFront, boxFrontTop, boxFront + 4, boxFrontBottom), red, layers: thick, wipe: down)
        lay(rect(boxFront, boxFrontBottom + 0.4, boxFront + 4, frameBottom - frameBand - 0.3), orange, layers: thick, wipe: down)
        let boxSide = face(Vector2(boxFront + 4.2, frameBottom - frameBand - 3.3), Vector2(boxFront + 4.2, boxFrontTop - 0.3),
                           reach: Vector2(3.5, -3.8))
        lay(between(boxSide, floorLine + 0.2, 100), navy, layers: thick, wipe: up)

        // 13. Bars that leave by the right edge. They are thin paint too.
        var barTop = 18.8 + roll(-3, 3)
        for _ in 0 ..< 2 + Int(roll() * 3) {
            lay(rect(frameRight + 0.4, barTop, 100, barTop + 6.2), violet, layers: 1, wipe: right)
            barTop += 12.7
        }

        // 14. The emblem against the frame's right side: the roof again, on
        // its side and small, pointing into two red lobes.
        let (ex1, ey0) = (frameRight - frameBand - 0.2, max(floorLine + 2, 76.7 + roll(-2, 4)))
        let (ew, eh) = (12.5, 10.5)
        let ex0 = ex1 - ew
        lay(rect(ex0, ey0, ex1, ey0 + eh), purple, layers: thick, wipe: right)
        for lobe in 0 ..< 2 {
            let center = Vector2(ex0 + 1.9 + eh / 4, ey0 + eh * (0.25 + 0.5 * Double(lobe)))
            var points: [Vector2] = []
            for k in 0 ... 24 {
                let angle = Double.pi / 2 + Double.pi * Double(k) / 24
                points.append(center + Vector2(cos(angle), sin(angle)) * (eh / 4))
            }
            points.append(Vector2(ex1, center.y - eh / 4))
            points.append(Vector2(ex1, center.y + eh / 4))
            lay(points, red, layers: thick, wipe: right)
        }
        let emblemMiddle = ey0 + eh / 2
        for (paint, reach, spread) in [(paleLavender, 0.73, 0.44), (frameBlue, 0.36, 0.2), (yellow, 0.14, 0.08)] {
            lay([Vector2(ex1 - ew * reach, emblemMiddle), Vector2(ex1, emblemMiddle - eh * spread),
                   Vector2(ex1, emblemMiddle + eh * spread)], paint, layers: thick, wipe: Vector2(-1, 0))
        }

        // 15. The crest on the frame's top band: two triangles and a red V.
        let crest = 2 * middle - roofLeft(frameTop) + 1.5
        if crest + 14.6 < frameRight - frameBand {
            lay([Vector2(crest, frameTop), Vector2(crest + 4, 0.2), Vector2(crest + 9.2, frameTop)], blue, layers: thick, wipe: right)
            lay([Vector2(crest + 5.6, 0), Vector2(crest + 6.6, 0), Vector2(crest + 9.9, frameTop - 0.3), Vector2(crest + 9.3, frameTop - 0.3)],
                  red, layers: thick, wipe: down)
            lay([Vector2(crest + 13.2, 0), Vector2(crest + 14.2, 0.3), Vector2(crest + 10.3, frameTop - 0.3), Vector2(crest + 9.9, frameTop - 0.3)],
                  red, layers: thick, wipe: down)
            lay([Vector2(crest + 10.6, frameTop), Vector2(crest + 14.6, 0.9), Vector2(crest + 14.6, frameTop)], lightBlue, layers: thick, wipe: right)
        }

        // The order of work is the order the parts were laid out in.
        for i in plan.colors.indices { plan.colors[i].turn = Double(i) / Double(plan.colors.count) }
        for i in plan.masked.indices { plan.masked[i].turn = Double(i) / Double(plan.masked.count) }
        for i in plan.tape.indices { plan.tape[i].turn = Double(i) / Double(plan.tape.count) }
        return plan
    }
}
```
