Ollin

Diagonales

Bands of yarn along the two diagonals of a square, and four ways for them to cross.

Run
swift run --package-path Examples Example-Recreations-EduardoTerrazas-Diagonales
Source
Examples/Recreations/EduardoTerrazas/Diagonales/Sketch.swift
//  Recreation after Eduardo Terrazas - Posibilidades de una estructura,
//  subserie Diagonales (works numbered 1.3; wool yarn on a wooden board
//  covered with Campeche wax). His galleries date the tablas read here from
//  1975 to 2023. A homage, not a reproduction of any one tabla, and not
//  affiliated with or endorsed by the artist or his galleries.
//  https://eduardoterrazas.com/index.php/diagonals/
//  https://www.proyectosmonclova.com/works/eduardo-terrazas-1-3-2b
//  https://www.proyectosmonclova.com/works/eduardo-terrazas-1-3-41
//
//  An original Ollin interpretation, written from the one sentence his site
//  gives the subseries and from measuring photographs of the tablas. Nothing
//  was ported: the work is yarn pressed into wax.

import Foundation
import Ollin

/// Diagonales (Eduardo Terrazas). One of the five subseries of
/// *Posibilidades de una estructura*, and the one about crossing. His site
/// gives it one sentence. It "allows the artist to explore the intertwining
/// of lines in his designs, almost like weaving." The lines are bands of
/// yarn that run beside the two diagonals of a square. The work is what
/// happens where the two sets meet.
///
/// The measures here are read off photographs of two tablas of 2023, 1.3.2B
/// and 1.3.41. Each side of the square is divided into 25 parts, and lanes
/// one part wide run at 45 degrees through the marks. Nineteen lanes lie
/// along each diagonal, the middle one on the diagonal itself. So the two
/// sets cross in a tilted square of 19 by 19 crossings. The four triangles
/// left at the middles of the sides stay white. A lane is a band of colored
/// wool or a white one. `sett` says how many bands lie side by side before
/// a white lane: one in 1.3.2B, four in 1.3.41.
///
/// `weave` is what happens at a crossing. **knots** is the way of those two
/// tablas. A white lane passes over every band, and where two bands meet,
/// the crossing takes a wool of its own. Here it is one that neither band
/// has. **chevrons** is read off other tablas of the subseries. Each band
/// runs in from its corner as far as the upright or the level line through
/// the middle. There it meets the band from the next corner. **plain** and
/// **twill** take his "almost like weaving" at its word. They come from the
/// loom, not from any tabla: over one and under one, and over two and under
/// two. `weave`, `sett`, and `symmetry` each have a `dealt` setting, which
/// lets every tabla of the cycle take its own.
///
/// The yarn is drawn as he describes laying it: one strand, then another
/// and another in parallel lines that follow the outline of the shape. A
/// band's strands run its length, a knot's run around it, and the light
/// catches the two directions differently.
///
/// Try it: `firstTabla` is the number the cycle starts from, and a click
/// takes the next one. `tablas` is how many the cycle lays in turn. `colors`
/// is how many wools the bands are dealt from, and `strands` how many
/// strands a lane is wide. Over one cycle of `seconds` each tabla is held,
/// unpicked back to the waxed board, and the next is laid. It is laid the
/// way a cloth is woven. First comes every strip that goes down to the
/// right. Then the strips that go up to the right cross them, one at a
/// time. That cycle is also the export loop.
///
/// `--export-svg` writes every piece of yarn as a closed outline in its
/// color.
@main
final class Diagonales: Sketch {
    enum Weave: String, CaseIterable, ParamOption { case dealt, knots, chevrons, plain, twill }
    enum Sett: String, CaseIterable, ParamOption { case dealt, ones, twos, threes, fours }
    enum Symmetry: String, CaseIterable, ParamOption { case dealt, none, mirrored, fourfold }

