Ollin

Integrales

The cut ribbons of 1979, after Integrales II (Edgard Varèse).

Run
swift run --package-path Examples Example-Recreations-KazuyaSakai-Integrales
Source
Examples/Recreations/KazuyaSakai/Integrales/Sketch.swift
//  Recreation after Kazuya Sakai - Integrales II (Edgard Varèse) (1979,
//  acrylic on canvas, 141 x 141 cm), at the Dallas Museum of Art. He made it
//  two years after he left Mexico for Texas. A homage, not a reproduction,
//  and not affiliated with or endorsed by the artist or his estate.
//  https://artsandculture.google.com/asset/integrales-ii-edgard-var%C3%A8se-kazuya-sakai/ogFqGWfNsF2nsg
//  https://athenaeumreview.org/essay/kazuya-sakai-in-texas/
//
//  An original Ollin interpretation, read off the museum's picture of the
//  painting. The rule it keeps is Lillian Michel's account of the paintings
//  he showed in 1979. The bands and circles "were now sliced and
//  overlapped". The bands had gradients of colors in place of many distinct
//  colors. The lines "rippled rather than taking sharp turns". No published
//  account says how he laid the cuts out. A straight cut that slides
//  everything on its far side is this sketch's reading. Nothing was ported:
//  the work is acrylic on canvas.

import Foundation
import Ollin

/// Integrales II (Kazuya Sakai, 1979). **Press** to deal another canvas.
///
/// The ribbons of his Mexican years ran whole from one side of a canvas to
/// another. After the move to Texas he cut them. This canvas is a square
/// hung on its corner. Its ground is split between a red field and a blue
/// one. Ribbons cross it that ripple like water instead of turning around
/// discs, and sets of rings sit under them. Each ribbon and each ring set
/// is a ladder of tones: a few steps from one shade of a color to another.
/// The earlier ribbons set unlike colors side by side. Straight cuts stop
/// the bands short, and what goes on past a cut has moved along it.
///
/// This sketch keeps the canvas on its corner, the ripples, the ladders of
/// tone, and the cuts. It deals the rest. The picture is first laid out
/// whole. It has the two fields, a band of tones along the upper left edge,
/// `rings` ring sets, and `ribbons` rippling ribbons over them.
/// Then `cuts` straight lines cross it. Each runs one of three ways: upright,
/// or along one of the canvas's own two edge directions. Everything on the
/// far side of a cut slides along it. So a ribbon that crossed the line
/// whole now arrives in two places. Some ribbons and ring sets are also
/// trimmed: they end flat at a line of their own.
///
/// A lap opens on the whole picture. The cuts are made one at a time, each
/// piece sliding as its cut is made. The pieces hold, then slide home. The
/// ripples travel along their ribbons the whole time, one wave a lap.
///
/// Try it: `slide` is how far the pieces move, and at 0 nothing is cut.
/// `ripple` is how far each ribbon swings, and at 0 it runs straight.
/// `tones` is the steps in every ladder. The seed deals the cuts, the
/// centers, the headings, and which ribbons and rings are trimmed.
@main
final class Integrales: Sketch {
    /// Straight cuts across the canvas.
    @Param(0 ... 6, icon: "scissors") var cuts = 3
    /// How far the pieces slide along their cuts, as a share of the dealt distance.
    @Param(0 ... 2, icon: "arrow.left.arrow.right") var slide = 1.0
    /// Rippling ribbons.
    @Param(0 ... 3, icon: "water.waves") var ribbons = 2
    /// Sets of rings.
    @Param(0 ... 4, icon: "circle.circle") var rings = 3
    /// Steps of tone in each ribbon and each ring set.
    @Param(3 ... 14, icon: "stairs") var tones = 9
    /// How far a ribbon swings from its heading: 0 is straight, 1 nearly doubles back.
    @Param(0 ... 1, icon: "wave.3.right") var ripple = 0.6
    /// Seconds for one lap: whole, cut and slid apart, and home again.
    @Param(8 ... 30, icon: "timer") var seconds = 20.0

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

    // The paints, sampled from the museum's picture.
    private let wall = Color(hex: 0xF3F2EE)
    private let redField = Color(hex: 0xB3261A)
    private let blueField = Color(hex: 0x12358A)

    /// A ladder of tones: it runs from one color to another, and may carry
    /// one thin line of a third color.
    private struct Ladder {
        var from: Color
        var to: Color
        var line: Color?
    }

