Ollin

LoveLetterOne

A net written with the letters B and D, with windows left in it for red words, after Shemza's Love Letter I (1969).

Run
swift run --package-path Examples Example-Recreations-AnwarJalalShemza-LoveLetterOne
Source
Examples/Recreations/AnwarJalalShemza/LoveLetterOne/Sketch.swift
//  Recreation after Anwar Jalal Shemza - Love Letter I (1969, oil on canvas,
//  91.4 x 58.7 cm, The Metropolitan Museum of Art, 2013.263; the estate
//  lists it as Love Letter One). A homage, not a reproduction, and not
//  affiliated with or endorsed by the artist or his estate.
//  https://www.metmuseum.org/art/collection/search/499568
//  https://www.anwarshemza.com/
//
//  An original Ollin interpretation, written from the museum's description
//  of the painting and from looking at pictures of it and of Love Letter 2.
//  The description gives the letters B and D, stacked and repeated, and the
//  lattice their curves make. The two sizes of cell, the runs of letters, the
//  windows, and the words in them are read off those pictures or are this
//  sketch's own. There is no code to port.

import Ollin

/// Love Letter I (Anwar Jalal Shemza, 1969). From a step away the painting
/// is a gray sheet with a fine net drawn across it, like a page of close
/// writing. Small windows are left open in the net, and in each a few signs
/// are written large in red. The museum that holds it says how the net is
/// made. The letters B and D stack and repeat, and their curves lace into a
/// lattice. Shemza said his pictures were built from two forms, the square
/// and the circle. A D is exactly that, a straight stroke from the square
/// and a half circle on it, and a B is two of them on one stroke.
///
/// This sketch writes the net with those two letters. The sheet is ruled
/// into square cells, in patches of two sizes, one half the other. The
/// ruled lines are the letters' straight strokes. In every cell a half
/// circle, a bowl, stands on one of the four sides, and that is a D. Often
/// a second bowl stands on the side opposite, and the two touch in the
/// middle of the cell. The same choice repeats along a run of cells, so
/// bowls line up on one stroke into B's and longer stacks. Bowls that meet
/// back to back across a stroke close into rings. A few bowls are filled.
/// The windows are cut out of the net, and each takes a word built from the
/// same two letters, larger and in red. Three more words stand in the bare
/// margins above and below, as in the painting.
///
/// Try it: `columns` is how many of the larger cells cross the sheet, and
/// `fine` is how much of the net is written at the smaller size. `windows`
/// is how many words are let into it, and `filled` is the share of bowls
/// that take a fill. `palette` is the gray sheet of Love Letter I or the
/// tan one of Love Letter 2. The seed deals the patches, the letters, and
/// the words, and a press deals the next sheet.
///
/// Over one cycle of `seconds` the net is written from the top, a row at a
/// time and right to left. Then the red words are written, stroke by
/// stroke. Then the letter holds and clears, which is also the export loop.
///
/// `--export-svg` with a frame in the hold writes the ruled lines as lines
/// and every bowl as its arc. So the file gives the rule back: every arc is
/// a half circle standing on a stroke, every cell of the net holds one, and
/// no line of the net crosses a window.
@main
final class LoveLetterOne: Sketch {
    enum Palette: String, CaseIterable, ParamOption {
        /// After Love Letter I: a gray sheet, ocher fills.
        case one
        /// After Love Letter 2: a tan sheet, blue fills.
        case two
    }

    /// The sheet and its paints.
    @Param(icon: "paintpalette") var palette = Palette.one
    /// How many of the larger cells cross the sheet.
    @Param(28 ... 56, icon: "square.grid.3x3") var columns = 44
    /// How much of the net is written at the smaller size.
    @Param(0 ... 1, icon: "square.grid.4x3.fill") var fine = 0.45
    /// How many windows are cut in the net for words.
    @Param(0 ... 18, icon: "rectangle.dashed") var windows = 12
    /// The share of bowls that take a fill. The larger bowls take one more
    /// often, as the painting's do.
    @Param(0 ... 0.05, icon: "circle.lefthalf.filled") var filled = 0.009
    /// One cycle: the letter is written, held, and cleared.
    @Param(8 ... 30, icon: "clock") var seconds = 24.0

