# PhoneFacePaint

Paint on a face, glasses on a head, and a blink that sets something off. A Face recording plays, and a flat drawing made in a layer is laid on the face by the mesh's own texture coordinates, so it follows the skin (painted(with:) inside withFace(_:)). Round glasses are placed from the eyes, and the head, drawn as depth alone, hides the arm that passes behind it (occluding { drawMesh(face.occluder()) }). A blink throws sparks and an opened mouth lets rings go, each once (device.expressions.events()). Click the face to move a bead that rides one spot of skin. With a phone on the cable the same draw() reads Face mode live. The bundled recording is a mannequin's head drawn on the Mac.

Run it with `swift run --package-path Examples Example-3D-Phone-PhoneFacePaint`.

```swift
import Foundation
import Ollin
import OllinPhone
import simd

/// Paint on a face, glasses on a head, and a blink that sets something off.
///
/// A recording the phone made in **Face** mode plays back, and three things
/// are drawn on the head it shows.
///
/// **Paint that follows the skin.** A flat drawing is made in a layer each
/// frame (stripes on the cheeks, dots across the forehead, a line down the
/// nose) and laid on the face's mesh by the mesh's own texture coordinates:
/// `painted(with: paint.image) { drawMesh(face.mesh()) }`. The mesh moves with
/// every turn of the head and every expression and keeps its coordinates, so
/// the drawing stays on its skin. The stripes also widen as the face smiles,
/// which is a level read off the face (`face.expression(.smile)`).
///
/// **Glasses the head hides.** They are placed from the two eyes inside
/// `withFace(face)`, which draws in the head's own meters. Before them the
/// head is drawn as depth alone (`occluding { drawMesh(face.occluder()) }`),
/// so the arm on the far side of a turned head goes behind it.
///
/// **A blink as an event.** `device.expressions.events()` hands over a blink
/// once, on the frame it begins, with the face that did it. Each one throws
/// sparks from the eyes, and an opened mouth lets a few rings go.
///
/// A bead rides one spot of skin: click the face to move it. The click is
/// kept as a texture coordinate in the `bead` parameter, which names that
/// spot on every later frame.
///
/// The recording bundled here is a stand-in: a mannequin's head in a small
/// room, drawn on the Mac and written with the writer the phone runs. To
/// play one of your own, record in Face mode, bring the folder over, and set
/// `OLLIN_PHONE_RECORDING` to its path. With an iPhone on the cable running
/// **Ollin Capture**, the same `draw()` reads the phone live: the sketch asks
/// it for Face mode and draws on whoever is in front of it. An export always
/// plays the recording.
///
/// A front camera's picture is a mirror, and the phone hands the face over
/// mirrored with it, so everything here lands where it should
/// (`view.isMirrored` says so).
///
/// Keys: **space** holds the recording and carries on, **R** puts the bead
/// back between the brows.
@main
final class PhoneFacePaint: Sketch {

    override var canvasSize: CanvasSize { .size(1080, 1440) }

    /// One lap of the recording, so an export of this sketch loops.
    override var loopDuration: Double? {
        guard !isLive, let recording = recorded.recording, recording.frameRate > 0 else { return nil }
        return recording.duration + 1 / recording.frameRate
    }

    /// The phone on the cable.
    let phone = PhoneDevice()

    /// A recording, played while no phone is on the cable. Both are
    /// properties of the sketch, so the sketch's clock reaches the recording.
    let recorded = PhoneDevice(playing: PhoneFacePaint.open())

    /// Whether the phone is on the cable and this is not an export.
    var isLive: Bool { phone.isLive && !isExporting }

    /// Whichever has a face to show: the phone when it is there.
    var device: PhoneDevice { isLive ? phone : recorded }

    /// The spot of skin the bead rides, as a texture coordinate: across the
    /// face, and down it from the top of the forehead.
    @Param(x: 0...1, y: 0...1) var bead = PhoneFacePaint.betweenTheBrows
    /// How strong the paint is, from none to solid.
    @Param(0...1) var strength = 0.9

    static let betweenTheBrows = Vector2(0.5, 0.3)

    /// The layer the paint is drawn in, clear where nothing is drawn.
    var paint: RenderTarget!

    /// A spark or a ring let go by something the face did.
    struct Mote {
        var from: Vector3
        var heading: Vector3
        var born: Double
        var isRing: Bool
        var ink: Color
    }
    var motes: [Mote] = []

    static let inks = [Color(hex: 0xF25C3B), Color(hex: 0xF2B63B), Color(hex: 0x3BC6C2), Color(hex: 0xF4EFE6)]

    /// The recording to play: your own when `OLLIN_PHONE_RECORDING` names one
    /// that opens, the bundled head otherwise.
    static func open() -> PhoneRecording {
        if let path = ProcessInfo.processInfo.environment["OLLIN_PHONE_RECORDING"],
           let own = try? PhoneRecording(path: path) {
            return own
        }
        return try! PhoneRecording(resource: "Face", withExtension: "ollinrecording", in: .module)
    }

    override func setup() {
        textFont(OutlineFont.system)
        paint = makeRenderTarget(width: 1024, height: 1024)
        // The phone looks through its front camera. An export leaves the
        // phone alone.
        if !isExporting {
            phone.use(.face)
            phone.start()
        }
        recorded.start()
    }

    override func draw() {
        background(.black)
        guard let view = device.latestCamera else {
            return drawStatus(device.waitingMessage, style: .info)
        }
        drawPhonePicture(view)
        camera(view)

        // What the face did since the last frame, each thing once.
        for event in device.expressions.events() { react(to: event) }

        guard let face = device.latestFace, !face.meshPoints.isEmpty else {
            drawMotes()
            return drawCaption(isLive ? "Look at the phone's front camera" : "No face in this recording")
        }

        drawPaint(smile: face.expression(.smile))
        withFace(face) {
            // The head, as depth alone: it hides what goes behind it.
            occluding { drawMesh(face.occluder()) }

            // The paint, laid by the mesh's own texture coordinates.
            noStroke()
            fill(Color(white: 1, alpha: strength))
            painted(with: paint.image) { drawMesh(face.mesh()) }

            drawGlasses(on: face)

            // The bead, on its spot of skin.
            if let spot = face.surface(at: bead) {
                withPlane(spot) {
                    noLights()
                    fill(Self.inks[3])
                    translate(0, 0, 0.002)
                    drawSphere(radius: 0.0032, segments: 20, rings: 10)
                }
            }
        }
        drawMotes()
        drawCaption("Paint that follows the skin, glasses the head hides, and a blink that sparks")
    }

    // MARK: The paint

    /// Draw this frame's paint into its layer. The layer is the face's own
    /// map: across it is across the face, down it is from the forehead to
    /// the chin, and the middle line is the face's middle.
    private func drawPaint(smile: Double) {
        let side = Double(paint.width)
        // Once round for each lap of the recording, so a loop closes.
        let turn = 2 * Double.pi * (loopDuration.map { time / $0 } ?? time / 4)
        withTarget(paint) {
            background(Color(white: 0, alpha: 0))
            noStroke()

            // Three stripes on each cheek, wider as the face smiles.
            let reach = 0.05 + 0.05 * min(1, max(0, smile))
            for cheek in [-1.0, 1.0] {
                for stripe in 0..<3 {
                    let down = 0.56 + Double(stripe) * 0.045
                    let across = 0.5 + cheek * (0.2 + Double(stripe) * 0.012)
                    drawMark(Self.inks[stripe], from: Vector2(across - cheek * reach, down) * side,
                             to: Vector2(across + cheek * reach, down + 0.012) * side, width: 0.017 * side)
                }
            }
            // A row of dots across the forehead, each swelling in its turn.
            for dot in 0..<7 {
                let across = 0.5 + (Double(dot) - 3) * 0.062
                let swell = 0.5 + 0.5 * sin(turn * 2 - Double(dot) * 0.9)
                fill(Self.inks[dot % 2 == 0 ? 1 : 2])
                drawEllipse(across * side, (0.13 + 0.012 * abs(Double(dot) - 3)) * side,
                            (0.02 + 0.012 * swell) * side, (0.016 + 0.0096 * swell) * side)
            }
            // A line down the nose, and a mark on the chin.
            drawMark(Self.inks[3], from: Vector2(0.5, 0.36) * side, to: Vector2(0.5, 0.5) * side,
                     width: 0.012 * side)
            drawMark(Self.inks[0], from: Vector2(0.47, 0.9) * side, to: Vector2(0.53, 0.9) * side,
                     width: 0.02 * side)
        }
    }

    /// One stroke of paint with round ends.
    private func drawMark(_ ink: Color, from a: Vector2, to b: Vector2, width: Double) {
        stroke(ink)
        strokeWeight(width)
        strokeCap(.round)
        drawLine(a, b)
        noStroke()
    }

    // MARK: The glasses

    /// A pair of round glasses, placed from the two eyes: a ring before each,
    /// a bridge between them, and an arm from each ring back along the head.
    private func drawGlasses(on face: PhoneFace) {
        let left = face.eyePosition(.left), right = face.eyePosition(.right)
        // Nothing to place them from without the eyes.
        guard left.distance(to: right) > 0.02 else { return }
        // The rings stand a little over three centimeters before the middle
        // of each eyeball, clear of the brow and the bridge of the nose.
        let rim = 0.024, before = 0.032
        // How wide the face is, so the arms can pass outside the head.
        let wide = face.meshPoints.map { abs($0.x) }.max() ?? 0.07
        ambientLight(Color(white: 0.55))
        directionalLight(.white, direction: Vector3(-0.45, -1, -0.55))
        material(.metal(roughness: 0.35))
        fill(Color(hex: 0x1F2630))
        noStroke()
        var centers: [Vector3] = []
        for eye in [left, right] {
            let center = eye + Vector3(0, 0, before)
            centers.append(center)
            withState {
                translate(center)
                rotateX(.pi / 2)
                drawTorus(radius: rim, tube: 0.0018, segments: 48, sides: 12)
            }
        }
        // The bridge joins the two rings on their near sides. On its far side
        // each ring reaches out to a hinge beside the temple, and the arm runs
        // straight back from there, a centimeter outside the face.
        let across = (centers[0] - centers[1]).normalized
        drawCapsule(from: centers[1] + across * rim, to: centers[0] - across * rim, radius: 0.0016)
        for (center, side) in [(centers[0], 1.0), (centers[1], -1.0)] {
            let hinge = Vector3(side * (wide + 0.01), center.y, center.z - 0.004)
            drawCapsule(from: center + across * (side * rim), to: hinge, radius: 0.0016)
            drawCapsule(from: hinge, to: hinge + Vector3(0, -0.004, -0.12), radius: 0.0016)
        }
        noLights()
    }

    // MARK: What the face did

    /// A blink throws sparks from each eye. An opened mouth lets three rings
    /// go, one after another.
    private func react(to event: PhoneExpressionEvent) {
        switch event.expression {
        case .blink:
            for eye in PhoneEye.allCases {
                let from = event.face.worldEyePosition(eye)
                let out = event.face.worldGazeDirection(eye)
                for spark in 0..<14 {
                    // The same fan every time, so a loop's laps are alike.
                    let around = Double(spark) * 2.399963, lift = 0.35 + 0.6 * Double(spark % 5) / 4
                    let aside = Vector3(cos(around), sin(around), 0) * (0.5 + 0.5 * Double(spark % 3) / 2)
                    motes.append(Mote(from: from + out * 0.02, heading: (out * lift + aside).normalized,
                                      born: time + Double(spark % 4) * 0.02, isRing: false,
                                      ink: Self.inks[spark % Self.inks.count]))
                }
            }
        case .mouthOpen:
            // The mouth has no skin to stand on, so it is placed from the
            // eyes: a little over six centimeters under the point between
            // them, in the head's own directions.
            let face = event.face
            let between = (face.eyePosition(.left) + face.eyePosition(.right)) / 2
            let mouth = inRoom(between + Vector3(0, -0.062, 0.02), of: face)
            let out = (inRoom(between + Vector3(0, -0.062, 1.02), of: face) - mouth).normalized
            for ring in 0..<3 {
                motes.append(Mote(from: mouth, heading: out, born: time + Double(ring) * 0.12,
                                  isRing: true, ink: Self.inks[ring]))
            }
        default:
            break
        }
    }

    /// A point given in the head's own meters, stood in the room.
    private func inRoom(_ point: Vector3, of face: PhoneFace) -> Vector3 {
        let placed = face.headTransform * SIMD4<Float>(Float(point.x), Float(point.y), Float(point.z), 1)
        return Vector3(Double(placed.x), Double(placed.y), Double(placed.z))
    }

    /// The sparks and rings in the air, each on its way for under a second.
    private func drawMotes() {
        let life = 0.55
        motes.removeAll { time - $0.born > life || time < $0.born - 1 }
        noLights()
        noStroke()
        for mote in motes {
            let age = (time - mote.born) / life
            guard age >= 0 else { continue }
            let fade = 1 - age
            fill(mote.ink)
            withState {
                if mote.isRing {
                    translate(mote.from + mote.heading * (0.09 * age))
                    // Turned to face the way it is going, and growing.
                    transform(Plane3(origin: .zero, normal: mote.heading).matrix)
                    rotateX(.pi / 2)
                    drawTorus(radius: 0.008 + 0.03 * age, tube: 0.0014 * fade + 0.0004, segments: 36, sides: 8)
                } else {
                    // Out from the eye, slowing, and falling a little.
                    let gone = 0.16 * (1 - (1 - age) * (1 - age))
                    translate(mote.from + mote.heading * gone + Vector3(0, -0.05 * age * age, 0))
                    drawSphere(radius: 0.0034 * fade + 0.0006, segments: 12, rings: 6)
                }
            }
        }
    }

    // MARK: Input

    /// A click on the face moves the bead to the spot of skin under it.
    override func mousePressed() {
        guard let view = device.latestCamera, let face = device.latestFace else { return }
        let ray = view.ray(through: mouse, covering: Vector2(width, height))
        if let spot = face.textureCoordinate(along: ray) { bead = spot }
    }

    override func keyPressed() {
        switch key {
        case " ":
            guard let recording = recorded.recording else { return }
            if recording.isPlaying { recording.pause() } else { recording.play() }
        case "r", "R":
            bead = Self.betweenTheBrows
        default:
            break
        }
    }
}
```