    /// A straight cut: a point on it, the way it runs, and how far the far
    /// side slides along it.
    private struct Cut {
        var point: Vector2
        var along: Vector2
        var slide: Double
    }

    /// A line something ends flat at: only the side `inward` points to is kept.
    private struct Trim {
        var point: Vector2
        var inward: Vector2
    }

    /// Rings around one center, from the widest in, each drawn over the last.
    private struct RingSet {
        var center: Vector2
        var radii: [Double]
        var paints: [Color]
        var trim: Trim?
    }

    /// A rippling ribbon: where it starts, the way it heads, the edges of
    /// its bands across it, and the arcs its centerline is made of.
    private struct Ribbon {
        var origin: Vector2
        var heading: Vector2
        var edges: [Double]
        var paints: [Color]
        /// The radius of each arc of the centerline.
        var bend: Double
        /// How far the heading swings to each side, in radians.
        var swing: Double
        var length: Double
        /// Where the ripple starts along the ribbon, in waves, and which way it travels.
        var phase: Double
        var travel: Double
        var trim: Trim?
    }

    private struct Plan {
        var cuts: [Cut] = []
        var rings: [RingSet] = []
        var ribbons: [Ribbon] = []
        /// The band of tones along the upper left edge: its edges in from
        /// the canvas edge, its paints, and where it ends.
        var edgeBand: [Double] = []
        var edgePaints: [Color] = []
        var edgeTrim: Trim?
        /// The blue field begins at this x.
        var split = 0.0
    }

    /// One piece of the cut canvas: its outline, and how far it has slid.
    private struct Piece {
        var points: [Vector2]
        var shift: Vector2
    }

    private var plan = Plan()
    private var built = ""
    private var dealt = 0

    /// Half the canvas's diagonal: the square hangs on its corner.
    private var reach: Double { width * 0.478 }
    private var middle: Vector2 { Vector2(width / 2, height / 2) }

    override func mousePressed() {
        dealt += 1
    }

    // MARK: - The frame

    override func draw() {
        let key = "\(variation)/\(dealt)/\(cuts)/\(ribbons)/\(rings)/\(tones)/\(ripple)"
        if key != built {
            plan = deal(seed: variation &+ dealt &* 7919)
            built = key
        }

        let lap = loopProgress(over: seconds)
        background(wall)
        noStroke()

        // The ribbons' outlines are worked out once and drawn in every piece.
        let bands = plan.ribbons.map { outlines(of: $0, lap: lap) }
        for piece in pieces(at: lap) {
            withClip(Shape(outer: piece.points, holes: [])) {
                translate(piece.shift.x, piece.shift.y)
                drawTheWholePicture(bands)
            }
        }
    }

    /// How much of its slide each cut has made at this point of the lap. The
    /// cuts are made one after another, hold, and close together.
    private func slid(_ index: Int, of count: Int, at lap: Double) -> Double {
        let (start, apart, back, home) = (0.06, 0.4, 0.7, 0.94)
        let step = (apart - start) / Double(max(count, 1))
        let out = smoothstep(0, 1, (lap - start - step * Double(index)) / step)
        return out * (1 - smoothstep(0, 1, (lap - back) / (home - back)))
    }

    /// Cuts the canvas into its pieces. Each cut splits every piece it
    /// crosses, and the part on its far side takes on the cut's slide.
    private func pieces(at lap: Double) -> [Piece] {
        let c = middle, r = reach
        var pieces = [Piece(points: [Vector2(c.x, c.y - r), Vector2(c.x + r, c.y), Vector2(c.x, c.y + r), Vector2(c.x - r, c.y)],
                            shift: Vector2(0, 0))]
        for (index, cut) in plan.cuts.enumerated() {
            // A cut that has not been made yet, or has closed again, splits nothing.
            let distance = cut.slide * slide * slid(index, of: plan.cuts.count, at: lap)
            guard distance != 0 else { continue }
            let across = Vector2(-cut.along.y, cut.along.x)
            let limit = cut.point.dot(across)
            let moved = cut.along * distance
            var next: [Piece] = []
            for piece in pieces {
                let nearSide = Self.cut(piece.points, normal: across, limit: limit)
                let farSide = Self.cut(piece.points, normal: across * -1, limit: -limit)
                if nearSide.count >= 3 { next.append(Piece(points: nearSide, shift: piece.shift)) }
                if farSide.count >= 3 { next.append(Piece(points: farSide, shift: piece.shift + moved)) }
            }
            pieces = next
        }
        return pieces
    }