    // The painting is 91.4 cm tall and 58.7 cm wide.
    override var canvasSize: CanvasSize { .size(694, 1080) }
    override var loopDuration: Double? { seconds }

    /// A half circle standing on a stroke.
    private struct Bowl {
        var center: Vector2
        var radius: Double
        /// The angle the arc starts at. It sweeps a half turn from there.
        var start: Double
        var isFilled: Bool
    }

    /// One stroke of a red word.
    private enum Mark {
        case line(Vector2, Vector2)
        case arc(center: Vector2, radius: Double, start: Double)
    }

    private struct Word {
        var marks: [Mark]
    }

    /// A band of the net: the painting has two, one above the other.
    private struct Band {
        var lines: [(Vector2, Vector2)]
        var bowls: [Bowl]
        var top: Double
        var rows: Int
    }

    private struct Letter {
        var bands: [Band]
        /// The words in the order they are written.
        var words: [Word]
        var cell: Double
    }

    private struct Dealt: Equatable {
        var columns: Int, fine: Double, windows: Int, filled: Double, seed: Int
    }

    private struct Paints {
        var sheet: Color, ink: Color, word: Color, fill: Color
    }

    private var paints: Paints {
        switch palette {
        case .one:
            Paints(sheet: Color(hex: 0xC6C8CA), ink: Color(hex: 0x2E3642), word: Color(hex: 0xE8442D),
                   fill: Color(hex: 0xCB8D2C))
        case .two:
            Paints(sheet: Color(hex: 0xB8944E), ink: Color(hex: 0x3A2E20), word: Color(hex: 0xEE5540),
                   fill: Color(hex: 0x6FACE4))
        }
    }

    private var letter: Letter?
    private var dealtFor: Dealt?
    private var pressed = false

    private var inkWidth: Double { 0.0011 * width }
    private var wordWidth: Double { 0.0028 * width }

    override func mousePressed() {
        pressed = true
    }

    override func draw() {
        if pressed {
            pressed = false
            seed(variation + 1)
        }
        let wanted = Dealt(columns: columns, fine: fine, windows: windows, filled: filled, seed: variation)
        if dealtFor != wanted || letter == nil {
            dealtFor = wanted
            letter = deal()
        }
        guard let letter else { return }
        let paints = paints

        background(paints.sheet)
        let phase = loopProgress(over: seconds)
        let begun = 0.02, netted = 0.62, worded = 0.84, held = 0.94

        // The net, a row of the larger cells at a time, from the right.
        let rows = letter.bands.reduce(0) { $0 + $1.rows }
        let netting = min(1, max(0, (phase - begun) / (netted - begun))) * Double(rows)
        var before = 0
        for band in letter.bands {
            let written = netting - Double(before)
            before += band.rows
            guard written > 0 else { continue }
            if written >= Double(band.rows) {
                drawBand(band, paints: paints)
                continue
            }
            let whole = written.rounded(.down)
            let rowTop = band.top + whole * letter.cell
            // The rows already written, then the row the pen is in.
            if whole > 0 {
                withClip(Rectangle(x: 0, y: band.top - 2, width: width, height: rowTop - band.top + 2)) {
                    drawBand(band, paints: paints)
                }
            }
            let across = (written - whole) * width
            withClip(Rectangle(x: width - across, y: rowTop, width: across, height: letter.cell)) {
                drawBand(band, paints: paints)
            }
        }

        // The red words, one after another, each stroke by stroke.
        let wording = min(1, max(0, (phase - netted) / (worded - netted))) * Double(letter.words.count)
        noFill()
        stroke(paints.word)
        strokeWeight(wordWidth)
        strokeCap(.round)
        for (index, word) in letter.words.enumerated() {
            let share = min(1, max(0, wording - Double(index)))
            guard share > 0 else { continue }
            let count = Int((share * Double(word.marks.count)).rounded(.up))
            for mark in word.marks.prefix(count) {
                switch mark {
                case .line(let from, let to):
                    drawLine(from, to)
                case .arc(let center, let radius, let start):
                    drawArc(center: center, radiusX: radius, radiusY: radius, start: start, stop: start + .pi,
                            mode: .open)
                }
            }
        }
        noStroke()

        if phase > held {
            fill(paints.sheet.withAlpha(smoothstep(held, 1, phase)))
            drawRect(0, 0, width, height)
        }
    }