    /// What happens where two lanes cross, or each tabla's own way in turn.
    @Param(icon: "square.grid.3x3.middle.filled") var weave = Weave.dealt
    /// How many bands lie side by side before a white lane.
    @Param(icon: "line.3.horizontal") var sett = Sett.dealt
    /// Whether the two sides of a diagonal, or all four corners, share wools.
    @Param(icon: "arrow.left.and.right") var symmetry = Symmetry.dealt
    /// How many wools the bands are dealt from.
    @Param(2 ... 7, icon: "paintpalette") var colors = 7
    /// How many strands of yarn a lane is wide.
    @Param(4 ... 12, icon: "ruler") var strands = 8
    /// How round the strands read: 0 is flat color.
    @Param(0 ... 1, icon: "sun.max") var relief = 0.7
    /// The number of the first tabla of the cycle, counted on from the seed.
    @Param(0 ... 9999, icon: "dice") var firstTabla = 0
    /// How many tablas one cycle lays, one after another.
    @Param(1 ... 6, icon: "square.stack") var tablas = 4
    /// One cycle: each tabla held, unpicked, and the next one laid.
    @Param(6 ... 120, icon: "clock") var seconds = 28.0

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

    // MARK: - The structure

    /// Where the tabla's middle sits, and half its side, in pixels.
    nonisolated static let center = Vector2(540, 540)
    nonisolated static let half = 420.0
    /// The parts a side is divided into. A lane is one part wide, measured
    /// along the side.
    nonisolated static let parts = 25
    /// The lanes on each side of the one that lies on a diagonal.
    nonisolated static let flank = 9
    /// A lane's width across, in pixels.
    nonisolated static var lane: Double { 2 * half / (Double(parts) * 2.0.squareRoot()) }
    /// How far a corner of the board is from its middle.
    nonisolated static var reach: Double { half * 2.0.squareRoot() }

    /// The structure has its own two axes, turned 45 degrees. `x` counts
    /// across the strips that go down to the right, toward the upper right.
    /// `y` counts across the strips that go up to the right, toward the
    /// lower right. This puts a point given that way on the canvas.
    nonisolated static func place(_ q: Vector2) -> Vector2 {
        let r = 0.5.squareRoot()
        return Vector2(center.x + (q.x + q.y) * r, center.y + (q.y - q.x) * r)
    }

    /// Whether a lane holds a band of colored wool. Lanes are numbered out
    /// from the diagonal, 0 on it, and the sign says which side.
    nonisolated static func isBand(_ lane: Int, group: Int) -> Bool {
        let out = abs(lane)
        // One band, one white lane, with the diagonal itself white (1.3.2B).
        if group <= 1 { return out % 2 == 1 }
        // Groups of bands with one white lane between them, the middle
        // group centered on the diagonal (1.3.41 has groups of four).
        return (out + (group + 1) / 2) % (group + 1) != 0
    }

    /// What lies on top at a crossing.
    enum Top { case down, up, knot }

    /// Which strip shows at a crossing. `i` is the lane of the strip that
    /// goes down to the right, `j` the lane of the one that goes up.
    nonisolated static func top(_ weave: Weave, group: Int, _ i: Int, _ j: Int) -> Top {
        let downBand = isBand(i, group: group), upBand = isBand(j, group: group)
        switch weave {
        case .dealt, .knots:
            // A white lane passes over a band, and two of a kind make a knot.
            if downBand == upBand { return .knot }
            return downBand ? .up : .down
        case .chevrons:
            // A strip keeps the top on its own side of the level and the
            // upright through the middle, and the two meet on those lines.
            if abs(i) == abs(j) { return .knot }
            return abs(i) > abs(j) ? .up : .down
        case .plain:
            return (i + j) % 2 == 0 ? .down : .up
        case .twill:
            return ((i + j) % 4 + 4) % 4 < 2 ? .down : .up
        }
    }

    // MARK: - One tabla

    /// One possibility: how it is woven, and the wool of every strip and of
    /// every knot. A wool is an index into the palette, and -1 is white.
    struct Tabla {
        var weave: Weave
        var group: Int
        var symmetry: Symmetry
        /// The strips that go down to the right, by lane, from -9 to 9.
        var down: [Int]
        /// The strips that go up to the right, by lane.
        var up: [Int]
        /// The wool at each crossing that is a knot of two bands.
        var knots: [Int]