    /// The part of a convex outline on the near side of a line: the points
    /// `p` with `p . normal <= limit`.
    private static func cut(_ points: [Vector2], normal: Vector2, limit: Double) -> [Vector2] {
        var kept: [Vector2] = []
        for i in points.indices {
            let a = points[i], b = points[(i + 1) % points.count]
            let da = a.dot(normal) - limit, db = b.dot(normal) - limit
            if da <= 0 { kept.append(a) }
            if (da < 0 && db > 0) || (da > 0 && db < 0) {
                kept.append(a + (b - a) * (da / (da - db)))
            }
        }
        return kept
    }

    /// Runs `body` with drawing kept to one side of a trim line, if there is one.
    private func trimmed(_ trim: Trim?, _ body: () -> Void) {
        guard let trim else {
            body()
            return
        }
        let far = width * 3
        let along = Vector2(-trim.inward.y, trim.inward.x)
        let side = [trim.point - along * far, trim.point + along * far,
                    trim.point + along * far + trim.inward * far, trim.point - along * far + trim.inward * far]
        withClip(Shape(outer: side, holes: []), body)
    }

    /// Draws the picture as it was before any cut. It reaches well past the
    /// canvas, since a piece that slides shows what lay beside it.
    private func drawTheWholePicture(_ bands: [[Shape]]) {
        let far = width * 2

        // 1. The two fields.
        fill(redField)
        drawRect(-far, -far, 2 * far + width, 2 * far + height)
        fill(blueField)
        drawRect(plan.split, -far, far + width, 2 * far + height)

        // 2. The band of tones along the upper left edge, widest at the edge.
        trimmed(plan.edgeTrim) {
            let corner = middle - Vector2(reach, 0)
            let along = Vector2(1, -1) / 2.0.squareRoot(), inward = Vector2(1, 1) / 2.0.squareRoot()
            for (i, paint) in plan.edgePaints.enumerated() {
                let a = corner + inward * plan.edgeBand[i], b = corner + inward * plan.edgeBand[i + 1]
                fill(paint)
                drawPolygon([a - along * far, a + along * far, b + along * far, b - along * far])
            }
        }

        // 3. The ring sets, each from its widest ring in.
        for set in plan.rings {
            trimmed(set.trim) {
                for (radius, paint) in zip(set.radii, set.paints) {
                    fill(paint)
                    drawCircle(center: set.center, radius: radius)
                }
            }
        }

        // 4. The ribbons, over the rings.
        for (ribbon, shapes) in zip(plan.ribbons, bands) {
            trimmed(ribbon.trim) {
                for (shape, paint) in zip(shapes, ribbon.paints) {
                    fill(paint)
                    drawShape(shape)
                }
            }
        }
    }

    // MARK: - The ribbons

    /// The outline of every band of a ribbon. The centerline is a chain of
    /// equal arcs that bulge to one side and then the other, so the ribbon
    /// ripples about its heading. A band's edge is that line moved across by
    /// the edge's own offset, which on an arc is an arc about the same
    /// center. Every edge is sampled at the same places, so neighbors share
    /// their points and the fills meet with nothing between them.
    private func outlines(of ribbon: Ribbon, lap: Double) -> [Shape] {
        let h = ribbon.heading
        let left = Vector2(h.y, -h.x)
        let margin = reach
        var lines = Array(repeating: [Vector2](), count: ribbon.edges.count)

        if ribbon.swing < 0.03 {
            // No ripple: the bands are plain parallel strips.
            for (j, e) in ribbon.edges.enumerated() {
                lines[j] = [ribbon.origin - h * margin + left * e, ribbon.origin + h * (ribbon.length + margin) + left * e]
            }
        } else {
            // One arc covers `span` of the heading. Two arcs make a wave,
            // and the ripple travels one wave a lap.
            let span = 2 * ribbon.bend * sin(ribbon.swing)
            let shift = 2 * (ribbon.phase + ribbon.travel * lap)
            let first = Int((-margin / span - shift).rounded(.down))
            let last = Int(((ribbon.length + margin) / span - shift).rounded(.up))
            let steps = 14
            for k in first ..< last {
                let side: Double = k % 2 == 0 ? 1 : -1
                let chordMiddle = ribbon.origin + h * ((Double(k) + 0.5 + shift) * span)
                let center = chordMiddle - left * (side * ribbon.bend * cos(ribbon.swing))
                for s in (k == first ? 0 : 1) ... steps {
                    let u = -ribbon.swing + 2 * ribbon.swing * Double(s) / Double(steps)
                    let radial = h * sin(u) + left * (side * cos(u))
                    for (j, e) in ribbon.edges.enumerated() {
                        lines[j].append(center + radial * (ribbon.bend + side * e))
                    }
                }
            }
        }
        return ribbon.paints.indices.map { Shape(outer: lines[$0] + lines[$0 + 1].reversed(), holes: []) }
    }