    /// One band of the net: the ruled strokes, then the bowls on them.
    private func drawBand(_ band: Band, paints: Paints) {
        stroke(paints.ink)
        strokeWeight(inkWidth)
        strokeCap(.butt)
        noFill()
        for (from, to) in band.lines {
            drawLine(from, to)
        }
        for bowl in band.bowls where !bowl.isFilled {
            drawArc(center: bowl.center, radiusX: bowl.radius, radiusY: bowl.radius,
                    start: bowl.start, stop: bowl.start + .pi, mode: .open)
        }
        fill(paints.fill)
        for bowl in band.bowls where bowl.isFilled {
            drawArc(center: bowl.center, radiusX: bowl.radius, radiusY: bowl.radius,
                    start: bowl.start, stop: bowl.start + .pi, mode: .chord)
        }
        noFill()
        noStroke()
    }

    // MARK: - Dealing

    /// A patch of the net, in larger cells, written at one size.
    private struct Patch {
        var column: Int, row: Int, columns: Int, rows: Int
        var isFine: Bool
    }

    /// A window, in larger cells.
    private struct Opening {
        var column: Int, row: Int, columns: Int, rows: Int
    }

    /// Deals the sheet for the seed: two bands of net, the windows in
    /// them, and the words.
    private func deal() -> Letter {
        randomSeed(variation)
        let margin = 0.008 * width
        let cell = (width - 2 * margin) / Double(columns)
        // The painting's bands take about 0.49 and 0.27 of its height, with
        // a strip of bare sheet between them.
        let upperRows = max(6, Int((0.488 * height / cell).rounded()))
        let lowerRows = max(4, Int((0.272 * height / cell).rounded()))
        let strip = 0.8 * cell
        let top = 0.119 * height
        let tops = [top, top + Double(upperRows) * cell + strip]
        let counts = [upperRows, lowerRows]

        // The window sizes of the painting, in larger cells at 44 across,
        // dealt in this order: eight above and four below.
        let sizes: [(Int, Int)] = [(10, 4), (5, 8), (6, 6), (4, 9), (11, 3), (3, 9), (3, 3), (3, 3),
                                   (6, 7), (5, 7), (3, 2), (3, 2), (8, 3), (4, 4), (3, 6), (7, 3), (3, 3), (4, 5)]
        let above = [0, 1, 2, 3, 4, 5, 6, 7, 12, 14, 15, 17], below = [8, 9, 10, 11, 13, 16]
        var wanted: [[(Int, Int)]] = [[], []]
        var a = 0, b = 0
        for index in 0 ..< windows {
            // Two above for each one below, as the bands' sizes ask.
            if index % 3 == 2, b < below.count {
                wanted[1].append(sizes[below[b]]); b += 1
            } else if a < above.count {
                wanted[0].append(sizes[above[a]]); a += 1
            } else if b < below.count {
                wanted[1].append(sizes[below[b]]); b += 1
            }
        }

        var bands: [Band] = []
        var words: [Word] = []
        let scale = Double(columns) / 44
        for index in 0 ..< 2 {
            let rows = counts[index]
            // Place the windows, apart from each other and off the edges.
            var placed: [Opening] = []
            for (wide, tall) in wanted[index] {
                let w = max(2, Int((Double(wide) * scale).rounded()))
                let h = max(2, Int((Double(tall) * scale).rounded()))
                guard w <= columns - 4, h <= rows - 2 else { continue }
                for _ in 0 ..< 200 {
                    let column = 2 + Int(random(0, Double(columns - w - 3)))
                    let row = 1 + Int(random(0, Double(rows - h - 1)))
                    let fits = !placed.contains {
                        column < $0.column + $0.columns + 2 && $0.column < column + w + 2
                            && row < $0.row + $0.rows + 2 && $0.row < row + h + 2
                    }
                    if fits {
                        placed.append(Opening(column: column, row: row, columns: w, rows: h))
                        break
                    }
                }
            }
            let origin = Vector2(margin, tops[index])
            bands.append(net(origin: origin, cell: cell, rows: rows, openings: placed))
            // The words read from the top, and from the right in a row.
            let ordered = placed.sorted { ($0.row, -$0.column) < ($1.row, -$1.column) }
            for opening in ordered {
                let box = Rectangle(x: origin.x + Double(opening.column) * cell, y: origin.y + Double(opening.row) * cell,
                                    width: Double(opening.columns) * cell, height: Double(opening.rows) * cell)
                words.append(word(in: box, pad: 0.75 * cell))
            }
        }

        // Three words in the bare margins: two above the net, one below.
        let unit = (width - 2 * margin) / 44
        let high = 0.119 * height, low = bands[1].top + Double(lowerRows) * cell
        let first = Rectangle(x: random(0.16, 0.3) * width, y: 0.3 * high, width: 9.5 * unit, height: 2.0 * unit)
        let second = Rectangle(x: random(0.7, 0.8) * width, y: 0.26 * high, width: 4.6 * unit, height: 3.4 * unit)
        let third = Rectangle(x: random(0.12, 0.4) * width, y: low + 0.32 * (height - low), width: 10.5 * unit,
                              height: 3.2 * unit)
        words.insert(word(in: first, pad: 0), at: 0)
        words.insert(word(in: second, pad: 0), at: 0)
        words.append(word(in: third, pad: 0))
        return Letter(bands: bands, words: words, cell: cell)
    }

