# StoZdarzen

a hundred turned squares, one thrown into every cell and cut by it, after Winiarski's Sto zdarzeń (1977).

Run it with `swift run --package-path Examples Example-Recreations-RyszardWiniarski-StoZdarzen`.

```swift
//  Recreation after Ryszard Winiarski - "Sto zdarzeń" (A Hundred Incidents,
//  1977). The Zachęta in Warsaw holds three canvases of the series, "Sto
//  zdarzeń 1x1", "8x8", and "10x10", under the English title "Hundred of
//  Incidents". A later one, "Sto zdarzeń podwójnych" (A Hundred Double
//  Incidents, 1980), is in the Anna and Jerzy Starak Collection. Each is a
//  canvas ruled into a hundred cells, with a turned square thrown into every
//  cell, or two. A homage, not a reproduction, and not affiliated with or
//  endorsed by the artist or his estate.
//  https://zacheta.art.pl/pl/kolekcja/katalog/winiarski-ryszard-sto-zdarzen-8x8-2
//
//  An original Ollin interpretation. No statement of this program by the
//  artist was found, so the rule is read off pictures of the work. It was
//  measured on the gallery's photographs of the three canvases. Nothing was
//  ported: the works are acrylic on canvas.

import Ollin

/// "Sto zdarzeń" (Ryszard Winiarski, 1977), a hundred events. In probability
/// an event is one outcome of a throw. The word is in the title of his
/// diploma, "Zdarzenie, informacja, obraz" (Event, Information, Image). Here
/// a square canvas about a meter on a side is ruled into a hundred cells of
/// ten centimeters. Each cell holds one event: a black square, dropped
/// somewhere in the cell and turned some way. The Zachęta has three canvases
/// of the series, named for the side of their squares in centimeters: 1x1,
/// 8x8, and 10x10.
///
/// No account of the program by Winiarski was found, so this sketch goes by
/// what the gallery's photographs measure. Every cell holds exactly one
/// square, and a square is painted only where it falls inside its own cell.
/// The 8x8 and the 10x10 canvas show the same hundred events. Each square
/// keeps one corner and its turn, and its sides grow from that corner. The
/// 1x1 canvas is another hundred, and all its small squares lie whole inside
/// their cells. The squares also open toward the inside of their cells far
/// more often than chance alone would have them. Black covers 41% of the 8x8
/// canvas and 46% of the 10x10. A corner and a turn thrown separately would
/// give 28% and 30%.
///
/// The photographs do not say what device threw an event, so the device here
/// is this sketch's own. An event is two points thrown in the cell. One
/// corner of the square goes on the first, and the diagonal from that corner
/// aims at the second. If the 1 cm square would cross the edge of its cell,
/// the event is thrown again. That rule gives 42% and 46% of black, and it
/// agrees with the other measurements too.
///
/// One lap goes through the series. The events are thrown in order, one cell
/// after another, each written under the canvas as it lands. Then every
/// square grows from its corner to the next side in `sides`, holds, and
/// grows again. At the end the squares draw back into their corners.
///
/// Try it: `eventSeed` is the hundred events, and a click throws the next
/// hundred. `sides` holds the sides of the series in centimeters: 1, 8, and
/// 10 as in the Zachęta's three. `doubled` gives each cell a second event in
/// gray under the first, as in the canvas of 1980. `seconds` is the lap.
///
/// `--export-svg` writes each square as the outline its cell leaves of it, so
/// the file holds one shape for every event.
@main
final class StoZdarzen: Sketch {
    /// The sides of the squares in centimeters, one canvas of the series
    /// each. A cell is 10 cm, and the lap visits the sides in this order.
    @Param(1 ... 10, step: 0.5, icon: "ruler") var sides = [1.0, 8, 10]
    /// Two events to a cell, the first in gray under the second.
    @Param(icon: "square.on.square") var doubled = false
    /// Seconds for one lap: the throwing, the series, and the way back.
    @Param(12 ... 30, icon: "clock") var seconds = 24.0
    /// Which hundred events are thrown. The seed it starts on gives the two
    /// shares of black measured on the photographs, 41% and 46%.
    @Param(1 ... 9999, icon: "dice") var eventSeed = 2

    override var loopDuration: Double? { seconds }

    private let wall = Color(hex: 0xE9E5DC)
    private let ground = Color(hex: 0xF7F6F2)
    private let ink = Color(hex: 0x161616)
    private let gray = Color(hex: 0x939696)
    private let pencil = Color(hex: 0xADA99F)
    private let handwriting = Color(hex: 0x4A4640)

    // MARK: The events

    /// One event, in centimeters from the top left of its cell. It holds the
    /// corner the square keeps and the point its diagonal aims at. The turn
    /// of the square's first side follows from the two.
    struct Event {
        var corner: Vector2
        var aim: Vector2
        var turn: Double
    }

    /// A cell's side, in centimeters.
    static let cell = 10.0

    /// The share of the lap spent throwing, and the share where the squares
    /// start to draw back.
    static let throwing = 0.40, drawingBack = 0.93

    /// Throw one event for each of `count` cells, in order. Each throw is
    /// four numbers: across and down for the corner, then across and down
    /// for the aim. A throw whose 1 cm square would cross the edge of the
    /// cell is thrown again, so `casts` counts every throw made.
    static func throwEvents(seed: UInt64, count: Int) -> (events: [Event], casts: Int) {
        var generator = SplitMix64(seed: seed)
        func roll() -> Double { Double(generator.next() >> 11) * 0x1p-53 }

        var events: [Event] = []
        var casts = 0
        while events.count < count {
            casts += 1
            let corner = Vector2(roll() * cell, roll() * cell)
            let aim = Vector2(roll() * cell, roll() * cell)
            let toward = aim - corner
            guard toward.length > 1e-9 else { continue }
            // The diagonal leaves the corner an eighth of a turn after the
            // first side does.
            let event = Event(corner: corner, aim: aim, turn: atan2(toward.y, toward.x) - .pi / 4)
            let small = square(of: event, side: 1)
            if small.allSatisfy({ $0.x >= 0 && $0.x <= cell && $0.y >= 0 && $0.y <= cell }) {
                events.append(event)
            }
        }
        return (events, casts)
    }

    /// The four corners of an event's square at a given side, before the
    /// cell cuts it.
    static func square(of event: Event, side: Double) -> [Vector2] {
        let first = Vector2(angle: event.turn, length: side)
        let second = Vector2(-first.y, first.x)
        return [event.corner, event.corner + first, event.corner + first + second, event.corner + second]
    }

    /// What the cell leaves of an event's square: the square cut along the
    /// four edges of its own cell, one edge at a time.
    static func outline(of event: Event, side: Double) -> [Vector2] {
        var shape = square(of: event, side: side)
        let inside: [(Vector2) -> Double] = [
            { $0.x }, { cell - $0.x }, { $0.y }, { cell - $0.y },
        ]
        for depth in inside {
            guard !shape.isEmpty else { break }
            var kept: [Vector2] = []
            for index in shape.indices {
                let a = shape[index], b = shape[(index + 1) % shape.count]
                let da = depth(a), db = depth(b)
                if da >= 0 { kept.append(a) }
                if (da >= 0) != (db >= 0) { kept.append(a + (b - a) * (da / (da - db))) }
            }
            shape = kept
        }
        return shape
    }

    /// The area of an outline, in square centimeters.
    static func area(of shape: [Vector2]) -> Double {
        var twice = 0.0
        for index in shape.indices {
            let a = shape[index], b = shape[(index + 1) % shape.count]
            twice += a.x * b.y - b.x * a.y
        }
        return abs(twice) / 2
    }

    // MARK: The lap

    /// Where the lap stands at `progress`, from 0 to 1. `thrown` counts the
    /// events thrown so far, with a fraction for the one landing. `side` is
    /// the side every landed square has, and `caption` how strongly the
    /// caption is inked.
    static func stage(at progress: Double, sizes: [Double],
                      events: Int) -> (thrown: Double, side: Double, caption: Double) {
        guard let first = sizes.first, let last = sizes.last else { return (0, 0, 0) }
        func smooth(_ t: Double) -> Double { t * t * (3 - 2 * t) }

        if progress < throwing {
            return (progress / throwing * Double(events), first, min(1, progress / 0.015))
        }
        if progress >= drawingBack {
            let t = (progress - drawingBack) / (1 - drawingBack)
            return (Double(events) + 1, last * (1 - smooth(t)), 1 - t)
        }
        // Between the two comes a short hold on the first side. Then each
        // later side gets a growth and a hold, the last hold the longest.
        var spans: [(length: Double, from: Double, to: Double)] = [(0.5, first, first)]
        for index in sizes.indices.dropFirst() {
            spans.append((1, sizes[index - 1], sizes[index]))
            spans.append((index == sizes.count - 1 ? 1.6 : 1, sizes[index], sizes[index]))
        }
        let whole = spans.reduce(0) { $0 + $1.length }
        var t = (progress - throwing) / (drawingBack - throwing) * whole
        for span in spans {
            if t <= span.length {
                return (Double(events) + 1, lerp(span.from, span.to, smooth(t / span.length)), 1)
            }
            t -= span.length
        }
        return (Double(events) + 1, last, 1)
    }

    // MARK: Drawing

    /// The events in the order they are thrown and painted: cell after cell
    /// along the rows, and in a doubled cell the gray one first.
    private var order: [(cell: Int, event: Event, under: Bool)] = []
    private var casts = 0
    private var thrownFor = ""
    /// Where in the lap the last click came, taken off the lap from then on
    /// so the next hundred start with their first throw.
    private var restart = 0.0

    private func throwAll() {
        let name = "\(eventSeed)/\(doubled)"
        guard thrownFor != name else { return }
        thrownFor = name
        let cells = 100
        let over = Self.throwEvents(seed: UInt64(eventSeed), count: cells)
        order = []
        casts = over.casts
        if doubled {
            // The gray events come from their own run of throws, so the
            // black ones stay where they were when a cell is doubled.
            let under = Self.throwEvents(seed: UInt64(eventSeed) &+ 0x5151_0000, count: cells)
            casts += under.casts
            for index in 0 ..< cells {
                order.append((index, under.events[index], true))
                order.append((index, over.events[index], false))
            }
        } else {
            for index in 0 ..< cells { order.append((index, over.events[index], false)) }
        }
    }

    override func setup() {
        textFont(OutlineFont.system)
    }

    override func mousePressed() {
        eventSeed = eventSeed >= 9999 ? 1 : eventSeed + 1
        restart = -loopProgress(over: seconds)
    }

    override func draw() {
        background(wall)
        throwAll()

        let side = min(width, height) * 0.8
        let field = Rectangle(center: Vector2(width / 2, height / 2 - side * 0.055),
                              width: side, height: side)
        // One centimeter of the canvas, in pixels.
        let cm = field.width / (Self.cell * 10)

        noStroke()
        fill(ground)
        drawRect(field)

        let stage = Self.stage(at: loopProgress(over: seconds, phase: restart), sizes: sides,
                               events: order.count)
        func smooth(_ t: Double) -> Double { t * t * (3 - 2 * t) }

        var black = 0.0
        for (index, item) in order.enumerated() {
            // An event lands over the time one throw takes: its square
            // opens from the corner to the side the lap is on.
            let landed = smooth(clamp(stage.thrown - Double(index), 0, 1))
            let grown = stage.side * landed
            guard grown > 1e-6 else { continue }
            let shape = Self.outline(of: item.event, side: grown)
            guard shape.count >= 3 else { continue }
            if !item.under { black += Self.area(of: shape) }
            let corner = Vector2(field.x + Double(item.cell % 10) * Self.cell * cm,
                                 field.y + Double(item.cell / 10) * Self.cell * cm)
            fill(item.under ? gray : ink)
            drawPolygon(shape.map { corner + $0 * cm })
        }

        // The ruling last. In the photographs the ruled lines stay bare, so
        // they still show where two black squares meet across a cell's edge.
        noFill()
        stroke(pencil)
        strokeWeight(1)
        for k in 0 ... 10 {
            let along = Double(k) * Self.cell * cm
            drawLine(field.x + along, field.y, field.x + along, field.y + field.height)
            drawLine(field.x, field.y + along, field.x + field.width, field.y + along)
        }

        // The caption: the canvas of the series the lap is on, then the
        // event landing, or the count once all have landed.
        let landing = min(order.count, Int(stage.thrown) + 1)
        let size = "\(Self.plain(stage.side)) x \(Self.plain(stage.side))"
        let title = doubled
            ? "Sto zdarzeń podwójnych \(size). A hundred double events, two to a cell."
            : "Sto zdarzeń \(size). A hundred events, one to a cell."
        let line: String
        if stage.thrown < Double(order.count), landing >= 1 {
            let event = order[landing - 1].event
            line = "Event \(landing) of \(order.count): corner at "
                + "\(Self.tenths(event.corner.x)), \(Self.tenths(event.corner.y)) cm, "
                + "aimed at \(Self.tenths(event.aim.x)), \(Self.tenths(event.aim.y))."
        } else {
            let share = black / (Self.cell * Self.cell * 100)
            line = "\(order.count) events from \(casts) throws. "
                + "Black covers \(Self.tenths(share * 100))% of the canvas."
        }
        let color = handwriting.withAlpha(stage.caption)
        let baseline = field.y + field.height + side * 0.026
        drawText(title, field.x, baseline, size: side * 0.0175, color: color, align: .left, .top)
        drawText(line, field.x, baseline + side * 0.032, size: side * 0.0175, color: color,
                 align: .left, .top)
    }

    /// A number to one decimal place, always with the decimal.
    private static func tenths(_ value: Double) -> String {
        let scaled = Int((value * 10).rounded())
        return "\(scaled / 10).\(abs(scaled) % 10)"
    }

    /// A side in centimeters: whole when it is whole, else to one decimal.
    private static func plain(_ value: Double) -> String {
        let scaled = Int((value * 10).rounded())
        return scaled % 10 == 0 ? "\(scaled / 10)" : "\(scaled / 10).\(scaled % 10)"
    }
}
```