    // MARK: - Dealing the canvas

    /// The tones of a ladder as `count` paints, each with its width as a
    /// share of a full step.
    private static func steps(of ladder: Ladder, count: Int) -> [(paint: Color, width: Double)] {
        (0 ..< count).map { i in
            let t = count > 1 ? Double(i) / Double(count - 1) : 0
            return (paint: ladder.from.mixed(with: ladder.to, t), width: 1.0)
        }
    }

    /// Lays out the whole picture and the cuts. Everything comes from the seed.
    private func deal(seed: Int) -> Plan {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(seed &* 1_000_003 &+ 1979)))
        func roll() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func roll(_ a: Double, _ b: Double) -> Double { a + (b - a) * roll() }
        func pick<T>(_ items: [T]) -> T { items[min(items.count - 1, Int(roll() * Double(items.count)))] }

        let c = middle, r = reach
        var plan = Plan()
        /// The three ways a cut or a trim can run: upright, and along the
        /// canvas's two edge directions.
        let ways = [Vector2(0, 1), Vector2(1, 1) / 2.0.squareRoot(), Vector2(1, -1) / 2.0.squareRoot()]

        // The ladders, read off the painting: reds for the largest rings,
        // greens over blues, a brown beside a teal, and violets.
        let crimson = Ladder(from: Color(hex: 0x83020E), to: Color(hex: 0xD2420A), line: Color(hex: 0x1F9A12))
        let blues = Ladder(from: Color(hex: 0x0452B4), to: Color(hex: 0x051C5E), line: Color(hex: 0x7A3414))
        let greens = Ladder(from: Color(hex: 0x0A3F38), to: Color(hex: 0x127A52), line: Color(hex: 0x7A3414))
        let violets = Ladder(from: Color(hex: 0x4E2A9A), to: Color(hex: 0x14102D), line: Color(hex: 0xA60E5E))
        let browns = Ladder(from: Color(hex: 0x2B1516), to: Color(hex: 0x6A2A1A), line: Color(hex: 0x3A1C7A))
        let teals = Ladder(from: Color(hex: 0x056074), to: Color(hex: 0x012C33), line: Color(hex: 0x3A1C7A))
        let leaves = Ladder(from: Color(hex: 0xC85A08), to: Color(hex: 0x06541A), line: Color(hex: 0xE8C020))
        let night = Ladder(from: Color(hex: 0x010F36), to: Color(hex: 0x5A46A0), line: nil)

        plan.split = c.x + roll(-0.06, 0.06) * r

        // 1. The band along the upper left edge: steps that lighten and thin
        // toward the inside, ending flat at an upright line.
        let edgeSteps = min(tones, 6)
        var inset = 0.0, stepWidth = 0.082 * r
        plan.edgeBand = [0]
        for step in Self.steps(of: night, count: edgeSteps) {
            inset += stepWidth
            stepWidth *= 0.74
            plan.edgeBand.append(inset)
            plan.edgePaints.append(step.paint)
        }
        plan.edgeTrim = Trim(point: c + Vector2(roll(-0.5, -0.3) * r, 0), inward: Vector2(-1, 0))

        // 2. The ring sets: down the left, in the middle, and at the bottom,
        // where the painting has them. Each is two ladders with a thin line
        // between them and a core.
        let seats = [Vector2(-0.11, -0.17), Vector2(0.13, 0.42), Vector2(-0.3, 0.13), Vector2(0.36, 0.02)]
        let suits: [(outer: Ladder, inner: Ladder, core: Color)] = [
            (greens, blues, Color(hex: 0x4A2018)),
            (crimson, violets, Color(hex: 0x05403C)),
            (crimson, Ladder(from: Color(hex: 0xB01226), to: Color(hex: 0x6A0A3C), line: nil), Color(hex: 0x4A0A4E)),
            (violets, teals, Color(hex: 0xC8380A)),
        ]
        // All four are dealt whatever `rings` is, and all three ribbons and
        // all six cuts below, so changing a count moves nothing else.
        for i in 0 ..< 4 {
            let center = c + (seats[i % 4] + Vector2(roll(-0.07, 0.07), roll(-0.07, 0.07))) * r
            let radius = (i % 4 == 1 ? roll(0.3, 0.35) : roll(0.24, 0.3)) * r
            let suit = suits[i % 4]
            let outerCount = max(1, tones / 2), innerCount = max(1, tones - tones / 2)
            let rungs = Self.steps(of: suit.outer, count: outerCount)
                + [(paint: suit.outer.line ?? suit.core, width: 0.35)]
                + Self.steps(of: suit.inner, count: innerCount)
            let core = radius * 0.2
            let unit = (radius - core) / rungs.reduce(0) { $0 + $1.width }
            var set = RingSet(center: center, radii: [], paints: [])
            var at = radius
            for rung in rungs {
                set.radii.append(at)
                set.paints.append(rung.paint)
                at -= rung.width * unit
            }
            set.radii.append(core)
            set.paints.append(suit.core)
            // Half of the sets end flat at a line through them.
            if roll() < 0.5 {
                let way = pick(ways)
                let across = Vector2(-way.y, way.x) * (roll() < 0.5 ? 1 : -1)
                set.trim = Trim(point: center - across * (roll(0.1, 0.6) * radius), inward: across)
            }
            if i < rings { plan.rings.append(set) }
        }

        // 3. The ribbons. Each comes in from one of the upper edges and heads
        // down toward the bottom of the canvas. It is two ladders side by
        // side with a line between.
        let pairs: [(Ladder, Ladder)] = [(browns, teals), (violets, Ladder(from: violets.to, to: violets.from, line: nil)), (leaves, greens)]
        for i in 0 ..< 3 {
            let fromLeft = i % 2 == 0
            let along = roll(0.3, 0.6)
            // A point on the upper left edge, or its mirror on the upper right.
            let start = c + Vector2((fromLeft ? -1 : 1) * (1 - along) * r, -along * r)
            let goal = c + Vector2(roll(-0.15, 0.25) * (fromLeft ? 1 : -1) * r, roll(0.45, 0.75) * r)
            let heading = (goal - start) / (goal - start).length
            let width = roll(0.24, 0.3) * r
            let pair = pairs[i % 3]
            let leftCount = max(1, tones / 2), rightCount = max(1, tones - tones / 2)
            let rungs = Self.steps(of: pair.0, count: leftCount) + [(paint: pair.0.line ?? .black, width: 0.3)]
                + Self.steps(of: pair.1, count: rightCount)
            let unit = width / rungs.reduce(0) { $0 + $1.width }
            var edges = [-width / 2]
            for rung in rungs { edges.append(edges[edges.count - 1] + rung.width * unit) }
            var ribbon = Ribbon(origin: start, heading: heading, edges: edges, paints: rungs.map(\.paint),
                                bend: width / 2 * 1.18, swing: ripple * 1.45, length: 2.2 * r,
                                phase: roll(), travel: roll() < 0.5 ? 1 : -1)
            // Most ribbons stop short, flat at a line that runs one of the three ways.
            if roll() < 0.75 {
                let way = pick(ways)
                var across = Vector2(-way.y, way.x)
                if across.dot(heading) > 0 { across = across * -1 }
                ribbon.trim = Trim(point: start + heading * (roll(0.75, 1.3) * r), inward: across)
            }
            if i < ribbons { plan.ribbons.append(ribbon) }
        }

        // 4. The cuts, each through the busy middle of the canvas, running
        // one of the three ways, with its own slide.
        var turn = Int(roll() * 3)
        var dealtCuts: [Cut] = []
        for _ in 0 ..< 6 {
            let way = ways[turn % 3]
            let across = Vector2(-way.y, way.x)
            // A cut keeps clear of the cuts that run its way, so no piece is a sliver.
            var point = c
            for _ in 0 ..< 12 {
                point = c + Vector2(roll(-0.35, 0.35) * r, roll(-0.3, 0.45) * r)
                let crowded = dealtCuts.contains { $0.along == way && abs(($0.point - point).dot(across)) < 0.24 * r }
                if !crowded { break }
            }
            let far = roll(0.09, 0.2) * r * (roll() < 0.5 ? 1 : -1)
            dealtCuts.append(Cut(point: point, along: way, slide: far))
            turn += 1 + Int(roll() * 2)
        }
        plan.cuts = Array(dealtCuts.prefix(cuts))
        return plan
    }
}

↑↓ move ↩ open