# ImagenRitmicaPorRotacion

a folded mirror turning at the bottom of a painted well, after Felguérez's Imagen rítmica por rotación (1971).

Run it with `swift run --package-path Examples Example-Recreations-ManuelFelguerez-ImagenRitmicaPorRotacion`.

```swift
//  Recreation after Manuel Felguerez - "Imagen ritmica por rotacion" (1971;
//  acrylic on wood, aluminum, mirrors and an electric motor; 61.5 x 61 x
//  22.5 cm). One of the kinetic boxes with mirrors he made around 1971, two
//  years before "El espacio multiple"; shown at Proyectos Monclova, Mexico
//  City, in 2022. A homage, not a reproduction, and not affiliated with or
//  endorsed by the artist or his estate.
//  https://proyectosmonclova.com/exhibitions-gallery/manuel-felguerez
//
//  An original Ollin interpretation, read off photographs of the piece and
//  of its still sibling, "Imagen ritmica" (1971). Nothing was ported: the
//  work is a painted box, mirrors and a motor. The photographs give the
//  eight-sided body, the square frame, the four half-disk windows backed
//  with mirror, and the turning disk folded along a diameter. The well
//  around the disk, its depth, its paint and the angle of the fold are a
//  reading, and the notes below say where.

import Foundation
import Ollin

/// "Imagen ritmica por rotacion" (Manuel Felguerez, 1971): a folded mirror
/// turning at the bottom of a painted well.
///
/// Around 1967 Felguerez began making kinetic pieces, and by 1971 mirrors
/// were at the center of them. Pilar Garcia, who curated his retrospective,
/// writes that the mirror works in these pieces as a device that multiplies
/// spaces: it gives the work one more dimension and brings the viewer into
/// it. This one is an eight-sided box about 61 centimeters across, painted
/// blue. A square frame opens at its middle onto a well. Four half-disk
/// windows around the frame are backed with mirror. At the bottom of the
/// well a disk turns on a motor. The disk is folded along a diameter and
/// each half is a mirror, so the two halves show the same well along two
/// different lines of sight.
///
/// The sketch keeps that rule exactly. A flat mirror shows the space in
/// front of it as if the space were folded through the glass, so every wall
/// of the well lands on a half of the disk as a parallelogram, and the open
/// mouth of the well lands as a patch of the room's light. The sketch works
/// those shapes out for the angle the disk stands at and cuts them to the
/// half disk. Nothing is traced and nothing is painted on: as the fold
/// turns, the same four walls slide across both halves, a corner of the
/// well sweeps through as a straight seam, and the room opens at the rim
/// each time a half looks into a corner. Four corners make four beats a
/// turn in each half: a rhythm made by turning, as the title says.
///
/// What is read and what is chosen. The body, the frame, the windows and
/// the fold are read off photographs. No photograph shows the walls of the
/// well whole, so their paint is a choice: two red, one black and one blue,
/// the colors the disk shows in the photographs, and the seed deals which
/// wall takes which. The fold here leans each half toward the other, like a
/// book held open to the viewer, at an angle steep enough for the walls to
/// fill the mirrors. The four windows show the room as plain light.
///
/// Try it: `inside` switches between the color fields of the motor piece
/// and the stripes of its still sibling, "Imagen ritmica", where the rings
/// painted round the well come back in the two halves as a herringbone.
/// `fold` is the angle of the fold and `depth` how deep the well is; a
/// shallow well lets more of the room in. `seconds` is one turn of the
/// motor. A folded disk looks the same after half a turn, so the picture
/// comes round twice in each one, and a lap of the loop is half of
/// `seconds`. `motor` stops it, and `turn` is where the fold stands at the
/// start. A click deals the walls again.
@main
final class ImagenRitmicaPorRotacion: Sketch {
    enum Inside: String, CaseIterable, ParamOption { case fields, stripes }

    /// How the inside of the well is painted: flat fields of color, as in
    /// the motor piece, or black and silver stripes, as in its still sibling.
    @Param(icon: "paintbrush") var inside = Inside.fields
    /// Seconds for one turn of the motor. The loop's lap is half of it.
    @Param(6 ... 60, icon: "clock") var seconds = 24.0
    /// How far each half of the disk leans toward the other, in degrees.
    @Param(8 ... 28, icon: "angle") var fold = 24.0
    /// How deep the well is in front of the disk, in half widths of its mouth.
    @Param(0.6 ... 3, icon: "arrow.up.and.down") var depth = 1.9
    /// The motor. Off, the disk stands still where `turn` puts it.
    @Param(icon: "power") var motor = true
    /// Where the fold stands when a turn begins, as a share of a full turn.
    @Param(0 ... 1, icon: "dial.low") var turn = 0.1

    /// Half a turn is one lap, since the two halves of the disk are alike.
    /// A stopped motor has nothing to loop.
    override var loopDuration: Double? { motor ? max(1, seconds) / 2 : nil }

    // MARK: The box, in units of half its width, y up

    /// Half the height of the eight-sided body. The photograph gives it a
    /// little wider than tall.
    private let halfHeight = 0.916
    /// Half the length of the top and bottom edges, then of the two sides.
    private let topEdge = 0.30
    private let sideEdge = 0.408
    /// Half the size of the square frame, and of its opening, the mouth.
    private let frame = 0.52
    private let mouth = 0.355
    /// The disk's radius: it nearly fills the mouth.
    private let disk = 0.337
    /// How far the frame stands in front of the rim, for the shading only.
    private let rise = 0.46

    private let wall = Color(red: 0.925, green: 0.918, blue: 0.914)
    private let bodyBlue = Color(red: 0.235, green: 0.318, blue: 0.500)
    private let frameGreen = Color(red: 0.185, green: 0.262, blue: 0.258)
    private let bodyRed = Color(red: 0.800, green: 0.275, blue: 0.180)
    private let frameBlack = Color(red: 0.10, green: 0.10, blue: 0.11)
    private let red = Color(red: 0.640, green: 0.105, blue: 0.085)
    private let black = Color(red: 0.070, green: 0.060, blue: 0.075)
    private let blue = Color(red: 0.100, green: 0.130, blue: 0.420)
    private let silver = Color(red: 0.800, green: 0.810, blue: 0.820)
    /// The room as a mirror returns it: the gallery's light, a little gray.
    private let room = Color(red: 0.900, green: 0.900, blue: 0.885)
    private let foldLine = Color(red: 0.780, green: 0.250, blue: 0.170)

    /// The paint on the four walls, in the order right, top, left, bottom.
    private var walls: [Color] = []
    private var dealtFor = Int.min
    private var pressed = false

    override func mousePressed() {
        pressed = true
    }

    // MARK: Drawing

    override func draw() {
        if pressed {
            pressed = false
            seed(variation + 1)
        }
        if dealtFor != variation {
            walls = deal()
            dealtFor = variation
        }

        background(wall)
        noStroke()
        drawBody()
        drawWindows()
        drawFrameAndFloor()

        // The motor turns evenly. After half a turn each half of the disk
        // stands where the other began, so the phase wraps there, and the
        // last frame of a lap meets the first exactly.
        let lap = max(1, seconds) / 2
        let phase = motor ? (time / lap).truncatingRemainder(dividingBy: 1) : 0
        let angle = turn * 2 * .pi + phase * .pi
        drawDisk(angle: angle)
    }

    /// Pixels to one unit, and a point of the box on the canvas.
    private var unit: Double { min(width, height) * 0.36 }
    private func place(_ p: Vector2) -> Vector2 { center + Vector2(p.x, -p.y) * unit }
    private func place(_ points: [Vector2]) -> [Vector2] { points.map(place) }

    /// The eight faces that slope back from the frame to the rim, each
    /// toned by how squarely it meets a light from above.
    private func drawBody() {
        let base = inside == .fields ? bodyBlue : bodyRed
        let h = halfHeight, f = frame
        // The rim, counterclockwise from the right end of the top edge.
        let rim = [Vector2(topEdge, h), Vector2(-topEdge, h), Vector2(-1, sideEdge), Vector2(-1, -sideEdge),
                   Vector2(-topEdge, -h), Vector2(topEdge, -h), Vector2(1, -sideEdge), Vector2(1, sideEdge)]
        // The frame's corners, starting top right, the same way round.
        let corners = [Vector2(f, f), Vector2(-f, f), Vector2(-f, -f), Vector2(f, -f)]

        // The shadow the box drops on the wall, below and a little aside.
        fill(Color(red: wall.red * 0.9, green: wall.green * 0.9, blue: wall.blue * 0.91))
        drawPolygon(place(rim.map { $0 * 1.03 + Vector2(0.03, -0.07) }))

        // The edge of the board all round: black on the striped piece, the
        // body's own color in shade on the other.
        let shade = Color(red: base.red * 0.3, green: base.green * 0.3, blue: base.blue * 0.3)
        fill(inside == .fields ? shade : frameBlack)
        drawPolygon(place(rim.map { $0 * (inside == .fields ? 1.01 : 1.03) }))

        for side in 0 ..< 4 {
            // A trapezoid from one edge of the rim to one edge of the frame,
            // then the triangle that turns the corner to the next one.
            let a = rim[side * 2], b = rim[side * 2 + 1], next = rim[(side * 2 + 2) % 8]
            let c0 = corners[side], c1 = corners[(side + 1) % 4]
            fill(toned(base, [a, b, c1]))
            drawPolygon(place([a, b, c1, c0]))
            fill(toned(base, [b, next, c1]))
            drawPolygon(place([b, next, c1]))
        }
    }

    /// A face's color under the light: the rim lies on the wall and the
    /// frame's corners stand `rise` in front of it.
    private func toned(_ base: Color, _ face: [Vector2]) -> Color {
        func lifted(_ p: Vector2) -> Vector3 {
            Vector3(p.x, p.y, abs(abs(p.x) - frame) < 1e-9 && abs(abs(p.y) - frame) < 1e-9 ? rise : 0)
        }
        let a = lifted(face[0]), b = lifted(face[1]), c = lifted(face[2])
        var normal = (b - a).cross(c - a).normalized
        if normal.z < 0 { normal = -normal }
        let light = Vector3(-0.2, 0.75, 0.62).normalized
        let lit = 0.30 + 0.74 * max(0, normal.dot(light))
        return Color(red: base.red * lit, green: base.green * lit, blue: base.blue * lit)
    }

    /// The four windows: a half disk cut in each sloping face, its straight
    /// side along the rim, with mirror behind it.
    private func drawWindows() {
        let base = inside == .fields ? bodyBlue : bodyRed
        let sides: [(out: Vector2, reach: Double, radius: Double)] = [
            (Vector2(0, 1), halfHeight, 0.298), (Vector2(0, -1), halfHeight, 0.298),
            (Vector2(-1, 0), 1, 0.36), (Vector2(1, 0), 1, 0.36),
        ]
        for side in sides {
            let at = side.out * (side.reach - 0.045)
            // The cut edge of the board shows as a thin crescent on the
            // inner side, then the mirror, which returns the room.
            fill(Color(red: base.red * 0.3, green: base.green * 0.3, blue: base.blue * 0.3))
            drawPolygon(place(halfDisk(at: at, out: side.out, radius: side.radius)))
            let glass = halfDisk(at: at, out: side.out, radius: side.radius * 0.93)
            let near = place(at), far = place(at - side.out * side.radius)
            fill(Gradient.linear(from: near, to: far, [room, silver]))
            drawPolygon(place(glass))
        }
    }

    /// A half disk whose straight side passes through `at`, bulging away
    /// from `out`, toward the middle of the box.
    private func halfDisk(at: Vector2, out: Vector2, radius: Double) -> [Vector2] {
        let along = Vector2(-out.y, out.x)
        return (0 ... 40).map { step in
            let angle = .pi * Double(step) / 40
            return at + along * (cos(angle) * radius) - out * (sin(angle) * radius)
        }
    }

    /// The square frame, and through its opening the floor of the well.
    private func drawFrameAndFloor() {
        // The frame faces the viewer squarely: dark green on the motor
        // piece, the body's own red on the striped one.
        let f = frame
        fill(inside == .fields ? frameGreen : toned(bodyRed, [Vector2(0, 0), Vector2(1, 0), Vector2(0, 1)]))
        drawRect(center: center, width: 2 * f * unit, height: 2 * f * unit)

        let m = mouth
        switch inside {
        case .fields:
            fill(Color(red: blue.red * 0.45, green: blue.green * 0.45, blue: blue.blue * 0.45))
            drawRect(center: center, width: 2 * m * unit, height: 2 * m * unit)
        case .stripes:
            // Twelve stripes across the floor, and the same stripes go on
            // up the walls as rings.
            fill(silver)
            drawRect(center: center, width: 2 * m * unit, height: 2 * m * unit)
            fill(black)
            for stripe in stride(from: 0, to: 12, by: 2) {
                let top = m - Double(stripe) * ring
                let low = top - ring
                drawPolygon(place([Vector2(-m, top), Vector2(m, top), Vector2(m, low), Vector2(-m, low)]))
            }
        }
    }

    /// The width of one stripe: a twelfth of the mouth.
    private var ring: Double { 2 * mouth / 12 }

    // MARK: The well, and what the mirrors show of it

    /// A flat piece of a wall, as a rectangle in space, and its paint.
    private struct Patch {
        var corners: [Vector3]
        var color: Color
    }

    /// The four walls of the well, from the floor to the mouth. The disk's
    /// center is the origin, x to the right, y up, z toward the viewer.
    private func well() -> [Patch] {
        let m = mouth
        let top = max(0.6, depth) * m
        let floor = -0.3 * m
        // Each wall by the two ends of its foot, counterclockwise from the
        // right-hand one.
        let feet = [(Vector2(m, -m), Vector2(m, m)), (Vector2(m, m), Vector2(-m, m)),
                    (Vector2(-m, m), Vector2(-m, -m)), (Vector2(-m, -m), Vector2(m, -m))]
        var patches: [Patch] = []
        for (index, foot) in feet.enumerated() {
            func band(_ z0: Double, _ z1: Double, _ color: Color) {
                patches.append(Patch(corners: [Vector3(foot.0.x, foot.0.y, z0), Vector3(foot.1.x, foot.1.y, z0),
                                               Vector3(foot.1.x, foot.1.y, z1), Vector3(foot.0.x, foot.0.y, z1)],
                                     color: color))
            }
            switch inside {
            case .fields:
                band(floor, top, walls.isEmpty ? red : walls[index % walls.count])
            case .stripes:
                // Rings one stripe wide, black and silver in turn, counted
                // up from the floor.
                var z = floor, dark = true
                while z < top - 1e-9 {
                    band(z, min(top, z + ring), dark ? black : silver)
                    z += ring
                    dark.toggle()
                }
            }
        }
        return patches
    }

    /// The disk at one angle: two half mirrors, each showing the well as it
    /// lies along that half's own line of sight, and the painted fold.
    private func drawDisk(angle: Double) {
        let lean = min(28, max(8, fold)) * .pi / 180
        let along = Vector3(cos(angle), sin(angle), 0)
        let across = Vector3(-sin(angle), cos(angle), 0)
        let patches = well()

        for side in [1.0, -1.0] {
            // This half lies on the `side` of the fold and rises toward the
            // viewer as it leaves it. Its normal leans back toward the fold.
            let normal = across * (-side * sin(lean)) + Vector3.unitZ * cos(lean)
            // A sight line straight into the box leaves this half along
            // `away`: back toward the viewer, across the fold.
            let away = across * (-side * sin(2 * lean)) + Vector3.unitZ * cos(2 * lean)

            // The half as the eye sees it: half an ellipse, since the lean
            // foreshortens it across the fold.
            let outline: [Vector2] = (0 ... 48).map { step in
                let sweep = .pi * Double(step) / 48
                let point = along * (cos(sweep) * disk) + across * (side * sin(sweep) * disk * cos(lean))
                return Vector2(point.x, point.y)
            }
            let half = Shape(place(outline), closed: true)

            // Wherever a sight line misses every wall it leaves by the
            // mouth, so the room is the ground the walls are laid on.
            fill(glassed(room))
            drawShape(half)

            for patch in patches {
                // Only what stands in front of the mirror's plane is seen in
                // it. Then each corner slides back along `away` until it
                // meets that plane, and that is where it shows.
                let seen = clipped(patch.corners, inFrontOf: normal)
                guard seen.count >= 3 else { continue }
                let image: [Vector2] = seen.map { corner in
                    let travel = normal.dot(corner) / normal.dot(away)
                    let on = corner - away * travel
                    return Vector2(on.x, on.y)
                }
                let shown = Shape(place(image), closed: true).intersection(half)
                guard !shown.contours.isEmpty else { continue }
                fill(glassed(patch.color))
                drawShape(shown)
            }
        }

        // The fold itself, painted red, edge to edge.
        let end = Vector2(along.x, along.y) * disk
        stroke(foldLine)
        strokeWeight(max(1.5, unit * 0.02))
        strokeCap(.butt)
        drawLine(place(end), place(-end))
        noStroke()
    }

    /// A color as the mirror returns it, a little grayer than the paint.
    private func glassed(_ color: Color) -> Color {
        color.mixed(with: Color(red: 0.52, green: 0.54, blue: 0.57), 0.14)
    }

    /// The part of a flat polygon in front of a plane through the origin.
    private func clipped(_ polygon: [Vector3], inFrontOf normal: Vector3) -> [Vector3] {
        var kept: [Vector3] = []
        for index in polygon.indices {
            let a = polygon[index], b = polygon[(index + 1) % polygon.count]
            let da = normal.dot(a), db = normal.dot(b)
            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
    }

    // MARK: Dealing the paint

    /// Two red walls, a black one and a blue one, in an order the seed
    /// deals.
    private func deal() -> [Color] {
        randomSeed(variation &* 7919)
        var paints = [red, red, black, blue]
        for index in stride(from: paints.count - 1, to: 0, by: -1) {
            let other = min(index, Int(random(0, Double(index + 1))))
            paints.swapAt(index, other)
        }
        return paints
    }
}
```
