# IdeiaVisivel

twenty-one straight lines, each stopped by one drawn before it, after Cordeiro's Idéia visível (1956).

Run it with `swift run --package-path Examples Example-Recreations-WaldemarCordeiro-IdeiaVisivel`.

```swift
//  Recreation after Waldemar Cordeiro - Idéia visível (Visible idea, 1956),
//  industrial latex paint on a plywood laminate panel, 100.3 x 100.5 cm. It
//  is in the Adolpho Leirner Collection of Brazilian Constructive Art at the
//  Museum of Fine Arts, Houston. He gave the same title to several works from
//  1956 on, and this is the one in black lines on white. A homage, not a
//  reproduction, and not affiliated with or endorsed by the artist's estate
//  or the museum.
//  https://artsandculture.google.com/asset/id%C3%A9ia-vis%C3%ADvel/hwGyJT6nWJvR9w
//  https://www.waldemarcordeiro.com/concrete
//
//  An original Ollin interpretation, read off the museum's picture of the
//  painting. No account of how he ruled it was found. The stopping rule and
//  the measures below are what the picture shows, made regular. Nothing was
//  ported: the painting was ruled by hand.

import Foundation
import Ollin

/// Visible idea (Waldemar Cordeiro, São Paulo, 1956): twenty-one straight
/// black lines on a white square. The museum that holds it calls it "a visual
/// ideogram featuring the progressive repetition of vanishing lines that play
/// with the viewer's perception". The lines read as a floor and a ceiling
/// falling away from the eye. The next moment they are flat bands that fold
/// over each other.
///
/// The picture gives up how it was made. Every line starts on the edge of the
/// panel and stops on another line, so that other line was there first. That
/// fixes the order within each half. A level line goes across the middle.
/// Then pairs of lines come in from the two sides, each pair steeper than the
/// last. In the upper half the line from the left runs on past its partner
/// until it meets the pair before. The line from the right stops on its
/// partner. The first long line has no pair before it, and it runs to the far
/// end of the level line. The lower half is the upper half turned half a
/// turn.
///
/// Measured on the picture, the pairs cross the upright middle axis at even
/// steps, 7 percent of the side apart. Their angles rise by about the same
/// amount each time, near 5.3 degrees. This sketch draws that regular figure.
/// Pair number k crosses the axis k times `axisStep` above the middle, with
/// both lines k times `turn` from level. With those two measures the fifth
/// pair leaves the top edge a fifth of the way in from each corner. The
/// painting's does too. His own lines were ruled by hand. Their ends sit
/// 1.5 percent of the side from these on the median, and 4.3 percent at
/// worst. The hand's departures are not copied.
///
/// A lap opens on the finished painting. The lines draw back to the edge in
/// the reverse of their order. Then the pen rules them again at a steady
/// pace, each one running until it is stopped.
///
/// Try it: `pairs` at 3 or 6 is a shallower or a deeper fall. `turn` opens
/// and closes the fan, and `axisStep` spreads the pairs along the middle.
/// Turn `stopsAtLines` off to see every line run from edge to edge, which is
/// the figure the stopping rule cuts. `--export-svg` gives the lines as
/// strokes for a pen.
@main
final class IdeiaVisivel: Sketch {
    /// How many pairs of lines each half holds. The painting has five.
    @Param(1 ... 6, icon: "line.3.horizontal") var pairs = 5
    /// How far apart the pairs cross the middle axis, as a part of the side.
    @Param(0.04 ... 0.1, icon: "arrow.up.and.down") var axisStep = 0.07
    /// How much steeper each pair is than the one before, in degrees.
    @Param(3 ... 8, icon: "angle") var turn = 5.3
    /// Whether a line stops on the first line it meets. Off, every line runs
    /// from edge to edge.
    @Param(icon: "scissors") var stopsAtLines = true
    /// Seconds for one lap: the painting, the lines drawn back, and ruled again.
    @Param(12 ... 30, icon: "timer") var seconds = 20.0

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

    private let ground = Color(hex: 0xE1E1DC)
    private let paint = Color(hex: 0x3A3E40)
    /// The width of a line as a part of the side, measured on the picture.
    private let lineWidth = 0.0049

    /// One ruled line, from where the pen starts on the edge to where it
    /// stops. Points are in sides of the panel from its middle, x to the
    /// right and y upward.
    struct Rule {
        var from: Vector2
        var to: Vector2
        var length: Double { (to - from).length }
        /// The same line in the other half, turned half a turn.
        var turned: Rule { Rule(from: from * -1, to: to * -1) }
    }

    // MARK: - The figure

    /// The lines in the order they must have been drawn, in groups that are
    /// ruled together. The level line comes first. Then each pair gives two
    /// groups: its long line with that line's twin in the lower half, and its
    /// short line with its twin.
    private func figure() -> [[Rule]] {
        let level = Rule(from: Vector2(-0.5, 0), to: Vector2(0.5, 0))
        var groups = [[level]]
        // The lines a new line of the upper half can run into.
        var standing = [level]

        for k in 1 ... max(pairs, 1) {
            let mark = Double(k) * axisStep
            let slope = tan(Double(k) * turn * .pi / 180)
            guard mark < 0.5, slope > 0 else { break }
            // Where a line through the mark at this slope leaves the panel:
            // on the side edge, or on the top edge when it is steep.
            let side = mark + 0.5 * slope
            let reach = side <= 0.5 ? Vector2(0.5, side) : Vector2((0.5 - mark) / slope, 0.5)

            // The long line comes from the left and falls to the right.
            let longStart = Vector2(-reach.x, reach.y)
            var longEnd = exit(from: longStart, toward: Vector2(1, -slope))
            if k == 1 {
                // Nothing stands in its way yet: it runs to the far end of
                // the level line.
                longEnd = level.to
            } else if stopsAtLines {
                longEnd = stop(from: longStart, toward: Vector2(1, -slope), at: standing) ?? longEnd
            }
            let long = Rule(from: longStart, to: longEnd)
            standing.append(long)
            groups.append([long, long.turned])

            // The short line comes from the right and falls to the left.
            var shortEnd = exit(from: reach, toward: Vector2(-1, -slope))
            if stopsAtLines {
                shortEnd = stop(from: reach, toward: Vector2(-1, -slope), at: standing) ?? shortEnd
            }
            let short = Rule(from: reach, to: shortEnd)
            standing.append(short)
            groups.append([short, short.turned])
        }
        return groups
    }

    /// Where a line from `start` heading `toward` first meets one of the
    /// lines already standing, if it meets any.
    private func stop(from start: Vector2, toward: Vector2, at standing: [Rule]) -> Vector2? {
        var nearest: Double?
        for rule in standing {
            let along = rule.to - rule.from
            let cross = toward.x * along.y - toward.y * along.x
            guard abs(cross) > 1e-12 else { continue }
            let gap = rule.from - start
            let t = (gap.x * along.y - gap.y * along.x) / cross
            let s = (gap.x * toward.y - gap.y * toward.x) / cross
            // A meeting counts a little way past the start, so a line does
            // not stop on the edge it leaves from.
            guard t > 1e-6, s >= -1e-9, s <= 1 + 1e-9 else { continue }
            if nearest == nil || t < nearest! { nearest = t }
        }
        return nearest.map { start + toward * $0 }
    }

    /// Where a line from `start` heading `toward` leaves the panel when
    /// nothing stops it.
    private func exit(from start: Vector2, toward: Vector2) -> Vector2 {
        var t = Double.infinity
        if toward.x > 0 { t = min(t, (0.5 - start.x) / toward.x) }
        if toward.x < 0 { t = min(t, (-0.5 - start.x) / toward.x) }
        if toward.y < 0 { t = min(t, (-0.5 - start.y) / toward.y) }
        return start + toward * t
    }

    // MARK: - The frame

    override func draw() {
        let groups = figure()
        let side = min(width, height)
        background(ground)

        // The lap: the painting, the lines drawn back to the edge last one
        // first, a bare panel, and the ruling. The pen keeps one pace, so a
        // group takes the share of the time that its length is of the whole.
        let lap = loopProgress(over: seconds)
        let lengths = groups.map { $0[0].length }
        let whole = lengths.reduce(0, +)
        var before = [Double](repeating: 0, count: groups.count)
        for i in groups.indices.dropFirst() {
            before[i] = before[i - 1] + lengths[i - 1]
        }
        let ruled: Double       // the length ruled so far, of `whole`
        switch lap {
        case ..<0.14: ruled = whole
        case ..<0.34: ruled = whole * (1 - ease((lap - 0.14) / 0.2))
        case ..<0.38: ruled = 0
        case ..<0.92: ruled = whole * (lap - 0.38) / 0.54
        default: ruled = whole
        }

        noFill()
        stroke(paint)
        strokeCap(.butt)
        strokeWeight(lineWidth * side)
        for (i, group) in groups.enumerated() {
            let part = lengths[i] > 0 ? clamp((ruled - before[i]) / lengths[i], 0, 1) : 0
            guard part > 0 else { continue }
            for rule in group {
                // A line starts a little outside the panel, so its square
                // end is cut by the edge. A pen plan starts on the edge.
                let heading = (rule.to - rule.from) / max(rule.length, 1e-9)
                let start = isVectorExporting ? rule.from : rule.from - heading * (2 * lineWidth)
                let end = rule.from + (rule.to - rule.from) * part
                drawLine(onCanvas(start, side), onCanvas(end, side))
            }
        }
    }

    /// A point of the panel on the canvas.
    private func onCanvas(_ p: Vector2, _ side: Double) -> Vector2 {
        Vector2(width / 2 + p.x * side, height / 2 - p.y * side)
    }

    /// A slow start and a slow stop.
    private func ease(_ t: Double) -> Double { t * t * (3 - 2 * t) }
}
```