    /// Writes one band of net: patches of two sizes, a bowl or two in
    /// every cell outside the windows, and the ruled strokes around them.
    private func net(origin: Vector2, cell: Double, rows: Int, openings: [Opening]) -> Band {
        // Cut the band into patches by splitting it again and again, and
        // give each patch a size of cell.
        var patches: [Patch] = []
        var pending = [Patch(column: 0, row: 0, columns: columns, rows: rows, isFine: false)]
        while let patch = pending.popLast() {
            let small = patch.columns <= 14 && patch.rows <= 12
            if (small && random() < 0.55) || patch.columns < 8 && patch.rows < 8 {
                var leaf = patch
                leaf.isFine = random() < fine
                patches.append(leaf)
                continue
            }
            if patch.columns >= patch.rows, patch.columns >= 8 {
                let cut = 4 + Int(random(0, Double(patch.columns - 7)))
                pending.append(Patch(column: patch.column, row: patch.row, columns: cut, rows: patch.rows, isFine: false))
                pending.append(Patch(column: patch.column + cut, row: patch.row, columns: patch.columns - cut,
                                     rows: patch.rows, isFine: false))
            } else if patch.rows >= 8 {
                let cut = 4 + Int(random(0, Double(patch.rows - 7)))
                pending.append(Patch(column: patch.column, row: patch.row, columns: patch.columns, rows: cut, isFine: false))
                pending.append(Patch(column: patch.column, row: patch.row + cut, columns: patch.columns,
                                     rows: patch.rows - cut, isFine: false))
            } else {
                var leaf = patch
                leaf.isFine = random() < fine
                patches.append(leaf)
            }
        }
        patches.sort { ($0.row, $0.column) < ($1.row, $1.column) }

        // Everything below is counted in the smaller cells, two to a
        // larger one, so both sizes share one set of ruled strokes.
        let across = 2 * columns, down = 2 * rows
        let half = cell / 2
        var open = [Bool](repeating: false, count: across * down)
        for opening in openings {
            for y in 2 * opening.row ..< 2 * (opening.row + opening.rows) {
                for x in 2 * opening.column ..< 2 * (opening.column + opening.columns) {
                    open[y * across + x] = true
                }
            }
        }
        var ruledAcross = [Bool](repeating: false, count: across * (down + 1))
        var ruledDown = [Bool](repeating: false, count: (across + 1) * down)
        var bowls: [Bowl] = []

        for patch in patches {
            let size = patch.isFine ? 1 : 2
            let wide = patch.columns * 2 / size, tall = patch.rows * 2 / size
            // The letters of a patch run along its rows or down its columns.
            let alongRows = random() < 0.5
            let outer = alongRows ? tall : wide, inner = alongRows ? wide : tall
            for line in 0 ..< outer {
                var step = 0
                while step < inner {
                    // One choice of bowls, repeated for a run of cells.
                    let sides: [Int]
                    switch Int(random(0, 10)) {
                    case 0 ..< 3: sides = [0, 2]
                    case 3 ..< 6: sides = [1, 3]
                    default: sides = [Int(random(0, 4))]
                    }
                    let run = 1 + Int(random(0, 5))
                    for _ in 0 ..< run where step < inner {
                        let i = alongRows ? step : line, j = alongRows ? line : step
                        step += 1
                        let x = 2 * patch.column + i * size, y = 2 * patch.row + j * size
                        guard !open[y * across + x] else { continue }
                        for k in 0 ..< size {
                            ruledAcross[y * across + x + k] = true
                            ruledAcross[(y + size) * across + x + k] = true
                            ruledDown[(y + k) * (across + 1) + x] = true
                            ruledDown[(y + k) * (across + 1) + x + size] = true
                        }
                        let left = origin.x + Double(x) * half, up = origin.y + Double(y) * half
                        let side = Double(size) * half, radius = side / 2
                        for edge in sides {
                            // The bowl stands on this side and swells into the cell.
                            let center: Vector2, start: Double
                            switch edge {
                            case 0: center = Vector2(left + radius, up); start = 0
                            case 1: center = Vector2(left + side, up + radius); start = .pi / 2
                            case 2: center = Vector2(left + radius, up + side); start = .pi
                            default: center = Vector2(left, up + radius); start = -.pi / 2
                            }
                            bowls.append(Bowl(center: center, radius: radius, start: start,
                                              isFilled: random() < filled * (size == 2 ? 1.8 : 0.75)))
                        }
                    }
                }
            }
        }

        // Join the ruled pieces into whole strokes.
        var lines: [(Vector2, Vector2)] = []
        for y in 0 ... down {
            var from: Int?
            for x in 0 ... across {
                let ruled = x < across && ruledAcross[y * across + x]
                if ruled, from == nil { from = x }
                if !ruled, let start = from {
                    lines.append((Vector2(origin.x + Double(start) * half, origin.y + Double(y) * half),
                                  Vector2(origin.x + Double(x) * half, origin.y + Double(y) * half)))
                    from = nil
                }
            }
        }
        for x in 0 ... across {
            var from: Int?
            for y in 0 ... down {
                let ruled = y < down && ruledDown[y * (across + 1) + x]
                if ruled, from == nil { from = y }
                if !ruled, let start = from {
                    lines.append((Vector2(origin.x + Double(x) * half, origin.y + Double(start) * half),
                                  Vector2(origin.x + Double(x) * half, origin.y + Double(y) * half)))
                    from = nil
                }
            }
        }
        return Band(lines: lines, bowls: bowls, top: origin.y, rows: rows)
    }