        func top(_ i: Int, _ j: Int) -> Top { Diagonales.top(weave, group: group, i, j) }
        func knot(_ i: Int, _ j: Int) -> Int {
            knots[(i + Diagonales.flank) * (2 * Diagonales.flank + 1) + j + Diagonales.flank]
        }
    }

    /// Deals a tabla from its number. The three choices come first. Each
    /// draw is made whether or not a parameter holds that choice, so holding
    /// one leaves the others as dealt. Then the bands take their wools, lane
    /// by lane, no band matching the two before it. Then the knots: each
    /// takes a wool that neither of its bands has, nor the knot before it
    /// along either strip.
    nonisolated static func deal(number: Int, weave: Weave, sett: Sett, symmetry: Symmetry,
                                 colors: Int) -> Tabla {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(number &* 1_000_003 &+ 131)))
        func unit() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func pick(_ count: Int) -> Int { min(count - 1, Int(unit() * Double(count))) }
        let f = flank, span = 2 * flank + 1

        // The ways of crossing are taken in turn, so a cycle of four shows
        // all four. Number 1 takes the way of the tablas measured.
        let ways: [Weave] = [.knots, .chevrons, .plain, .twill]
        let turned = ways[((number - 1) % 4 + 4) % 4]
        let groups = [1, 1, 1, 4, 4, 2, 3]
        let dealtGroup = groups[pick(groups.count)]
        let symmetries: [Symmetry] = [.none, .none, .mirrored, .mirrored, .fourfold]
        let dealtSymmetry = symmetries[pick(symmetries.count)]

        let way = weave == .dealt ? turned : weave
        let group: Int
        switch sett {
        case .dealt: group = dealtGroup
        case .ones: group = 1
        case .twos: group = 2
        case .threes: group = 3
        case .fours: group = 4
        }
        let mirror = symmetry == .dealt ? dealtSymmetry : symmetry

        /// The wools of one set of strips, dealt along the lanes given.
        func bands(_ lanes: [Int]) -> [Int] {
            var wools = [Int](repeating: -1, count: span)
            var last = -1, before = -1
            for lane in lanes where isBand(lane, group: group) {
                var pool = (0 ..< colors).filter { $0 != last && (colors < 3 || $0 != before) }
                if pool.isEmpty { pool = Array(0 ..< colors) }
                let wool = pool[pick(pool.count)]
                wools[lane + f] = wool
                before = last
                last = wool
            }
            return wools
        }
        /// The far side of each diagonal takes the near side's wools.
        func mirrored(_ wools: [Int]) -> [Int] {
            var both = wools
            for out in 1 ... f { both[f - out] = wools[f + out] }
            return both
        }

        var down: [Int], up: [Int]
        switch mirror {
        case .dealt, .none:
            down = bands(Array(-f ... f))
            up = bands(Array(-f ... f))
        case .mirrored:
            down = mirrored(bands(Array(0 ... f)))
            up = mirrored(bands(Array(0 ... f)))
        case .fourfold:
            down = mirrored(bands(Array(0 ... f)))
            up = down
        }

        var knots = [Int](repeating: -1, count: span * span)
        let whole = mirror == .none || mirror == .dealt
        let first = whole ? -f : 0
        /// The nearest band lane before this one, in the order of dealing.
        func before(_ lane: Int) -> Int? {
            var other = lane - 1
            while other >= first {
                if isBand(other, group: group) { return other }
                other -= 1
            }
            return nil
        }
        for i in first ... f {
            for j in first ... f {
                guard isBand(i, group: group), isBand(j, group: group),
                      top(way, group: group, i, j) == .knot else { continue }
                // What this knot must not match, the least binding last.
                var avoid: [Int] = []
                if let other = before(i) { avoid.append(knots[(other + f) * span + j + f]) }
                if let other = before(j) { avoid.append(knots[(i + f) * span + other + f]) }
                avoid.append(down[i + f])
                avoid.append(up[j + f])
                var pool: [Int] = []
                while pool.isEmpty {
                    pool = (0 ..< colors).filter { !avoid.contains($0) }
                    if avoid.isEmpty { break }
                    if pool.isEmpty { avoid.removeLast() }
                }
                knots[(i + f) * span + j + f] = pool[pick(pool.count)]
            }
        }
        if !whole {
            for i in -f ... f {
                for j in -f ... f {
                    knots[(i + f) * span + j + f] = knots[(abs(i) + f) * span + abs(j) + f]
                }
            }
        }
        return Tabla(weave: way, group: group, symmetry: mirror, down: down, up: up, knots: knots)
    }

    // MARK: - The pieces of yarn

    /// One piece of yarn: its outline in pixels, its wool, and the parts it
    /// is laid in. Each part says which way its strands lie: 0 down to the
    /// right, 1 up to the right, 2 level, 3 upright.
    struct Field {
        var outline: [Vector2]
        var wool: Int
        var parts: [(outline: [Vector2], lay: Int)]
    }

    /// Cuts a convex outline, given on the structure's own axes, by the
    /// half-plane a*x + b*y <= c.
    nonisolated static func cut(_ outline: [Vector2], a: Double, b: Double, c: Double) -> [Vector2] {
        var kept: [Vector2] = []
        for index in outline.indices {
            let p = outline[index], q = outline[(index + 1) % outline.count]
            let dp = a * p.x + b * p.y - c, dq = a * q.x + b * q.y - c
            if dp <= 0 { kept.append(p) }
            if (dp < 0 && dq > 0) || (dp > 0 && dq < 0) { kept.append(p + (q - p) * (dp / (dp - dq))) }
        }
        return kept
    }

    /// An outline cut to the board, whose four edges are diagonals on the
    /// structure's own axes.
    nonisolated static func onBoard(_ outline: [Vector2]) -> [Vector2] {
        var result = outline
        for (a, b) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] where result.count >= 3 {
            result = cut(result, a: a, b: b, c: reach)
        }
        return result
    }

    /// Whether an outline is more than a sliver.
    nonisolated static func holds(_ outline: [Vector2]) -> Bool {
        guard outline.count >= 3 else { return false }
        var twice = 0.0
        for index in outline.indices {
            let p = outline[index], q = outline[(index + 1) % outline.count]
            twice += p.x * q.y - q.x * p.y
        }
        return abs(twice) > 1e-6
    }

    /// Every piece of yarn of a tabla when `laid` of it is down: 0 is the
    /// bare board and 1 the whole tabla. The strips that go down to the
    /// right are laid first, from the upper left, one lane after another.
    /// Then the strips that go up to the right cross them from the lower
    /// left. A crossing takes its final wool as the second strip arrives.
    /// The white triangles at the sides go down last.
    nonisolated static func fields(of tabla: Tabla, laid: Double) -> [Field] {
        let w = lane, far = reach, f = flank
        let edge = (Double(f) + 0.5) * w
        let first = min(1, laid / 0.30)
        let second = min(1, max(0, (laid - 0.30) / 0.60))
        let sides = min(1, max(0, (laid - 0.90) / 0.10))
        /// How far from the middle a strip's lane runs before it leaves
        /// the board: the lanes near a corner are the long ones.
        func run(_ lane: Int) -> Double { far - max(0, Double(abs(lane)) - 0.5) * w }
        /// How far along its lane each strip has come, on its own axis.
        /// Each strip takes the same time to cross, whatever its length.
        func downTip(_ i: Int) -> Double {
            let t = (first - Double(i + f) / Double(2 * f) * 0.5) / 0.5
            return run(i) * (2 * min(1, max(0, t)) - 1)
        }
        func upTip(_ j: Int) -> Double {
            let t = (second - Double(j + f) / Double(2 * f) * 0.7) / 0.3
            return run(j) * (2 * min(1, max(0, t)) - 1)
        }
        func box(_ x0: Double, _ x1: Double, _ y0: Double, _ y1: Double) -> [Vector2] {
            [Vector2(x0, y0), Vector2(x1, y0), Vector2(x1, y1), Vector2(x0, y1)]
        }
        var result: [Field] = []
        func add(_ outline: [Vector2], wool: Int, lay: Int) {
            let cutToBoard = onBoard(outline)
            guard holds(cutToBoard) else { return }
            let placed = cutToBoard.map(place)
            result.append(Field(outline: placed, wool: wool, parts: [(placed, lay)]))
        }

        // The strips that go down to the right. Each shows from its corner
        // arm to the far one, less the crossings where another strip or a
        // knot has taken the top.
        for i in -f ... f {
            let x0 = (Double(i) - 0.5) * w, x1 = x0 + w
            let tip = downTip(i)
            guard tip > -run(i) else { continue }
            let wool = tabla.down[i + f]
            var start: Double? = -far
            func close(at y: Double) {
                if let from = start, y > from {
                    add(cut(box(x0, x1, from, y), a: 0, b: 1, c: tip), wool: wool, lay: 0)
                }
                start = nil
            }
            for j in -f ... f {
                let y0 = (Double(j) - 0.5) * w, y1 = y0 + w
                let other = upTip(j)
                if tabla.top(i, j) == .down || other <= x0 {
                    if start == nil { start = y0 }
                } else {
                    close(at: y0)
                    // The crossing strip has come only part of the way over.
                    if other < x1 { add(cut(box(other, x1, y0, y1), a: 0, b: 1, c: tip), wool: wool, lay: 0) }
                }
            }
            if start == nil { start = edge }
            close(at: far)
        }

        // The strips that go up to the right, cut off at their tips.
        for j in -f ... f {
            let y0 = (Double(j) - 0.5) * w, y1 = y0 + w
            let tip = upTip(j)
            guard tip > -run(j) else { continue }
            let wool = tabla.up[j + f]
            var start: Double? = -far
            func close(at x: Double) {
                if let from = start, x > from {
                    add(cut(box(from, x, y0, y1), a: 1, b: 0, c: tip), wool: wool, lay: 1)
                }
                start = nil
            }
            for i in -f ... f {
                let x0 = (Double(i) - 0.5) * w
                if tabla.top(i, j) == .up {
                    if start == nil { start = x0 }
                } else {
                    close(at: x0)
                }
            }
            if start == nil { start = edge }
            close(at: far)
        }

        // The knots: a crossing laid as its own small square, the strands
        // running around it, so each side's strands lie beside that side.
        for i in -f ... f {
            for j in -f ... f where tabla.top(i, j) == .knot {
                let tip = upTip(j)
                let x0 = (Double(i) - 0.5) * w, x1 = x0 + w
                let y0 = (Double(j) - 0.5) * w, y1 = y0 + w
                guard tip > x0 else { continue }
                let bands = isBand(i, group: tabla.group) && isBand(j, group: tabla.group)
                let corners = box(x0, x1, y0, y1)
                let middle = Vector2((x0 + x1) / 2, (y0 + y1) / 2)
                var parts: [(outline: [Vector2], lay: Int)] = []
                for side in 0 ..< 4 {
                    let part = cut([corners[side], corners[(side + 1) % 4], middle], a: 1, b: 0, c: tip)
                    if holds(part) { parts.append((part.map(place), side % 2 == 0 ? 1 : 0)) }
                }
                let outline = cut(corners, a: 1, b: 0, c: tip)
                guard holds(outline), !parts.isEmpty else { continue }
                result.append(Field(outline: outline.map(place), wool: bands ? tabla.knot(i, j) : -1, parts: parts))
            }
        }

        // The four white triangles at the middles of the sides, laid from
        // their edges in toward the point every edge is equally far from.
        if sides > 0 {
            for (sx, sy) in [(1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0)] {
                let a = Vector2(sx * edge, sy * edge)
                let b = Vector2(sx * edge, sy * (far - edge))
                let c = Vector2(sx * (far - edge), sy * edge)
                let la = (b - c).length, lb = (c - a).length, lc = (a - b).length
                let inner = (a * la + b * lb + c * lc) / (la + lb + lc)
                let bare = 1 - sides
                func toward(_ q: Vector2) -> Vector2 { inner + (q - inner) * bare }
                // The top and bottom triangles lie against a level edge of
                // the board, the left and right ones against an upright edge.
                let boardLay = sx * sy < 0 ? 2 : 3
                var parts: [(outline: [Vector2], lay: Int)] = []
                for (p, q, lay) in [(a, b, 0), (c, a, 1), (b, c, boardLay)] {
                    let part = bare > 1e-9 ? [p, q, toward(q), toward(p)] : [p, q, inner]
                    parts.append((part.map(place), lay))
                }
                result.append(Field(outline: bare > 1e-9 ? [] : [a, b, c].map(place), wool: -1, parts: parts))
            }
        }
        return result
    }

    // MARK: - The yarn

    /// One strand of yarn, run at every pixel of a piece. It needs only
    /// where the pixel is and which way the piece is laid. Strands are
    /// counted across the lanes, so every piece laid one way shares its
    /// rows with its neighbors. A strand is shaded as a round thread of two
    /// twisted plies, lit from the upper left.
    private static let yarn = """
    static float3 diagonalesWool(float v) {
        float r = floor(v / 65536.0);
        float g = floor((v - r * 65536.0) / 256.0);
        float b = v - r * 65536.0 - g * 256.0;
        return float3(r, g, b) / 255.0;
    }

    float4 shade(float2 uv, ShaderInfo info) {
        float2 p = info.position - float2(param(info, 0), param(info, 1));
        float lane = param(info, 2);
        float pitch = lane / param(info, 3);
        float relief = param(info, 4);
        float rim = param(info, 5);
        float lay = param(info, 6);
        float3 wool = srgbToLinear(diagonalesWool(param(info, 7)));

        // The bare board: wax, a little uneven.
        if (lay > 3.5) {
            return float4(linearToSrgb(wool * (0.90 + 0.20 * fbm(p * 0.035))), 1.0);
        }

        // `across` is the way the strands are counted and `run` the way
        // they lie.
        float2 across = float2(0.70710678, -0.70710678);
        if (lay > 0.5) across = float2(0.70710678, 0.70710678);
        if (lay > 1.5) across = float2(0.0, 1.0);
        if (lay > 2.5) across = float2(1.0, 0.0);
        float2 run = float2(across.y, -across.x);
        float offset = dot(p, across);
        // On the diagonals strands are counted from a lane's edge. Beside
        // an edge of the board they are counted in from that edge.
        float x = lay < 1.5 ? (offset + 0.5 * lane) / pitch : (rim - abs(offset)) / pitch;
        float turn = lay < 1.5 ? 1.0 : (offset > 0.0 ? -1.0 : 1.0);
        float along = dot(p, run) / pitch;

        float strand = floor(x);
        float f = fract(x) * 2.0 - 1.0;
        float lot = hash12(float2(strand, 17.0 + lay * 31.0));
        float rise = sqrt(max(0.0, 1.0 - f * f));
        float3 normal = normalize(float3(across * f * turn, rise + 0.35));
        float ply = sin((along / 3.0 + f * 0.5 + lot) * 6.2831853);
        normal = normalize(normal + float3(run * ply * 0.35, 0.0));
        float lit = max(dot(normal, normalize(float3(-0.45, -0.6, 0.66))), 0.0);
        float groove = smoothstep(1.0, 0.72, abs(f));
        float fiber = valueNoise(float2(along * 0.9 + lot * 40.0, x * 7.0)) - 0.5;
        float tone = mix(1.0, (0.50 + 0.58 * lit) * mix(0.66, 1.0, groove), relief);
        tone *= 1.0 + relief * (0.10 * fiber + 0.07 * (lot - 0.5));
        return float4(linearToSrgb(wool * tone), 1.0);
    }
    """

    // MARK: - Drawing

    private let wall = Color(hex: 0xE9E6DF)
    private let maple = Color(hex: 0xD9C19A)
    private let recess = Color(hex: 0x2B2622)
    private let wax = Color(hex: 0x8B6B3D)
    private let white = Color(hex: 0xF1EFE8)
    /// The wools, sampled from a photograph of 1.3.2B, in the order the
    /// `colors` parameter takes them.
    private let dyed: [Color] = [
        Color(hex: 0xC9002B), Color(hex: 0x04579E), Color(hex: 0xE7A302), Color(hex: 0x5A9247),
        Color(hex: 0xDD5E2B), Color(hex: 0x11182F), Color(hex: 0x01363E),
    ]

    private var kept: [String: Tabla] = [:]

    /// The tabla at a place in the cycle, dealt once and kept.
    private func tabla(at index: Int) -> Tabla {
        let number = variation &+ firstTabla &+ index
        let name = "\(number)/\(weave.rawValue)/\(sett.rawValue)/\(symmetry.rawValue)/\(colors)"
        if let found = kept[name] { return found }
        if kept.count > 60 { kept.removeAll() }
        let made = Diagonales.deal(number: number, weave: weave, sett: sett, symmetry: symmetry, colors: colors)
        kept[name] = made
        return made
    }

    /// Where the cycle is: which tabla is on the board, and how much of it
    /// is laid. Each tabla is held, unpicked the way it went in, and the
    /// next is laid, so the last one hands over to the first.
    private func moment() -> (index: Int, laid: Double) {
        let count = max(1, tablas)
        let place = loopProgress(over: seconds) * Double(count)
        let slot = min(count - 1, Int(place)), within = place - Double(slot)
        func ease(_ t: Double) -> Double { t * t * (3 - 2 * t) }
        switch within {
        case ..<0.32: return (slot, 1)
        case ..<0.48: return (slot, 1 - ease((within - 0.32) / 0.16))
        case ..<0.51: return (slot, 0)
        case ..<0.97: return ((slot + 1) % count, (within - 0.51) / 0.46)
        default: return ((slot + 1) % count, 1)
        }
    }

    override func mousePressed() {
        firstTabla = firstTabla >= 9999 ? 0 : firstTabla + 1
    }

    private func color(of wool: Int) -> Color { wool < 0 ? white : dyed[wool % dyed.count] }

    override func draw() {
        let (index, laid) = moment()
        let pieces = Diagonales.fields(of: tabla(at: index), laid: laid)
        let c = Diagonales.center, h = Diagonales.half

        background(wall)
        noStroke()
        fill(maple)
        drawRect(center: c, width: 2 * h + 64, height: 2 * h + 64)
        fill(recess)
        drawRect(center: c, width: 2 * h + 36, height: 2 * h + 36)

        if isVectorExporting {
            fill(wax)
            drawRect(center: c, width: 2 * h, height: 2 * h)
            for piece in pieces {
                fill(color(of: piece.wool))
                if piece.outline.isEmpty {
                    for part in piece.parts { drawPolygon(part.outline) }
                } else {
                    drawPolygon(piece.outline)
                }
            }
            return
        }

        func packed(_ color: Color) -> Float {
            let r = (color.red * 255).rounded(), g = (color.green * 255).rounded()
            let b = (color.blue * 255).rounded()
            return Float(r * 65536 + g * 256 + b)
        }
        func paint(lay: Int, _ color: Color) -> Shader {
            Shader(Diagonales.yarn, params: [
                Float(c.x), Float(c.y), Float(Diagonales.lane), Float(strands), Float(relief), Float(h),
                Float(lay), packed(color),
            ])
        }

        // The waxed board, with the lanes scored into it.
        fill(paint(lay: 4, wax))
        drawRect(center: c, width: 2 * h, height: 2 * h)
        if laid < 1 {
            noFill()
            stroke(Color(white: 0, alpha: 0.28))
            strokeWeight(1)
            let far = Diagonales.reach
            for mark in 0 ... 2 * Diagonales.flank + 1 {
                let at = (Double(mark - Diagonales.flank) - 0.5) * Diagonales.lane
                let run = far - abs(at)
                drawLine(Diagonales.place(Vector2(at, -run)), Diagonales.place(Vector2(at, run)))
                drawLine(Diagonales.place(Vector2(-run, at)), Diagonales.place(Vector2(run, at)))
            }
            noStroke()
        }

        // Pieces are put down a wool and a lay at a time, so that every
        // piece sharing a paint is drawn in one go. No two pieces overlap,
        // so the order does not change the picture.
        var groups = [[[Vector2]]](repeating: [], count: 4 * 8)
        for piece in pieces {
            for part in piece.parts { groups[part.lay * 8 + piece.wool + 1].append(part.outline) }
        }
        for (key, outlines) in groups.enumerated() where !outlines.isEmpty {
            fill(paint(lay: key / 8, color(of: key % 8 - 1)))
            for outline in outlines { drawPolygon(outline) }
        }
    }
}

↑↓ move ↩ open