# EspiralDeArquimedes

a spiral and the ruled circles that find it, after Cordeiro's Desenvolvimento óptico da espiral de Arquimedes (1952).

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

```swift
//  Recreation after Waldemar Cordeiro - Desenvolvimento óptico da espiral de
//  Arquimedes (Optical development of the spiral of Archimedes, 1952), enamel
//  on plywood, 71 x 60.5 cm, private collection. It hung in the Ruptura
//  group's first exhibition, at the Museu de Arte Moderna de São Paulo in
//  1952. The museum showed it again in 2022. A homage, not a reproduction,
//  and not affiliated with or endorsed by the artist's estate or the museum.
//  https://www.waldemarcordeiro.com/concrete
//  https://mam.org.br/wp-content/uploads/2022/11/ruptura-catalogo-ingles-2022-07-26.pdf
//
//  An original Ollin interpretation, written from the estate's picture of the
//  painting and from the two curators' accounts of it in the 2022 catalog.
//  Every measure here was read off that picture. No published account gives
//  them. Nothing was ported: the painting was ruled by hand.

import Foundation
import Ollin

/// The optical development of the spiral of Archimedes (Waldemar Cordeiro, São
/// Paulo, 1952). A spiral of Archimedes is the curve a point draws when it
/// turns about a center and moves away from it at one steady pace. Its turns
/// are the same distance apart all the way out.
///
/// Cordeiro showed the curve together with the drawing that finds it. Heloisa
/// Espada was one of the two curators of the 2022 exhibition. She describes a
/// part of the spiral set inside concentric circles and half circles. They
/// are in very thin lines, ruled with a compass and a ruling pen. A yellow
/// disk sits at the foot of the circles. Yuri Quevedo, the other curator,
/// reads the spiral as the path of that disk. It travels from the inside to
/// the outside, from one circle to the next.
///
/// The measures below come from the estate's picture. One small length runs
/// through all of it, called a unit here. The spiral moves out one unit for
/// each of the `divisions` of a turn, twelve in the painting. It starts half a
/// turn's growth from the center and makes `turns` turns, two in the painting.
/// A straight stroke down the middle joins its two ends into one closed red
/// band. Fitted to the picture, the band is the true spiral and not the
/// draftsman's shortcut of half circles struck from two centers. The true
/// curve lies more than three times closer to the painted band than the
/// shortcut does.
///
/// The thin lines come in four sets. Ten green circles about the center lie
/// one unit apart, two fewer than the `divisions`. Each runs from the upright
/// stroke until it meets the spiral, so their ends are a twelfth of a turn
/// apart. A geometry book finds this spiral the same way, with circles one
/// step apart and a turn cut into equal parts. Ten orange circles ring the
/// outside. The inner five are only drawn where they clear the spiral, on
/// the lower left. Five gray circles repeat one circle with its center moved
/// a unit at a time down the middle. Five lilac circles grow from the yellow
/// disk, all touching the outermost orange circle at its lowest point.
///
/// A lap opens on the finished painting. Then the ground clears and the
/// compass rules the thin circles again. The disk sets out where the spiral
/// starts and travels along the ends of the green arcs. The red band is its
/// track. It comes to rest at the foot of the outermost circle.
///
/// Try it: `divisions` at 8 or 16 changes how fast the spiral opens, and the
/// thin circles follow. `turns` at 1 or 3 is a shorter or a longer journey.
/// `construction` at 0 leaves the red band and the disk alone. `--export-svg`
/// gives every circle and the band as strokes.
@main
final class EspiralDeArquimedes: Sketch {
    /// How many equal parts a turn is cut into. The spiral moves out one unit
    /// for each part.
    @Param(8 ... 24, icon: "circle.dotted") var divisions = 12
    /// How many turns the spiral makes before the upright stroke closes it.
    @Param(1 ... 3, icon: "arrow.clockwise") var turns = 2
    /// How strongly the thin ruled circles show. At 0 only the red band and
    /// the yellow disk are left.
    @Param(0 ... 1, icon: "pencil.and.ruler") var construction = 0.8
    /// Seconds for one lap: the painting, the bare ground, and the drawing.
    @Param(12 ... 30, icon: "timer") var seconds = 24.0

    // The panel is 60.5 cm wide and 71 cm high.
    override var canvasSize: CanvasSize { .size(1080, 1268) }
    override var loopDuration: Double? { seconds }

    private let ground = Color(hex: 0xE3DACD)
    private let red = Color(hex: 0xB5401F)
    private let orange = Color(hex: 0xC8693F)
    private let green = Color(hex: 0x4C7A55)
    private let gray = Color(hex: 0x7F8792)
    private let lilac = Color(hex: 0xB9A6C2)
    private let yellow = Color(hex: 0xDBA534)

    /// The outermost circle's radius on the canvas, in pixels. In the
    /// picture it is 0.382 of the panel's width.
    private let reach = 413.0

    // Measures read off the picture, in units. In the painting a unit is
    // close to two thirds of a centimeter.
    /// How far outside the spiral's start the first green circle lies.
    private let greenInset = 1.65
    /// How far inside the spiral's outer end the first orange circle lies.
    private let orangeInset = 4.55
    /// The yellow disk's radius.
    private let diskRadius = 3.8
    /// How much smaller the gray circle is than the innermost orange one.
    private let grayInset = 0.25
    /// The width of the red band.
    private let bandWidth = 0.69

    // MARK: - The figure

    /// Everything the frame needs, worked out once from the parameters.
    private struct Figure {
        var unit: Double
        var start: Double       // the spiral's radius where it begins
        var end: Double         // and where it ends
        var perDegree: Double   // units the spiral moves out per degree
        var sweep: Double       // degrees the spiral turns in all
        var orange: [Double]    // the ten orange radii, inside out
        var greens: [Double]    // the green radii, inside out
        var grayRadius: Double
        var foot: Double        // the outermost circle's lowest point, below the center
    }

    private func figure() -> Figure {
        let parts = Double(max(divisions, 2))
        let start = parts / 2
        let end = start + parts * Double(turns)
        let orange = (0 ..< 10).map { end - orangeInset + Double($0) }
        let greens = (0 ..< max(divisions - 2, 0)).map { start + greenInset + Double($0) }
        return Figure(unit: reach / orange[9], start: start, end: end, perDegree: parts / 360,
                      sweep: 360 * Double(turns), orange: orange, greens: greens,
                      grayRadius: orange[0] - grayInset, foot: orange[9])
    }

    /// A point `radius` units from the center, `degrees` clockwise from
    /// straight up.
    private func place(_ radius: Double, _ degrees: Double, _ f: Figure, center: Vector2 = .zero) -> Vector2 {
        let a = degrees * .pi / 180
        return Vector2(width / 2 + (center.x + radius * sin(a)) * f.unit,
                       height / 2 + (center.y - radius * cos(a)) * f.unit)
    }

    /// An arc as points close enough together to read as a curve. It turns
    /// about `center` (in units from the middle), clockwise from `from`
    /// degrees through `sweep` degrees.
    private func arc(_ radius: Double, from: Double, sweep: Double, _ f: Figure,
                     center: Vector2 = .zero) -> [Vector2] {
        guard sweep > 0 else { return [] }
        let steps = max(2, Int((sweep / 1.5).rounded(.up)))
        return (0 ... steps).map { place(radius, from + sweep * Double($0) / Double(steps), f, center: center) }
    }

    /// Rules a circle from its foot round clockwise, as much of it as `part`
    /// says. A whole one is closed, and a pen plan gets it as a true circle.
    private func rule(_ radius: Double, part: Double, _ f: Figure, center: Vector2 = .zero) {
        guard part > 0 else { return }
        if part >= 1, isVectorExporting {
            let middle = place(0, 0, f, center: center)
            drawCircle(middle.x, middle.y, radius * f.unit)
        } else if part >= 1 {
            drawPolyline(Array(arc(radius, from: 180, sweep: 360, f, center: center).dropLast()), closed: true)
        } else {
            drawPolyline(arc(radius, from: 180, sweep: 360 * part, f, center: center))
        }
    }

    /// The spiral's radius after it has turned `degrees`.
    private func spiral(_ degrees: Double, _ f: Figure) -> Double { f.start + degrees * f.perDegree }

    // MARK: - The frame

    override func draw() {
        let f = figure()
        let lap = loopProgress(over: seconds)
        background(ground)

        // The lap: the finished painting, the ground cleared, then the
        // drawing made again in the order the construction asks.
        let shown = lap < 0.12 ? 1.0 : (lap < 0.18 ? 1 - smoothstep(0.12, 0.18, lap) : 1.0)
        let drawing = lap >= 0.18
        func made(_ from: Double, _ to: Double) -> Double {
            if !drawing { return 1 }
            return clamp((lap - from) / (to - from), 0, 1)
        }
        /// A set of lines ruled one after another inside a stretch of the
        /// lap, each taking twice its share so neighbors overlap.
        func turn(_ index: Int, of count: Int, _ from: Double, _ to: Double) -> Double {
            let share = (to - from) / Double(count + 1)
            return ease(made(from + share * Double(index), from + share * Double(index + 2)))
        }

        noFill()
        strokeCap(.butt)
        strokeJoin(.round)
        // The thin circles are hairlines in the painting, a ruling pen's.
        strokeWeight(1.25)

        // The concentric circles first. The outer five orange ones are whole.
        // The inner five start at the foot and stop where the spiral passes.
        for (j, radius) in f.orange.enumerated() {
            let part = turn(9 - j, of: 10, 0.2, 0.31)
            stroke(orange.withAlpha(construction * shown))
            if j >= 5 {
                rule(radius, part: part, f)
            } else {
                // The spiral reaches this radius partway through its last
                // half turn, which runs up the left side.
                let meets = (radius - spiral(f.sweep - 180, f)) / f.perDegree
                drawPolyline(arc(radius, from: 180, sweep: clamp(meets, 0, 180) * part, f))
            }
        }

        // The green circles: each from the upright stroke round to the place
        // where the spiral has grown out to meet it.
        for (k, radius) in f.greens.enumerated() {
            let part = turn(k, of: f.greens.count, 0.3, 0.41)
            stroke(green.withAlpha(construction * shown))
            drawPolyline(arc(radius, from: 0, sweep: (radius - f.start) / f.perDegree * part, f))
        }

        // One circle, struck again and again with the compass point moved a
        // unit down the middle. Each touches an orange circle at its foot.
        for k in 0 ..< 5 {
            let part = turn(k, of: 5, 0.4, 0.5)
            let down = f.orange[k] - f.grayRadius
            stroke(gray.withAlpha(construction * shown))
            rule(f.grayRadius, part: part, f, center: Vector2(0, down))
        }

        // The disk's journey: out along the spiral, then half a turn more to
        // its place at the foot of the outermost circle.
        let rest = f.foot - diskRadius
        let traveled = drawing ? ease(made(0.5, 0.875)) * (f.sweep + 180) : f.sweep + 180
        let onSpiral = min(traveled, f.sweep)

        // The circles that grow from the disk, all touching at the foot.
        for j in 1 ... 5 {
            let part = turn(j - 1, of: 5, 0.875, 0.95)
            let radius = diskRadius + Double(j)
            stroke(lilac.withAlpha(construction * shown))
            rule(radius, part: part, f, center: Vector2(0, f.foot - radius))
        }

        // The red band: the spiral as far as the disk has gone. Then the
        // upright stroke joins its outer end back to its start.
        if onSpiral > 0 {
            var band: [Vector2] = []
            let steps = max(1, Int((onSpiral / 1.5).rounded(.up)))
            for s in 0 ... steps {
                let turned = onSpiral * Double(s) / Double(steps)
                band.append(place(spiral(turned, f), turned, f))
            }
            let closing = drawing ? made(0.8, 0.875) : 1
            if traveled >= f.sweep, closing > 0 {
                band.append(place(f.end - (f.end - f.start) * closing, 0, f))
            }
            stroke(red.withAlpha(shown))
            strokeWeight(bandWidth * f.unit)
            strokeJoin(.miter)
            drawPolyline(band, closed: closing >= 1)
        }

        // The yellow disk, on top of its own track.
        let at: Vector2
        if traveled <= f.sweep {
            at = place(spiral(traveled, f), traveled, f)
        } else {
            let past = (traveled - f.sweep) / 180
            at = place(f.end + (rest - f.end) * past, traveled, f)
        }
        // It fades in at the spiral's start as the journey begins.
        let arrived = drawing ? made(0.47, 0.5) : 1
        noStroke()
        fill(yellow.withAlpha(shown * arrived))
        drawCircle(at.x, at.y, diskRadius * f.unit)
    }

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