    // MARK: - Words

    /// One sign of a word, drawn in a box one unit tall: its strokes, and
    /// how far the pen moves on to the next sign.
    private struct Sign {
        var marks: [Mark]
        var advance: Double
    }

    /// The signs. Each is a D or a B, or two of them set together.
    private func sign(_ index: Int) -> Sign {
        let quarter = Double.pi / 2
        func stem(_ x: Double) -> Mark { .line(Vector2(x, 0), Vector2(x, 1)) }
        func bar(_ y: Double, _ from: Double, _ to: Double) -> Mark { .line(Vector2(from, y), Vector2(to, y)) }
        /// A bowl swelling right or left from a stem, or up or down from a bar.
        func right(_ x: Double, _ y: Double, _ r: Double) -> Mark { .arc(center: Vector2(x, y), radius: r, start: -quarter) }
        func left(_ x: Double, _ y: Double, _ r: Double) -> Mark { .arc(center: Vector2(x, y), radius: r, start: quarter) }
        func up(_ x: Double, _ y: Double, _ r: Double) -> Mark { .arc(center: Vector2(x, y), radius: r, start: .pi) }
        func down(_ x: Double, _ y: Double, _ r: Double) -> Mark { .arc(center: Vector2(x, y), radius: r, start: 0) }
        let gap = 0.14
        switch index {
        case 0: // D
            return Sign(marks: [stem(0), right(0, 0.5, 0.5)], advance: 0.5)
        case 1: // D turned to face left
            return Sign(marks: [stem(0.5), left(0.5, 0.5, 0.5)], advance: 0.5)
        case 2: // B
            return Sign(marks: [stem(0), right(0, 0.25, 0.25), right(0, 0.75, 0.25)], advance: 0.25)
        case 3: // B turned to face left
            return Sign(marks: [stem(0.25), left(0.25, 0.25, 0.25), left(0.25, 0.75, 0.25)], advance: 0.25)
        case 4: // two D's face to face, their bowls touching
            return Sign(marks: [stem(0), right(0, 0.5, 0.5), stem(1), left(1, 0.5, 0.5)], advance: 1)
        case 5: // two D's back to back: a ring with a doubled stroke through it
            return Sign(marks: [stem(0.5), left(0.5, 0.5, 0.5), stem(0.5 + gap), right(0.5 + gap, 0.5, 0.5)],
                        advance: 1 + gap)
        case 6: // a D lying on its back over one lying on its face
            let r = 0.5 - gap / 2
            return Sign(marks: [bar(r, 0, 2 * r), up(r, r, r), bar(r + gap, 0, 2 * r), down(r, r + gap, r)],
                        advance: 2 * r)
        case 7: // a B lying on its back over one lying on its face
            let r = 0.25
            return Sign(marks: [bar(0.5 - gap / 2, 0, 1), up(r, 0.5 - gap / 2, r), up(3 * r, 0.5 - gap / 2, r),
                                bar(0.5 + gap / 2, 0, 1), down(r, 0.5 + gap / 2, r), down(3 * r, 0.5 + gap / 2, r)],
                        advance: 1)
        default: // two lying D's, one hanging and one standing, bowls touching
            return Sign(marks: [bar(0, 0, 1), down(0.5, 0, 0.5), bar(1, 0, 1), up(0.5, 1, 0.5)], advance: 1)
        }
    }

