# LaCiudadPerdida

a city of small lit blocks that sinks into its ocher ground and is found again, after Gunther Gerzso's La ciudad perdida (1948).

Run it with `swift run --package-path Examples Example-Recreations-GuntherGerzso-LaCiudadPerdida`.

```swift
//  Recreation after Gunther Gerzso - La ciudad perdida (The Lost City), 1948,
//  oil on hardboard, 55.9 x 71.5 cm, the Art Institute of Chicago, gift of
//  Muriel Kallis Newman. A homage, not a reproduction, and not affiliated
//  with or endorsed by the artist's estate or the museum.
//  https://www.artic.edu/artworks/60257
//  https://bombmagazine.org/articles/gunther-gerzso/
//
//  An original Ollin interpretation, read off the museum's picture of the
//  painting. Its motion takes up a sentence from Gerzso's conversation with
//  José Antonio Aldrete-Haas. Nothing was ported: the work is oil on
//  hardboard.

import Foundation
import Ollin

/// La ciudad perdida (Gunther Gerzso, 1948). An early painting, from before
/// his large planes. A crowd of small blocks stands on a ground of deep
/// ocher. Each block is lit on one side and dark on the other, and many
/// carry one dark window. The blocks gather into quarters. One quarter is
/// raised on thin legs like a tower, and another sits in a shape like a
/// hull. Large pale slabs lie between them like courts. Around every
/// quarter the ground goes nearly black, as if the blocks stood in a pit.
/// Toward the edges of the painting, blocks are only outlines in the ocher.
///
/// No statement of a rule for this painting was found, so the structure is
/// read off pictures of the work. A quarter here grows the way a town
/// does: each new block is set against the side of one already standing.
/// The blocks at a quarter's rim stay in the ground as outlines.
///
/// He described the moment a painting begins to work: "a being that was
/// underwater comes to the surface and slowly comes to life." The cycle
/// takes the title at its word in that spirit. The city stands, the ground
/// takes it back block by block, and it is found again in the order it was
/// built. A pit darkens as its quarter comes up. The losing and the finding
/// are this sketch's own: the painting is still. A vector export draws the
/// city as a plan, every block an outline.
///
/// Try it: `blocks` is how many blocks the city has, and `courts` how many
/// pale courts lie in it. `windows` is the share of blocks with a window.
/// `buried` is the share that stays in the ground, and `grain` how broken
/// the paint is. The seed deals the city, and a press deals the next.
@main
final class LaCiudadPerdida: Sketch {
    /// How many blocks the quarters have between them. Past 320 the blocks
    /// are dealt smaller, so that more of them fit. A quarter that is full
    /// still takes no more, so the city can hold a few fewer than this.
    @Param(60 ... 480, icon: "square.grid.3x3") var blocks = 320
    /// How many pale courts lie among the quarters.
    @Param(0 ... 4, icon: "rectangle") var courts = 3
    /// The share of the blocks that carry a window.
    @Param(0 ... 1, icon: "square.dashed.inset.filled") var windows = 0.6
    /// The share of each quarter, at its rim, that stays in the ground.
    @Param(0 ... 0.6, icon: "square.dashed") var buried = 0.14
    /// How broken and clouded the paint is.
    @Param(0 ... 1, icon: "circle.dotted") var grain = 0.7
    /// One cycle: the city stands, is lost to the ground, and is found.
    @Param(8 ... 30, icon: "clock") var seconds = 24.0

    // The painting is 71.5 by 55.9 centimeters.
    override var canvasSize: CanvasSize { .size(1382, 1080) }
    override var loopDuration: Double? { seconds }

    // MARK: - The parts

    /// One block. It has an outline and two paints, one for its dark side
    /// and one for its lit side. A second color is broken over them, and
    /// `toward` is the way its light falls. It may carry a window. `order`
    /// is its place in the finding, and a buried block is never found.
    private struct Block {
        var outline: [Vector2]
        var base: Color
        var lit: Color
        var second: Color
        var toward: Vector2
        var center: Vector2
        var breadth: Double
        var window: Window?
        var quarter: Int
        var order: Double
        var seed: Double
        var buried = false
    }

    /// A window: a small dark square, sometimes inside a frame of another
    /// color.
    private struct Window {
        var frame: [Vector2]?
        var frameColor: Color
        var pane: [Vector2]
        var paneColor: Color
    }

    /// A thin line drawn over the blocks, such as the two bows across the
    /// tower's sail.
    private struct Mark {
        var points: [Vector2]
        var color: Color
        var order: Double
    }

    /// The pit a quarter stands in: where it is, how far it reaches, how
    /// dark it gets, and which quarter it darkens with.
    private struct Pit {
        var center: Vector2
        var reach: Vector2
        var depth: Double
        var quarter: Int
    }

    private struct City {
        var blocks: [Block] = []
        var marks: [Mark] = []
        var pits: [Pit] = []
    }

    /// An upright box, before it is turned and nudged into a block.
    private struct Box {
        var x: Double
        var y: Double
        var w: Double
        var h: Double
        var midX: Double { x + w / 2 }
        var midY: Double { y + h / 2 }
        func shared(with other: Box) -> Double {
            let across = min(x + w, other.x + other.w) - max(x, other.x)
            let down = min(y + h, other.y + other.h) - max(y, other.y)
            return across > 0 && down > 0 ? across * down : 0
        }
    }

    // The colors, each a dark side and a lit side, matched by eye to the
    // museum's picture.
    private static let ochers: [(UInt32, UInt32)] = [(0x7E5516, 0xD2A03A), (0x8C5E14, 0xDCAE46), (0x704A18, 0xBE8C34),
                                                     (0x86641E, 0xCFAA4C), (0x6A5220, 0xB09440)]
    private static let oranges: [(UInt32, UInt32)] = [(0x86401A, 0xCC7434), (0x904A1C, 0xD68442), (0x7A3216, 0xB85C2C)]
    private static let greens: [(UInt32, UInt32)] = [(0x444E2C, 0x848E52), (0x4E5C3C, 0x94A070), (0x3C4626, 0x727E44)]
    private static let blues: [(UInt32, UInt32)] = [(0x33464A, 0x6A8482), (0x3A5258, 0x7A9892), (0x42566A, 0x7E929E)]
    private static let browns: [(UInt32, UInt32)] = [(0x482C14, 0x7C5026), (0x56361A, 0x8C602C)]
    private static let pales: [(UInt32, UInt32)] = [(0xB89C7A, 0xEEDCBC), (0xC4A690, 0xF2DECA), (0xBCAC86, 0xEADDB6),
                                                    (0xCAB292, 0xF4E6CA)]

    private let soot = Color(hex: 0x1C120C)
    private let umber = Color(hex: 0x3A210C)

    private var city = City()
    private var built = (seed: Int.min, blocks: -1, courts: -1, windows: -1.0, buried: -1.0, width: 0.0, height: 0.0)
    private var pressed = 0

    override func mousePressed() {
        pressed += 1
    }

    // MARK: - Dealing a city

    /// Deal one city. Places are parts of the width and the height until
    /// `at` turns them into pixels, mirrored for half the seeds.
    private func deal(seed: Int) -> City {
        // Every part of the city rolls from a generator of its own, numbered
        // by `stream`. A change of one parameter then leaves the rest of the
        // city where it was.
        func stream(_ number: Int) -> SplitMix64 {
            SplitMix64(seed: UInt64(bitPattern: Int64(seed &* 1_000_003 &+ 1948 &+ number &* 7919)))
        }
        var rng = stream(0)
        func roll(_ range: ClosedRange<Double>) -> Double { Double.random(in: range, using: &rng) }
        func pick<T>(_ options: [T]) -> T { options[Int.random(in: 0 ..< options.count, using: &rng)] }
        func coin(_ p: Double) -> Bool { Double.random(in: 0 ..< 1, using: &rng) < p }
        let w = width, h = height
        let unit = w / 1382
        let mirrored = coin(0.5)
        func at(_ u: Double, _ v: Double) -> Vector2 { Vector2((mirrored ? 1 - u : u) * w, v * h) }
        var result = City()

        /// Grow a quarter of `count` boxes around `center`. The first box
        /// stands at the center. Each later one is set against a side of a
        /// box already standing. It is kept if it stays inside `reach` and
        /// shares almost no ground with the others.
        func grow(_ count: Int, around center: Vector2, reach: Vector2, sizes: ClosedRange<Double>,
                  flat: Bool = false, laps: ClosedRange<Double> = -3 ... 5) -> [Box] {
            // Small blocks are common and large ones rare.
            func box() -> (Double, Double) {
                let part = roll(0 ... 1)
                let side = (sizes.lowerBound + (sizes.upperBound - sizes.lowerBound) * part * part) * unit
                let shape = flat ? roll(1.0 ... 2.0) : roll(0.55 ... 1.8)
                return (side * shape.squareRoot(), side / shape.squareRoot())
            }
            guard count > 0 else { return [] }
            let first = box()
            var boxes = [Box(x: center.x - first.0 / 2, y: center.y - first.1 / 2, w: first.0, h: first.1)]
            var tries = 0
            while boxes.count < count, tries < count * 60 {
                tries += 1
                let parent = boxes[Int.random(in: 0 ..< boxes.count, using: &rng)]
                let size = box()
                // A new box overlaps its neighbor by a little, or leaves a
                // slit of the dark ground.
                let lap = roll(laps) * unit
                var next = Box(x: 0, y: 0, w: size.0, h: size.1)
                switch Int.random(in: 0 ..< 4, using: &rng) {
                case 0:
                    next.x = parent.x + roll(-size.0 * 0.6 ... max(-size.0 * 0.6 + 1, parent.w - size.0 * 0.4))
                    next.y = parent.y - size.1 + lap
                case 1:
                    next.x = parent.x + roll(-size.0 * 0.6 ... max(-size.0 * 0.6 + 1, parent.w - size.0 * 0.4))
                    next.y = parent.y + parent.h - lap
                case 2:
                    next.x = parent.x - size.0 + lap
                    next.y = parent.y + roll(-size.1 * 0.6 ... max(-size.1 * 0.6 + 1, parent.h - size.1 * 0.4))
                default:
                    next.x = parent.x + parent.w - lap
                    next.y = parent.y + roll(-size.1 * 0.6 ... max(-size.1 * 0.6 + 1, parent.h - size.1 * 0.4))
                }
                let dx = (next.midX - center.x) / reach.x, dy = (next.midY - center.y) / reach.y
                guard dx * dx + dy * dy <= 1 else { continue }
                guard boxes.allSatisfy({ $0.shared(with: next) <= 0.18 * min($0.w * $0.h, next.w * next.h) }) else {
                    continue
                }
                boxes.append(next)
            }
            return boxes
        }

        /// Turn a box into a block. It is turned a few degrees, narrowed at
        /// one end, and nudged at each corner. It gets its colors, its
        /// light, and perhaps a window.
        func raise(_ box: Box, colors: (UInt32, UInt32), quarter: Int, order: Double, lean: Double,
                   windowed: Bool, buried: Bool = false, pale: Bool = false) {
            let grainSeed = roll(0 ... 40)
            let center = Vector2(box.midX, box.midY)
            let turn = lean + roll(-0.11 ... 0.11)
            let nudge = min(box.w, box.h) * 0.08
            let narrow = roll(0.8 ... 1.0), above = coin(0.5)
            let corners = [Vector2(-box.w / 2 * (above ? narrow : 1), -box.h / 2),
                           Vector2(box.w / 2 * (above ? narrow : 1), -box.h / 2),
                           Vector2(box.w / 2 * (above ? 1 : narrow), box.h / 2),
                           Vector2(-box.w / 2 * (above ? 1 : narrow), box.h / 2)].map {
                center + ($0 + Vector2(roll(-nudge ... nudge), roll(-nudge ... nudge))).rotated(by: turn)
            }
            // The light comes from the upper left, but each block catches
            // it its own way, as a facet does.
            let toward = Vector2(angle: -2.2 + roll(-1.3 ... 1.3))
            // Each block is a little darker or warmer than its color.
            let tint = roll(-0.16 ... 0.12)
            func toned(_ hex: UInt32) -> Color {
                let color = Color(hex: hex)
                return tint < 0 ? color.mixed(with: .black, -tint) : color.mixed(with: Color(hex: 0xD9A040), tint)
            }
            // A pale slab has pink or blue-gray broken over it. Any other
            // block has a warm or green tone of the city's.
            let second = pale ? Color(hex: pick([0xE0AE96, 0xB4C0BE, 0xE8C7A4, 0xF6EAD6]))
                : Color(hex: pick(pick([LaCiudadPerdida.ochers, LaCiudadPerdida.oranges, LaCiudadPerdida.greens])).1)
            var window: Window?
            let small = min(box.w, box.h)
            // The chance is rolled first, so more of `windows` only ever adds
            // windows to the blocks that had none.
            let chance = roll(0 ... 1)
            if windowed, small > 20 * unit, chance < windows {
                let side = max(5 * unit, small * roll(0.14 ... 0.27))
                let room = Vector2(max(0, box.w * 0.4 - side * 1.2), max(0, box.h * 0.4 - side * 1.2))
                let middle = center + Vector2(roll(-room.x ... room.x), roll(-room.y ... room.y)).rotated(by: turn)
                let tilt = turn + roll(-0.08 ... 0.08)
                let wide = roll(0.8 ... 1.3)
                func pane(_ half: Double) -> [Vector2] {
                    [Vector2(-half * wide, -half), Vector2(half * wide, -half), Vector2(half * wide, half),
                     Vector2(-half * wide, half)].map { middle + $0.rotated(by: tilt) }
                }
                let framed = coin(0.42)
                let frames = LaCiudadPerdida.pales + LaCiudadPerdida.blues + LaCiudadPerdida.oranges
                    + LaCiudadPerdida.oranges
                window = Window(frame: framed ? pane(side * 0.5) : nil, frameColor: Color(hex: pick(frames).1),
                                pane: pane(side * (framed ? 0.26 : 0.36)),
                                paneColor: coin(0.82) ? soot : Color(hex: pick(LaCiudadPerdida.blues).0))
            }
            result.blocks.append(Block(outline: corners, base: toned(colors.0), lit: toned(colors.1), second: second,
                                       toward: toward, center: center, breadth: small / 2, window: window,
                                       quarter: quarter, order: order, seed: grainSeed, buried: buried))
        }

        // The quarters: where each stands, how far it reaches, its share
        // of the blocks, and which colors it leans to. The places are read
        // off the painting.
        struct Plan {
            var center: (Double, Double)
            var reach: (Double, Double)
            var share: Double
            var colors: [[(UInt32, UInt32)]]
            var depth: Double
        }
        let o = LaCiudadPerdida.ochers, r = LaCiudadPerdida.oranges, g = LaCiudadPerdida.greens
        let b = LaCiudadPerdida.blues, n = LaCiudadPerdida.browns
        let plans = [
            Plan(center: (0.31, 0.145), reach: (0.105, 0.09), share: 0.1, colors: [o, o, o, b, r], depth: 1),
            Plan(center: (0.555, 0.25), reach: (0.085, 0.135), share: 0.17, colors: [o, o, o, r, g, b], depth: 1),
            Plan(center: (0.735, 0.33), reach: (0.125, 0.1), share: 0.15, colors: [o, o, r, r, g, b], depth: 0.95),
            Plan(center: (0.15, 0.4), reach: (0.1, 0.085), share: 0.08, colors: [o, n, g, b], depth: 1),
            Plan(center: (0.37, 0.485), reach: (0.12, 0.055), share: 0.08, colors: [o, o, r, n], depth: 0.9),
            Plan(center: (0.665, 0.7), reach: (0.145, 0.12), share: 0.2, colors: [g, g, b, o, o, r], depth: 1),
            Plan(center: (0.1, 0.85), reach: (0.075, 0.06), share: 0.05, colors: [n, n, o], depth: 0.85),
            Plan(center: (0.37, 0.855), reach: (0.115, 0.05), share: 0.08, colors: [o, g, n, b], depth: 0.9),
            Plan(center: (0.88, 0.47), reach: (0.075, 0.07), share: 0.09, colors: [o, o, g, n], depth: 0.6),
        ]
        // A crowded city is dealt smaller blocks: past 320 of them, each
        // side shrinks so that the blocks cover the same ground.
        let fit = min(1, (320 / Double(max(1, blocks))).squareRoot())
        // Each quarter is found over its own stretch of the cycle, one
        // after another, with the next beginning before the last is done.
        var sequence = Array(plans.indices)
        sequence.shuffle(using: &rng)
        let span = 1.0 / (Double(plans.count) * 0.62 + 0.38)
        var towerHead: (center: Vector2, bottom: Double, order: Double, quarter: Int)?
        for (turnIndex, planIndex) in sequence.enumerated() {
            let plan = plans[planIndex]
            rng = stream(100 + planIndex)
            let center = at(plan.center.0 + roll(-0.02 ... 0.02), plan.center.1 + roll(-0.02 ... 0.02))
            let reach = Vector2(plan.reach.0 * w, plan.reach.1 * h)
            let count = max(1, Int((Double(blocks) * plan.share).rounded()))
            let boxes = grow(count, around: center, reach: reach, sizes: 22 * fit ... 96 * fit)
            let begun = Double(turnIndex) * 0.62 * span
            let lean = roll(-0.05 ... 0.05)
            // The blocks farthest from the middle of the quarter stay in
            // the ground.
            let far = boxes.map { box -> Double in
                let dx = (box.midX - center.x) / reach.x, dy = (box.midY - center.y) / reach.y
                return dx * dx + dy * dy
            }
            let kept = boxes.count - Int((Double(boxes.count) * buried).rounded())
            let limit = far.sorted()[max(0, min(far.count - 1, kept - 1))]
            for (index, box) in boxes.enumerated() {
                rng = stream(1000 * (planIndex + 1) + index)
                let order = begun + span * Double(index) / Double(boxes.count)
                raise(box, colors: pick(pick(plan.colors)), quarter: turnIndex, order: order, lean: lean,
                      windowed: true, buried: kept == 0 || far[index] > limit)
            }
            result.pits.append(Pit(center: center, reach: reach * 1.2, depth: plan.depth, quarter: turnIndex))
            if planIndex == 0 {
                towerHead = (center, (boxes.map { $0.y + $0.h }.max() ?? center.y), begun + span, turnIndex)
            }
            // The quarter at the bottom stands in a hull, a long shape
            // with a bowed keel, laid before its blocks.
            if planIndex == 7 {
                let long = 0.15 * w, deck = center.y + 0.012 * h, keel = 0.1 * h
                var outline = [Vector2(center.x - long, deck - 0.03 * h), Vector2(center.x - long * 0.4, deck),
                               Vector2(center.x + long * 0.5, deck + 0.004 * h),
                               Vector2(center.x + long, deck - 0.036 * h)]
                for step in 0 ... 7 {
                    let t = 1 - Double(step) / 7 * 2
                    outline.append(Vector2(center.x + long * t * 0.98, deck + keel * (1 - t * t) + 0.004 * h))
                }
                result.blocks.append(Block(outline: outline, base: Color(hex: 0x4A3E18), lit: Color(hex: 0xA88E3E),
                                           second: Color(hex: 0x7C8448), toward: Vector2(0.3, 0.95),
                                           center: Vector2(center.x, deck + keel * 0.5), breadth: keel * 0.6,
                                           window: nil, quarter: turnIndex, order: max(0, begun - 0.002),
                                           seed: 7.7))
            }
        }

        // The far field: blocks out in the open ground that are never
        // found. There are more of them as more of the city stays buried.
        rng = stream(50)
        let field = at(0.83 + roll(-0.02 ... 0.02), 0.13 + roll(-0.02 ... 0.02))
        for box in grow(Int((Double(blocks) * 0.4 * buried).rounded()), around: field,
                        reach: Vector2(0.14 * w, 0.11 * h), sizes: 44 ... 110, flat: true, laps: -2 ... 2) {
            raise(box, colors: pick(o), quarter: -1, order: 0, lean: 0.03, windowed: false, buried: true)
        }

        // The tower: its head stands on three thin legs, with a pale sail
        // between them that two bows cross.
        if let head = towerHead {
            rng = stream(51)
            let foot = head.bottom + 0.3 * h
            let sail = Box(x: head.center.x - 0.07 * w, y: head.bottom + 0.05 * h, w: 0.14 * w, h: 0.11 * h)
            raise(sail, colors: (0x8E9A84, 0xD8DEC6), quarter: head.quarter, order: head.order,
                  lean: roll(-0.1 ... 0.1), windowed: false, pale: true)
            for (index, offset) in [-0.05, -0.004, 0.045].enumerated() {
                let top = head.center.x + offset * w, bottom = top + roll(-0.014 ... 0.014) * w
                let wide = 0.0048 * w
                let color = pick(LaCiudadPerdida.blues)
                result.blocks.append(Block(outline: [Vector2(top - wide, head.bottom - 0.02 * h),
                                                     Vector2(top + wide, head.bottom - 0.02 * h),
                                                     Vector2(bottom + wide, foot), Vector2(bottom - wide, foot)],
                                           base: Color(hex: color.0), lit: Color(hex: color.1),
                                           second: Color(hex: color.1), toward: Vector2(-1, 0),
                                           center: Vector2(top, (head.bottom + foot) / 2),
                                           breadth: wide, window: nil, quarter: head.quarter,
                                           order: head.order + 0.01 * Double(index + 1), seed: roll(0 ... 40)))
            }
            for sag in [-1.0, 1.0] {
                let middle = Vector2(sail.midX, sail.midY)
                let bow = (0 ... 16).map { step -> Vector2 in
                    let t = Double(step) / 16 * 2 - 1
                    return middle + Vector2(t * 0.052 * w, sag * (1 - t * t) * 0.026 * h + 0.01 * h)
                }
                result.marks.append(Mark(points: bow, color: Color(hex: 0x8A3A1C), order: head.order + 0.05))
            }
            result.pits.append(Pit(center: Vector2(head.center.x, head.bottom + 0.16 * h),
                                   reach: Vector2(0.11 * w, 0.2 * h), depth: 0.9, quarter: head.quarter))
        }

        // The courts: a few large pale slabs laid together. The first is
        // the long one across the middle. A court has no pit of its own.
        let yards: [((Double, Double), (Double, Double), Int)] = [((0.3, 0.63), (0.23, 0.1), 9),
                                                                  ((0.625, 0.525), (0.075, 0.08), 4),
                                                                  ((0.83, 0.64), (0.06, 0.1), 4),
                                                                  ((0.55, 0.4), (0.07, 0.045), 3)]
        for (index, yard) in yards.prefix(courts).enumerated() {
            rng = stream(70 + index)
            let center = at(yard.0.0 + roll(-0.015 ... 0.015), yard.0.1 + roll(-0.015 ... 0.015))
            let reach = Vector2(yard.1.0 * w, yard.1.1 * h)
            let boxes = grow(yard.2, around: center, reach: reach, sizes: 96 ... 168, flat: true, laps: 2 ... 9)
            let begun = 0.25 + 0.2 * Double(index)
            let lean = roll(-0.03 ... 0.03)
            for (place, box) in boxes.enumerated() {
                rng = stream(80000 + 100 * index + place)
                raise(box, colors: pick(LaCiudadPerdida.pales), quarter: -1,
                      order: begun + 0.12 * Double(place) / Double(boxes.count), lean: lean, windowed: coin(0.45),
                      pale: true)
            }
        }
        // Blocks go on in the order they are found, so a later one lies
        // over an earlier one.
        result.blocks.sort { $0.order < $1.order }
        result.marks.sort { $0.order < $1.order }
        // The last block found, or the last mark drawn, is at 1.
        let last = max(result.blocks.last?.order ?? 1, result.marks.last?.order ?? 1)
        for index in result.blocks.indices { result.blocks[index].order /= last }
        for index in result.marks.indices { result.marks[index].order /= last }
        return result
    }

    // MARK: - The paint

    /// The ground: a deep ocher, clouded and streaked, that goes nearly
    /// black in the pit around each quarter. The pits ride along as
    /// numbers, five to a pit.
    private static let ground = """
    float4 shade(float2 uv, ShaderInfo info) {
        float grain = param(info, 0);
        float seed = param(info, 1);
        int count = int(param(info, 2));
        float2 p = info.position;
        float3 color = mix(float3(0.47, 0.29, 0.06), float3(0.64, 0.45, 0.09), clamp(0.5 + 0.7 * (uv.x - uv.y), 0.0, 1.0));
        float cloud = fbm(p / 230.0 + seed * 7.31) - 0.5;
        float patch = fbm(p / 64.0 + seed * 2.17) - 0.5;
        float dab = fbm(p / 11.0 + seed * 9.4) - 0.5;
        float streak = valueNoise(float2(p.x / 3.2 + seed * 3.1, p.y / 150.0)) - 0.5;
        float fine = hash12(floor(p) + seed * 17.0) - 0.5;
        color *= 1.0 + grain * (0.55 * cloud + 0.34 * patch + 0.16 * dab + 0.07 * streak + 0.1 * fine);
        float olive = smoothstep(0.46, 0.76, fbm(p / 170.0 + seed * 4.6));
        color = mix(color, color * float3(0.66, 0.78, 0.5), grain * 0.75 * olive);
        float glow = smoothstep(0.52, 0.8, fbm(p / 120.0 + seed * 12.2));
        color = mix(color, color * float3(1.2, 1.1, 0.8), grain * 0.5 * glow);
        float dark = 0.0;
        for (int i = 0; i < count; i++) {
            float2 c = float2(param(info, 3 + 5 * i), param(info, 4 + 5 * i));
            float2 r = float2(param(info, 5 + 5 * i), param(info, 6 + 5 * i));
            float2 q = (p - c) / r;
            float ragged = 0.9 * (fbm(p / 70.0 + seed + float(i) * 3.7) - 0.5) + 0.35 * (fbm(p / 17.0 + seed) - 0.5);
            float d = dot(q, q) * (1.0 + ragged);
            float pit = param(info, 7 + 5 * i) * smoothstep(1.32, 0.86, d);
            dark = 1.0 - (1.0 - dark) * (1.0 - pit);
        }
        color = mix(color, float3(0.055, 0.035, 0.025), 0.97 * dark);
        return float4(color, 1.0);
    }
    """

    /// One block's paint. The color runs from the dark side to the lit
    /// side, and the edge away from the light goes darker still. A second
    /// broken tone lies over it. The outline rides along as numbers, so the
    /// paint knows how far each pixel is from the nearest edge. `found` is
    /// how thick the coat is.
    private static let paint = """
    float4 shade(float2 uv, ShaderInfo info) {
        float3 base = float3(param(info, 0), param(info, 1), param(info, 2));
        float3 lit = float3(param(info, 3), param(info, 4), param(info, 5));
        float3 second = float3(param(info, 6), param(info, 7), param(info, 8));
        float2 toward = float2(param(info, 9), param(info, 10));
        float2 center = float2(param(info, 11), param(info, 12));
        float breadth = param(info, 13);
        float seed = param(info, 14);
        float grain = param(info, 15);
        float found = param(info, 16);
        int count = int(param(info, 17));
        float2 p = info.position;
        float edge = 1.0e6;
        for (int i = 0; i < count; i++) {
            int j = (i + 1) % count;
            float2 a = float2(param(info, 18 + 2 * i), param(info, 19 + 2 * i));
            float2 b = float2(param(info, 18 + 2 * j), param(info, 19 + 2 * j));
            float2 ab = b - a;
            float along = clamp(dot(p - a, ab) / max(dot(ab, ab), 1.0e-6), 0.0, 1.0);
            edge = min(edge, length(p - a - ab * along));
        }
        float run = clamp(0.5 + 0.5 * dot(p - center, toward) / max(breadth, 1.0), 0.0, 1.0);
        run = run * run * (3.0 - 2.0 * run);
        float3 color = mix(base, lit, run);
        float broken = 0.5 * fbm(p / 3.0 + seed * 3.1) + 0.5 * fbm(p / 15.0 + seed * 8.9);
        color = mix(color, second * (0.62 + 0.38 * run), grain * 0.6 * smoothstep(0.44, 0.7, broken));
        float rim = exp(-edge / (0.22 * breadth + 2.5));
        color *= 1.0 - 0.42 * rim * (1.0 - run);
        color = mix(color, lit * 1.05, 0.28 * rim * run);
        float cloud = fbm(p / 34.0 + seed * 7.3) - 0.5;
        float speck = hash12(floor(p) + seed * 17.0) - 0.5;
        color *= 1.0 + grain * (0.5 * cloud + 0.14 * speck);
        return float4(color, found);
    }
    """

    private func paint(for block: Block, found: Double) -> Shader {
        var numbers: [Float] = [Float(block.base.red), Float(block.base.green), Float(block.base.blue),
                                Float(block.lit.red), Float(block.lit.green), Float(block.lit.blue),
                                Float(block.second.red), Float(block.second.green), Float(block.second.blue),
                                Float(block.toward.x), Float(block.toward.y), Float(block.center.x),
                                Float(block.center.y), Float(block.breadth), Float(block.seed), Float(grain),
                                Float(found), Float(block.outline.count)]
        for point in block.outline {
            numbers += [Float(point.x), Float(point.y)]
        }
        return Shader(LaCiudadPerdida.paint, params: numbers, using: [.noise, .hash])
    }

    // MARK: - Drawing

    override func draw() {
        let seed = variation &+ pressed
        if built.seed != seed || built.blocks != blocks || built.courts != courts || built.windows != windows
            || built.buried != buried || built.width != width || built.height != height {
            built = (seed, blocks, courts, windows, buried, width, height)
            city = deal(seed: seed)
        }
        // A vector export gets the city as a plan.
        if isVectorExporting {
            drawPlan()
            return
        }
        let cycle = max(8, seconds)
        let turn = (time / cycle).truncatingRemainder(dividingBy: 1)
        func ease(_ x: Double) -> Double {
            let t = clamp(x, 0, 1)
            return t * t * (3 - 2 * t)
        }
        // The cycle. The city stands until 0.18. From there to 0.40 the
        // ground takes it back, the last block found going first. It lies
        // buried until 0.44 and is found again by 0.96.
        func found(_ place: Double) -> Double {
            if turn < 0.18 { return 1 }
            if turn < 0.42 { return 1 - ease(((turn - 0.18) / 0.22 * 1.12 - (1 - place)) / 0.12) }
            return ease(((turn - 0.44) / 0.52 * 1.08 - place) / 0.08)
        }
        let amounts = city.blocks.map { $0.buried ? 0 : found($0.order) }

        // A pit is as dark as its quarter is found.
        let quarters = (city.pits.map { $0.quarter }.max() ?? 0) + 1
        var up = [Double](repeating: 0, count: quarters)
        var total = [Double](repeating: 0, count: quarters)
        for (index, block) in city.blocks.enumerated() where !block.buried && block.quarter >= 0 {
            up[block.quarter] += amounts[index]
            total[block.quarter] += 1
        }
        var numbers: [Float] = [Float(grain), Float(seed % 89), Float(min(12, city.pits.count))]
        for pit in city.pits.prefix(12) {
            let share = total[pit.quarter] > 0 ? up[pit.quarter] / total[pit.quarter] : 0
            numbers += [Float(pit.center.x), Float(pit.center.y), Float(pit.reach.x), Float(pit.reach.y),
                        Float(pit.depth * share)]
        }
        noStroke()
        fill(Shader(LaCiudadPerdida.ground, params: numbers, using: [.noise, .hash]))
        drawRect(0, 0, width, height)

        let unit = width / 1382
        for (index, block) in city.blocks.enumerated() {
            lay(block, found: amounts[index], unit: unit)
        }
        noFill()
        strokeWeight(2.2 * unit)
        for mark in city.marks {
            let shown = found(mark.order)
            guard shown > 0 else { continue }
            stroke(mark.color.withAlpha(0.85 * shown))
            drawPolyline(mark.points)
        }
        noStroke()
    }

    /// The city as a plan, for a vector export: the outline of every block,
    /// the buried ones lighter, with the windows and the tower's bows. A pen
    /// can draw all of it.
    private func drawPlan() {
        let unit = width / 1382
        background(Color(hex: 0xEADFC6))
        noFill()
        for block in city.blocks {
            stroke(block.buried ? umber.withAlpha(0.45) : soot)
            strokeWeight((block.buried ? 0.8 : 1.2) * unit)
            drawShape(Shape(block.outline, closed: true))
            if let window = block.window, !block.buried {
                if let frame = window.frame { drawPolygon(frame) }
                drawPolygon(window.pane)
            }
        }
        strokeWeight(1.2 * unit)
        for mark in city.marks {
            stroke(mark.color)
            drawPolyline(mark.points)
        }
        noStroke()
    }

    /// Lay one block as far as it has been found. A block still in the
    /// ground is a faint outline. A found one throws a little dark onto
    /// whatever is under it, then takes its paint, its edge, and its window.
    private func lay(_ block: Block, found: Double, unit: Double) {
        let shape = Shape(block.outline, closed: true)
        if found < 1 {
            fill(Color(hex: 0xD9B45A).withAlpha(0.07 * (1 - found)))
            stroke(umber.withAlpha(0.5 * (1 - found)))
            strokeWeight(1.2 * unit)
            drawShape(shape)
        }
        guard found > 0 else { return }
        noStroke()
        // The dark under a block: its own outline, slid down and to the
        // side in thin coats.
        for step in 1 ... 3 {
            fill(Color.black.withAlpha(0.2 * found))
            withState {
                translate(Vector2(1.6, 2.4) * (Double(step) * unit))
                drawShape(shape)
            }
        }
        fill(paint(for: block, found: found))
        drawShape(shape)
        noFill()
        stroke(soot.withAlpha(0.8 * found))
        strokeWeight(1.7 * unit)
        drawShape(shape)
        noStroke()
        if let window = block.window {
            if let frame = window.frame {
                fill(window.frameColor.mixed(with: block.lit, 0.35).withAlpha(found))
                drawPolygon(frame)
            }
            fill(window.paneColor.withAlpha(found))
            drawPolygon(window.pane)
        }
    }
}
```
