# Strands

the bent strands of one ruled sheet of the 1970s.

Run it with `swift run --package-path Examples Example-Recreations-NasreenMohamedi-Strands`.

```swift
//  Recreation after Nasreen Mohamedi - an untitled ink and graphite drawing
//  of the 1970s, one of the small square sheets Talwar Gallery showed in "the
//  grid, unplugged" (New York, 2008 to 2009): Untitled, ca. 1970s, ink and
//  graphite on paper, 7 1/2 x 7 1/2 in., TG 1640, read beside two sheets of
//  the same show and size, TG 1629 and TG 1631. Every work of hers is
//  untitled, so nothing here is named after one. A homage, not a
//  reproduction, and not affiliated with or endorsed by the artist or her
//  estate.
//  https://www.talwargallery.com/artists/nasreen-mohamedi
//  https://www.talwargallery.com/exhibitions/nasreen-mohamedi6
//  https://artreview.com/september-2016-review-nasreen-mohamedi/
//
//  An original Ollin interpretation. No statement of a rule for this sheet
//  was found, hers or anyone's: the rule below was read off the gallery's
//  picture of it, by measuring where its lines stand. Nothing was ported: the
//  work is a ruling pen and a pencil on paper.

import Foundation
import Ollin

/// The strands of a ruled sheet of the 1970s (Nasreen Mohamedi, Baroda).
/// Joshua Mack, reviewing her retrospective in 2016, wrote that in 1970 she
/// "began drawing vertical and diagonal lines across horizontal registers".
/// This sheet shows that at its clearest. It is ruled edge to edge with
/// horizontals at one even pitch, about 120 of them. Heavy bars cut them
/// into registers: two ink lines with a band of graphite between. Faint
/// pencil verticals stand under the ink, the guides she ruled first. Across
/// each register run strands, thin ink lines that bend, and in the middle
/// register they meet in a row of arrowheads.
///
/// Measuring the sheet gives the rule. It is one sum used twice: 1, then
/// 1 + 2, then 1 + 2 + 3.
///
/// - The guides gather on one vertical. The first stands one unit from it,
///   the next two units farther, the next three, the same on both sides. On
///   the sheet the unit is two line pitches. The guides sit within 3 parts
///   in 2,000 of where that puts them.
/// - A strand starts where a guide crosses a ruled line and takes three
///   steps. Each step crosses to the next guide. The first step moves one
///   ruled line, the second two, the third three. So every corner of a
///   strand sits on a crossing, and the pen left a dot at each.
/// - A strand starts at every second guide. It lands on a heavy line, the
///   one on the side of its register that faces the middle. Strands above
///   the middle fall as they go, strands below it rise.
/// - The middle register is two strands tall and is ruled only where a
///   strand turns. Its strands land on its middle line from both sides, and
///   those are the arrowheads.
///
/// The rule predicts 209 steps on the sheet, and 199 of them can be found
/// in the picture. The other 10 lie along a ruled line or in the crowd at
/// the gathering line, where the test cannot tell. One row does not obey:
/// the lowest, half cut off by the paper's edge, lands on a fine line.
///
/// The guides crowd toward one line and the steps grow as they go. So the
/// straight pieces read as curves, and the flat sheet seems to tilt away.
/// This sketch keeps the rule and deals the registers. It moves the way a
/// floor moves for someone walking past it: the line the guides gather on
/// travels across the sheet and back once a lap, and every strand follows
/// its guides. At every frame the corners still sit on crossings.
///
/// Try it: `travel` is how far the gathering line walks (0 holds the sheet),
/// and `seconds` is the lap and the export loop. `gather` is where the line
/// rests, `unit` is the guides' unit in line pitches, and `steps` is how
/// many steps a strand takes. `lines` is how many pitches the sheet is
/// ruled in, `mirrored` turns the sheet left to right, and `guides` shows
/// or hides the pencil. The seed deals the registers and which guides the
/// strands start from.
///
/// Every line exports as a line and every strand as one bent stroke, so
/// `--export-svg` gives the sheet back for a pen.
@main
final class Strands: Sketch {
    /// How many steps a strand takes. Each step moves one ruled line more
    /// than the last. The measured sheet takes 3.
    @Param(2 ... 5, icon: "stairs") var steps = 3
    /// The guides' unit, in line pitches. Guide number k stands this many
    /// pitches times 1 + 2 + ... + k from the gathering line. The measured
    /// sheet has 2.
    @Param(1 ... 4, icon: "arrow.left.and.right") var unit = 2.0
    /// Where the gathering line rests, as a share of the sheet's width. The
    /// measured sheet has it a little left of the middle.
    @Param(0 ... 1, icon: "scope") var gather = 0.475
    /// How far the gathering line walks over one lap. 0 holds the sheet
    /// still.
    @Param(0 ... 1, icon: "figure.walk") var travel = 0.5
    /// Seconds for one lap, there and back. It is also the export loop.
    @Param(8 ... 30, icon: "clock") var seconds = 24.0
    /// How many line pitches the sheet's height is ruled in. The measured
    /// sheet has 120.
    @Param(72 ... 160, icon: "line.3.horizontal") var lines = 120
    /// Turns the sheet left to right, so the strands run the other way.
    @Param(icon: "arrow.left.arrow.right") var mirrored = false
    /// The pencil guides, ruled first and left under the ink.
    @Param(icon: "grid") var guides = true

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

    /// The paper's margin: no ink crosses it.
    private let margin = 60.0
    /// The weights of the four kinds of line, in canvas pixels.
    private let heavyWeight = 1.6
    private let fineWeight = 1.1
    private let strandWeight = 0.8
    private let guideWeight = 0.5
    /// The dot the pen leaves where it rests at a corner.
    private let restWeight = 2.0
    /// The graphite band in a bar, in line pitches from the heavy line a
    /// strand lands on. Measured on four bars of the sheet.
    private let bandPlace = (from: 0.9, to: 1.7)
    /// The gathering line walks this share of the width to each side at
    /// full `travel`.
    private let walk = 0.3

    private let paper = Color(hex: 0xE3DAC3)
    private let ink = Color(hex: 0x473A2C)
    private let strandInk = Color(hex: 0x5A4E40)
    private let graphite = Color(hex: 0xAFA794)
    private let wash = Color(hex: 0x9F9886)
    private let pencil = Color(hex: 0xCDC4AE)

    /// What stands on one pitch of the sheet.
    private enum Ruling { case nothing, fine, heavy }

    /// A row of strands: the pitch its strands start on, and which way they
    /// move from there (1 down the sheet, -1 up it).
    private struct Row {
        var start: Int
        var toward: Int
    }

    /// 1 + 2 + ... + n, the reach of n steps.
    private func reach(_ n: Int) -> Int { n * (n + 1) / 2 }

    override func draw() {
        background(paper)
        noFill()
        strokeCap(.butt)
        strokeJoin(.round)
        randomSeed(variation)

        // The field is where a line's center may go; the heaviest line's
        // half width keeps every stroke inside the margin.
        let x0 = margin + heavyWeight / 2, x1 = width - margin - heavyWeight / 2
        let y0 = margin + heavyWeight / 2, y1 = height - margin - heavyWeight / 2
        let pitch = (y1 - y0) / Double(lines)
        let landing = reach(steps)
        func y(_ index: Double) -> Double { y0 + index * pitch }

        // 1. Deal the sheet. Every pitch is ruled fine until something else
        //    is put there. The deal never reads the clock.
        var ruled = [Ruling](repeating: .fine, count: lines + 1)
        var bands: [(from: Double, to: Double)] = []
        var rows: [Row] = []
        func rule(_ index: Int, _ ruling: Ruling) {
            if ruled.indices.contains(index) { ruled[index] = ruling }
        }

        // The middle register: two strands tall, ruled only where a strand
        // turns, heavy at both sides.
        let middle = Int((Double(lines) * random(0.44, 0.56)).rounded())
        let top = middle - landing, bottom = middle + landing
        for index in top ... bottom { rule(index, .nothing) }
        for step in 0 ... steps {
            rule(top + reach(step), .fine)
            rule(bottom - reach(step), .fine)
        }
        rule(top, .heavy)
        rule(bottom, .heavy)
        rows.append(Row(start: top, toward: 1))
        rows.append(Row(start: bottom, toward: -1))

        // The registers above it and below it, dealt outward until they
        // leave the sheet. Each is some spare ruled lines, a bar, and then
        // the strands, which land on the bar's line that faces the middle.
        for side in [-1, 1] {
            var edge = side < 0 ? top : bottom
            var isFirst = true
            while edge >= 0 && edge <= lines {
                var lands = edge
                // The first register on a side may land on the middle
                // register's own heavy line, with no bar between.
                let sharesLine = isFirst && random(1) < 0.4
                if !sharesLine {
                    let spare = Int(random(isFirst ? 2 : 1, 7))
                    let isThin = random(1) < 0.25
                    let inner = edge + side * spare
                    lands = inner + side * (isThin ? 1 : 3)
                    rule(inner, .heavy)
                    rule(lands, .heavy)
                    // A bar the sheet's edge cuts keeps its ruled lines and
                    // gets no band.
                    if !isThin, ruled.indices.contains(lands) {
                        rule(inner + side, .nothing)
                        rule(inner + 2 * side, .nothing)
                        let a = Double(lands) - Double(side) * bandPlace.from
                        let b = Double(lands) - Double(side) * bandPlace.to
                        bands.append((from: min(a, b), to: max(a, b)))
                    }
                }
                edge = lands + side * landing
                rows.append(Row(start: edge, toward: -side))
                isFirst = false
            }
        }
        // Whether the strands start from the even guides or the odd ones,
        // and which way they run as they near the line they land on.
        let parity = random(1) < 0.5 ? 0 : 1
        let heading = mirrored ? -1 : 1

        // 2. The guides. They gather on one vertical, which walks across the
        //    sheet and back once a lap.
        let phase = loopProgress(over: seconds) * 2 * .pi
        let home = x0 + (x1 - x0) * (gather + walk * travel * sin(phase))
        let step = unit * pitch
        func guide(_ k: Int) -> Double { home + Double(k.signum()) * step * Double(reach(abs(k))) }
        var farthest = 1
        while step * Double(reach(farthest)) < x1 - x0 { farthest += 1 }

        if guides {
            stroke(pencil)
            strokeWeight(guideWeight)
            for k in -farthest ... farthest {
                let x = guide(k)
                if x >= x0 && x <= x1 { drawLine(Vector2(x, y0), Vector2(x, y1)) }
            }
        }

        // 3. The ruling: the graphite bands, the fine lines, the heavy lines.
        //    A band is laid as strokes that touch, the way a soft pencil
        //    fills it.
        stroke(wash)
        strokeWeight(1.5)
        for band in bands {
            var at = y(band.from) + 0.75
            let end = y(band.to) - 0.75
            while at <= end + 1e-9 {
                if at >= y0 && at <= y1 { drawLine(Vector2(x0, at), Vector2(x1, at)) }
                at += 1.3
            }
        }
        stroke(graphite)
        strokeWeight(fineWeight)
        for index in 0 ... lines where ruled[index] == .fine {
            drawLine(Vector2(x0, y(Double(index))), Vector2(x1, y(Double(index))))
        }
        stroke(ink)
        strokeWeight(heavyWeight)
        for index in 0 ... lines where ruled[index] == .heavy {
            drawLine(Vector2(x0, y(Double(index))), Vector2(x1, y(Double(index))))
        }

        // 4. The strands. Each starts on a guide and a ruled line, crosses
        //    one guide a step, and moves one line more each step. The sheet's
        //    edge cuts the ones that run past it.
        stroke(strandInk)
        strokeWeight(strandWeight)
        var rests: [Vector2] = []
        for row in rows {
            for k in -(farthest + steps) ... farthest + steps where (k & 1) == parity {
                var corners: [Vector2] = []
                for turn in 0 ... steps {
                    corners.append(Vector2(guide(k + heading * turn),
                                           y(Double(row.start + row.toward * reach(turn)))))
                }
                for piece in inside(corners, x0: x0, y0: y0, x1: x1, y1: y1) {
                    drawPolyline(piece)
                    // The pen rests at the corners it reached, not where
                    // the sheet's edge cut the strand. Two strands that
                    // meet in an arrowhead share one rest.
                    for point in piece where corners.contains(where: { isSame($0, point) })
                        && !rests.contains(where: { isSame($0, point) }) {
                        rests.append(point)
                    }
                }
            }
        }

        // 5. Where the pen rested. On the sheet every corner of a strand
        //    carries a small dot of ink. A dot is drawn as the shortest of
        //    strokes with a round end, which is what a pen touching down is.
        strokeCap(.round)
        strokeWeight(restWeight)
        for rest in rests {
            drawLine(Vector2(rest.x - 0.1, rest.y), Vector2(rest.x + 0.1, rest.y))
        }
    }

    /// Two points that are one point, give or take the last bits of a sum.
    private func isSame(_ a: Vector2, _ b: Vector2) -> Bool {
        abs(a.x - b.x) < 1e-9 && abs(a.y - b.y) < 1e-9
    }

    /// The parts of a bent line that lie inside the box, each as its own
    /// bent line, so the pen stays down wherever the strand does.
    private func inside(_ corners: [Vector2],
                        x0: Double, y0: Double, x1: Double, y1: Double) -> [[Vector2]] {
        var pieces: [[Vector2]] = []
        var current: [Vector2] = []
        for index in 0 ..< corners.count - 1 {
            guard let (a, b) = clipped(corners[index], corners[index + 1],
                                       x0: x0, y0: y0, x1: x1, y1: y1) else {
                if current.count > 1 { pieces.append(current) }
                current = []
                continue
            }
            if let last = current.last, isSame(last, a) {
                current.append(b)
            } else {
                if current.count > 1 { pieces.append(current) }
                current = [a, b]
            }
        }
        if current.count > 1 { pieces.append(current) }
        return pieces
    }

    /// The part of the segment inside the box, or nil when none of it is.
    private func clipped(_ a: Vector2, _ b: Vector2,
                         x0: Double, y0: Double, x1: Double, y1: Double) -> (Vector2, Vector2)? {
        let d = b - a
        var enter = 0.0, leave = 1.0
        for (speed, room) in [(-d.x, a.x - x0), (d.x, x1 - a.x), (-d.y, a.y - y0), (d.y, y1 - a.y)] {
            if abs(speed) < 1e-12 {
                if room < 0 { return nil }
                continue
            }
            let t = room / speed
            if speed < 0 {
                if t > leave { return nil }
                enter = max(enter, t)
            } else {
                if t < enter { return nil }
                leave = min(leave, t)
            }
        }
        guard leave - enter > 1e-9 else { return nil }
        // An end the box does not cut is handed back as it came.
        return (enter == 0 ? a : a + d * enter, leave == 1 ? b : a + d * leave)
    }
}
```