    /// Writes a word to fill a box: a row of signs along its longer side,
    /// or two rows when the box is nearly square and large enough.
    private func word(in box: Rectangle, pad: Double) -> Word {
        let upright = box.height > box.width
        let long = max(box.width, box.height) - 2 * pad, short = min(box.width, box.height) - 2 * pad
        let rows = short > 0.62 * long && short > 0.07 * width ? 2 : 1
        let between = 0.16
        let tall = (short - Double(rows - 1) * between * short / Double(rows)) / Double(rows)
        var marks: [Mark] = []
        for row in 0 ..< rows {
            // Signs until the row is full.
            let room = long / tall
            var signs: [Sign] = []
            var length = 0.0
            var tries = 0
            while tries < 40 {
                tries += 1
                let next = sign(Int(random(0, 9)))
                let more = length + next.advance + (signs.isEmpty ? 0 : between)
                if more > room { continue }
                signs.append(next)
                length = more
                if room - length < 0.25 + between { break }
            }
            if signs.isEmpty { signs = [sign(2)]; length = 0.25 }
            // Center the row, and turn it a quarter when the box is upright.
            var pen = (room - length) / 2
            let across = Double(row) * tall * (1 + between)
            for one in signs {
                for mark in one.marks {
                    func place(_ p: Vector2) -> Vector2 {
                        let along = (pen + p.x) * tall, off = across + p.y * tall
                        return upright
                            ? Vector2(box.x + box.width - pad - off, box.y + pad + along)
                            : Vector2(box.x + pad + along, box.y + pad + off)
                    }
                    switch mark {
                    case .line(let from, let to):
                        marks.append(.line(place(from), place(to)))
                    case .arc(let center, let radius, let start):
                        marks.append(.arc(center: place(center), radius: radius * tall,
                                          start: start + (upright ? .pi / 2 : 0)))
                    }
                }
                pen += one.advance + between
            }
        }
        return Word(marks: marks)
    }
}

↑↓ move ↩ open