#### <sup>[Ollin](../index.md) → [Guide](index.md) → Chapter 40</sup>

---

# 40. Augmented reality

<img src="Images/40-AugmentedReality/BallInTheWall.jpg" alt="A phone's picture of a tiled wall with a poster of red, blue, and yellow rectangles on it, and a blue post standing in front. A yellow ball floats just in front of the wall beside the poster. Around the place it came out of, an arch of the wall's own tiles stands out from the wall, each a small gray slab with dark sides, and two of them carry pieces of the poster" width="560">

Augmented reality, AR for short, puts a drawing into a camera's picture. The drawing keeps its place in the room while the camera moves. This chapter draws in a room an iPhone filmed. You play a recording that knows where the camera stood on every frame, and you look through that camera. Then you draw on a wall in meters, lift pieces of the wall off it, and let the real wall hide what goes behind it. The ball at the top does all of that in a recording that ships with Ollin, so the chapter needs no phone. After it come more ways to work on a surface, a face to draw on, and the recording's own sound. Last is the same sketch running live with a phone in your hand: on the cable, and then on the phone alone, where it keeps a picture or a video of itself.

## A film that knows where the camera stood: a recording

[Chapter 39](39-thephoneasasensor.md#ollins-own-app-ollin-capture)'s capture app, Ollin Capture, sends what the phone senses down a cable. It also **records**. Press Record, with no cable, and the phone writes the camera's video to a folder. Beside every frame of the video, it writes where the camera stood and what its lens was. The phone knows both from ARKit's world tracking, which follows the phone through the room while it films. Nothing has to be worked out from the footage afterwards.

A recording is where an AR sketch starts, even one that will end up live. It plays the same frames every time, so you can work on one corner of a wall for an hour. It needs no phone on the desk. And an export of the sketch shows the same frames on every run.

One recording ships with Ollin, in the folder of the `PhoneWallTiles` example. It is six seconds of a small room with a tiled wall and a poster. The room was drawn on the Mac and written with the code the phone runs, so it stands in for a room of your own. Make `MySketches/Room.swift`:

```swift
import Ollin
import OllinPhone

final class Room: Sketch {
    // The picture's own proportion, held upright: three across, four down.
    override var canvasSize: CanvasSize { .size(1080, 1440) }

    let device = PhoneDevice(playing: try! PhoneRecording(
        path: "Examples/3D/Phone/PhoneWallTiles/Wall.ollinrecording"))

    override func setup() {
        device.start()
    }

    override func draw() {
        background(.black)
        guard let view = device.latestCamera else { return }
        drawPhonePicture(view)          // the camera's picture, covering the canvas
    }
}
```

Run it with `swift run OllinLive MySketches/Room.swift`. The path is read from the folder you run in, so run from the repository's root, as [Chapter 1](01-helloollin.md) did. The film plays and loops, and the camera drifts from side to side in front of the wall.

`PhoneDevice(playing:)` is the object Chapter 39 read, fed by a recording in place of the cable. Everything that chapter read from a phone reads the same way here, and each reading arrives at the frame it was sensed on. `device.latestCamera` is the camera of the frame the recording stands on. It is `nil` until the first frame arrives, which is what the `guard` is for. `drawPhonePicture(_:)` draws that frame's picture. It scales the picture to cover the canvas and crops what overflows, so a canvas in the picture's proportion shows all of it.

The recording plays on the sketch's clock, and that is why `device` is a property of the sketch. The sketch hands its clock to the objects it holds, and a device made inside `draw()` would never receive it. Pause the sketch and the recording holds. Under an export, frame `n` of the output is the same frame of the recording on every run.

<img src="Images/40-AugmentedReality/RecordingAsPath.jpg" alt="Left, three frames of a recording, numbered 1 to 3: the same tiled wall and poster seen from the middle, from the right, and from the left. Right, the room from above: a long line labeled the wall, a small square labeled a table top, and an orange loop under them with three numbered dots on it, a short line leaving each dot toward the wall. A caption reads 180 frames in six seconds, each with its place and its lens" width="680">

The figure shows what the folder holds. On the left are three of its 180 frames. On the right is the room from above, drawn from the recording alone. The line at the top is the wall and the square is a table top, both found by the phone. The orange loop is where the camera stood on each frame, and a short line leaves each numbered dot the way the camera looked. The frames are a film. The camera's path is what turns that film into a place you can draw in.

To make a recording of your own, the [Phone reference](../docs/3d/phone.md#a-recording) covers the Record button and bringing the folder to the Mac. Give `PhoneRecording(path:)` its path, such as `"~/Movies/Walk.ollinrecording"`, and the same sketch plays it.

## Looking through the phone's camera: camera(_:)

`view` is a `PhoneCamera`. It holds where the camera stood on this frame, which way it looked, and its lens. [Chapter 27](27-3dgently.md#a-camera-and-a-sphere)'s `camera(_:)` took a camera you described. It takes the phone's as well:

```swift
drawPhonePicture(view)
camera(view)                        // a 3D camera that matches the phone's
translate(1.1, 1.1, -0.9)           // a place in the room, in meters
drawSphere(radius: 0.1)
```

Add the three new lines to `draw()`, and a ball sits on top of the green column. It stays there while the camera drifts.

<img src="Images/40-AugmentedReality/PinsHold.jpg" alt="Three frames of the recording side by side, labeled frame 1, frame 41, and frame 61 of 180, the camera farther to the right in each. In every one a yellow pin stands on the green column's top, a red pin on the blue post's top, and a green pin on the poster's top left corner" width="680">

It stays because of what `camera(view)` sets up. The 3D camera stands where the phone stood, with the phone's lens, cropped the way the picture is. So a point of the room lands on the pixel the picture has of that point. The ball itself never moves. On every frame the camera is where the phone was, and the ball is drawn from there. The figure stands three pins in the room and shows three frames. Each pin stays on its own thing, which is the column's top, the post's top, or a corner of the poster.

The three numbers are a place in the room. The room is measured in meters, with y pointing up, and its origin is wherever the phone was when its session began. This room was drawn on the Mac, with its origin on the floor. So the column's top is known to be at 1.1, 1.0, and -0.9, and the ball's middle goes one radius above it. In a room of your own you rarely know such numbers. [A click that stays on the wall](#a-click-that-stays-on-the-wall-pinned-points) turns a click into one.

Two limits come with this. A drawn thing is only as steady as the phone's sense of where it is. That sense drifts a little over a long walk, and a pinned thing slides against the picture by as much. And nothing hides the ball yet. Move it behind the column and it still draws over the column, because the picture under it is flat. [A real wall that hides a drawn thing](#a-real-wall-that-hides-a-drawn-thing-occluding) deals with that.

## What the phone found in the room: flat surfaces and light

A recording made in the app's **Room** mode carries more than the camera. As the phone looks around, ARKit finds the room's flat surfaces and measures its light. Both are in the folder, and both arrive on `device` as they would from a phone on the cable. A recording made in World mode carries depth frames in their place, and no surface.

### Somewhere to stand: flat surfaces

ARKit finds a floor, a table top, or a wall as a single flat patch, and grows it as the phone looks around. It needs no LiDAR for this, so any phone that runs the app finds them. A flat surface is for standing something on, and for drawing on.

<img src="Images/40-AugmentedReality/RoomAsPlanes.jpg" alt="Left, three flat surfaces of a staged room corner drawn as outlined polygons: a green floor, a blue-gray wall, a tan table top. Right, the same three in plain gray with a metal ball resting on the table. Below, three color swatches labeled lamp 480 lm 2700 K, room 1000 lm 5000 K, window 900 lm 9000 K, running from warm brown through cream to pale blue" width="680">

```swift
if let table = device.planes.largest(of: .table) {
    withState {
        translate(table.center + table.normal * 0.15)
        drawSphere(radius: 0.15)
    }
}
```

`largest(of:)` picks by real area, measured on the outline rather than on the box around it, so a long thin shelf never wins. In the recording, the one table top is the orange cube at the lower left. Add these lines, and a ball rests on the cube whenever the camera looks that way. For the ground, `floor` is the one to reach for, because it answers early. It gives you the labeled floor once ARKit has decided, and the lowest flat surface until then.

Every surface carries that outline: a convex polygon around everything the phone has seen of it. `plane.mesh` fills it in, and `plane.outline` is the same loop closed, ready for `drawTube`.

### The light in the room: PhoneLight

The phone also measures how bright and how warm the room is, a few times a second. It does this in every mode that runs the camera through ARKit, and a recording keeps the readings. That leaves out Touch, Selfie, and Sketch, which run no ARKit session. It is for a sketch whose light follows the room's.

```swift
ambientLight(device.latestLight?.ambient ?? Color(white: 0.4))
directionalLight(.white, direction: Vector3(-0.45, -1, -0.55))
```

`ambient` is the room's own white, turned down by how bright the room is. The three swatches under the picture above are three readings, a lamp, a working room, and a window. Put the first line before the ball, and the ball takes the tone of the room it stands in. With a phone on the cable, switching a lamp on warms the sketch with it.

Only Face mode knows where the light comes from, because ARKit works that out from the shading on a face. A camera that faces the room has no face to read. So Room mode gives you brightness and color, and the second line is a key light you aim yourself.

## A wall as a canvas in meters: withPlane(_:)

The wall in the recording is one of those surfaces, and `withPlane(_:)` draws in its coordinates. Inside the block, the wall's middle is the origin. x runs along the wall, to the right of someone facing it. y climbs the wall, and z comes straight out of it into the room. All three are in meters.

```swift
guard let wall = device.planes.largest(of: .wall) else { return }
withPlane(wall) {
    translate(-0.75, 0.25, 0)                       // left of the wall's middle, and a little up
    drawBox(width: 0.5, height: 0.5, depth: 0.05)   // a slab half a meter square, on the wall
}
```

<img src="Images/40-AugmentedReality/WallInMeters.jpg" alt="Three frames of the recording, labeled frame 1, 41, and 61 of 180. On the wall in each, three arrows leave one point beside the poster: a red one along the wall labeled x, a green one up it labeled y, and a short blue one out toward the camera labeled z. A flat yellow square lies on the wall to their left, covering the same four tiles in every frame" width="680">

The figure draws the three directions as arrows from the wall's middle. They run a meter along x, a meter up y, and half a meter out along z. The yellow slab is the one in the listing. It is half a meter square, and the wall's tiles are a quarter of a meter. So it covers two tiles each way, in every frame. You never worked out how the wall is turned to the camera. The surface carries that, and `withPlane(_:)` scopes it the way `withState` scopes a transform.

Give `translate` three numbers inside the block. With two numbers it is the 2D `translate`, which moves the canvas in pixels, and the slab stays at the wall's middle. A 2D call such as `drawCircle` still draws on the canvas too. A flat drawing reaches a wall through a layer, as [a flat drawing on a wall](#a-flat-drawing-on-a-wall-an-image-on-four-points) shows.

A floor or a table top has no up of its own. On those, x is the room's x and y runs along the room's -z. The directions hold still while the phone widens a surface, and the origin moves with the outline's middle. `wall.plane` is the surface as a [`Plane3`](../docs/drawing/geometry.md#plane3), a value you can keep once the surface has settled. `withPlane(_:)` takes that as well.

## The picture as paint: painted(with:)

A slab drawn on the wall covers the wall. `painted(with:)` does something else. It paints the meshes drawn in its block with the camera's picture, as the phone saw it. Every point of a mesh shows the pixel the camera had of that point. A painted slab left where it lies shows the wall's own pixels, and you cannot see it. Move it, and it carries those pixels along. It is for a piece of the real wall that you can move.

```swift
withPlane(wall) {
    translate(0.25, 0.5, 0)                 // before the block: where the slab lies on the wall
    painted(with: view) {
        translate(0, 0, 0.45)               // inside it: the move, pixels and all
        drawBox(width: 0.5, height: 0.5, depth: 0.02)
    }
}
```

<img src="Images/40-AugmentedReality/LiftedTile.jpg" alt="One frame of the recording three times, with a thin yellow outline around a square slab over the poster's top left corner. Left, labeled painted where it lies, nothing changes: the outline lies flat on the wall and the picture is untouched. Middle, labeled moved inside the block, it carries its pixels: the outline floats off the wall and the square inside it shows the poster's corner and four tiles, shifted. Right, labeled moved before the block, it takes the pixels there: the outline floats in the same place and the picture inside it is the plain picture" width="680">

One rule decides what a painted mesh shows. **A mesh takes its pixels where it stands when the block opens.** A transform made before the block places the mesh. A transform made inside the block moves it afterwards. The figure runs one frame three ways, with an outline around the slab so you can find it. On the left the slab is painted where it lies, and nothing changes. In the middle it is moved out inside the block, and a corner of the poster comes with it. On the right it is moved out before the block. There it takes the pixels the picture already shows in its new place, so it disappears.

So a scene of several placed things wants a block around each one, with the placement outside. One block around the whole scene would read every transform in it as a move.

A stretch counts as a move too. Paint a thin slab flat on the wall, scale it along z inside the block, and it grows out of the wall. Its face shows the tile it came from. Its sides show that tile's edge pixels, drawn out into streaks. The finished sketch raises its tiles this way, for a reason the middle panel shows. The camera's picture is still flat on the canvas. So the lifted corner of the poster shows a second time, on the wall behind it. A tile that stays joined to the wall covers the place it left.

A painted mesh is unlit, because the picture already holds the light of the room it was taken in. `fill(.white)` leaves the picture as it is, and any other fill multiplies it. A gray fill is how the sketch shades the sides of a raised tile.

## A real wall that hides a drawn thing: occluding

The picture is flat, so everything you draw lands on top of it. A ball placed behind the wall still shows, as if the wall were glass. `occluding { }` gives a real thing its depth back. It draws the meshes in its block as depth alone, [Chapter 27](27-3dgently.md#depth-that-hides-things-the-depth-test)'s depth test with nothing to see. Each mesh hides whatever is drawn behind it afterwards, and puts no color on the canvas. It is for the real things in the picture that a drawn thing should be able to go behind.

```swift
drawPhonePicture(view)
camera(view)
occluding { drawMesh(wall.mesh) }       // the real wall, as depth alone
```

<img src="Images/40-AugmentedReality/BehindTheWall.jpg" alt="One frame of the recording twice, with an orange ring standing square to the wall. Left, labeled drawn over the picture, all of the ring shows: the whole ring is visible as if it floated in front of the wall. Right, labeled after occluding with the wall, the wall hides the half behind it: only the half of the ring in front of the wall shows, and the tiles where the rest went are untouched" width="680">

The figure draws a ring that passes through the wall. Without the block, all of the ring shows. With the wall's mesh drawn inside `occluding { }` first, the half behind the wall is gone, and the picture of the wall shows through untouched.

Order matters, as it does for anything that hides. What was drawn before the block is already on the canvas and stays. The block also hides only as much as the meshes you give it. Here that is the wall. The post and the column are in the picture, and they are not among the recording's surfaces. So a thing drawn low on the wall draws over them. `device.planes.mesh` is every surface the phone found as one mesh, for when a floor and a table should hide things too.

## Putting it together: the ball in the wall

The finished sketch is the ball at the top of the chapter. It travels in a figure of eight over the wall, and it dives through the wall and comes out again on the way. Each time it crosses, the wall's own tiles lift in a ring that spreads from the place. It puts together the recording, the phone's camera, and the room's light. On the wall it uses the wall's coordinates, the picture as paint, and the wall as the thing that hides. Make `MySketches/BallInTheWall.swift`:

```swift
import Ollin
import OllinPhone

final class BallInTheWall: Sketch {
    // The camera's own proportion, held upright: three across, four down.
    override var canvasSize: CanvasSize { .size(1080, 1440) }
    // One lap of the recording, so an export loops.
    override var loopDuration: Double? { 6 }

    // The recording, played through the object the cable feeds.
    let device = PhoneDevice(playing: try! PhoneRecording(
        path: "Examples/3D/Phone/PhoneWallTiles/Wall.ollinrecording"))

    let tile = 0.25        // the side of one real tile, in meters
    let thin = 0.004       // how thick a tile is while it lies in the wall

    override func setup() {
        device.start()
    }

    override func draw() {
        background(.black)
        guard let view = device.latestCamera,
              let wall = device.planes.largest(of: .wall) else { return }

        drawPhonePicture(view)             // the camera's picture, covering the canvas
        camera(view)                       // the camera that took it

        // Lit the way the room was lit.
        ambientLight(device.latestLight?.ambient ?? Color(white: 0.4))
        directionalLight(.white, direction: Vector3(-0.45, -1, -0.55))
        noStroke()

        // The real wall, as depth alone: it hides what goes behind it.
        occluding { drawMesh(wall.mesh) }

        withPlane(wall) {                  // x along the wall, y up it, z out of it
            // The tiles a ring has reached, each pushed out of the wall.
            for row in -1 ..< 6 {          // from just above the furniture to the top
                for column in -7 ..< 7 {
                    let middle = Vector2((Double(column) + 0.5) * tile, (Double(row) + 0.5) * tile)
                    let out = 0.3 * ripple(at: middle)
                    if out > 0.004 { drawTile(at: middle, out: out, view: view) }
                }
            }

            // The ball, where it is now.
            let place = path(at: time)
            material(.dielectric(roughness: 0.35))
            fill(Color(hex: 0xF2B63B))
            translate(place.x, place.y, depth(at: time))
            drawSphere(radius: 0.16)
        }
    }

    // Where the ball is over the wall, in the wall's meters: a figure of
    // eight, once around in a lap.
    func path(at t: Double) -> Vector2 {
        let turn = t / 6 * .tau
        return Vector2(0.9 * sin(turn), 0.3 + 0.4 * sin(2 * turn))
    }

    // How far out of the wall the ball is. It crosses the wall's face every
    // second and a half, in and then out.
    func depth(at t: Double) -> Double {
        0.42 * cos(t / 3 * .tau)
    }

    // How far a tile is pushed out, 0 to 1: a ring spreads from each place
    // the ball crossed the wall, and dies away as it goes.
    func ripple(at tileMiddle: Vector2) -> Double {
        var push = 0.0
        for crossing in 0 ..< 4 {                               // the lap's four crossings
            let crossed = 0.75 + Double(crossing) * 1.5         // when, in seconds
            var age = (time - crossed).truncatingRemainder(dividingBy: 6)
            if age < 0 { age += 6 }                             // one from the lap before
            if age > 2 { continue }                             // it has died away
            let crest = 0.5 + age * 0.8                         // how far the ring has spread
            let toCrest = abs(tileMiddle.distance(to: path(at: crossed)) - crest)
            push = max(push, sin(age / 2 * .pi) * max(0, 1 - toCrest / 0.25))
        }
        return push
    }

    // One tile of the wall, pushed `out` meters. Everything before `painted`
    // lays a thin slab on the tile, where it takes its pixels. Everything
    // inside moves it.
    func drawTile(at middle: Vector2, out: Double, view: PhoneCamera) {
        let side = tile * 0.92                                   // the grout stays on the wall
        withState {
            translate(middle.x, middle.y, 0)
            painted(with: view) {
                withState {                                      // the sides: the tile's edges, drawn out
                    translate(0, 0, out / 2)
                    scale(1, 1, out / thin)
                    fill(Color(white: 0.55))
                    drawBox(width: side, height: side, depth: thin)
                }
                translate(0, 0, out)                             // the face: the tile itself
                fill(.white)
                drawBox(width: side, height: side, depth: thin)
            }
        }
    }
}
```

Here is what each part does:

- **The room.** `draw()` opens the way every step did. It draws the picture, looks through the phone's camera, and lights the scene from the recording's own reading. Then the wall goes in as depth alone, before anything that should be able to go behind it.
- **The ball.** `path(at:)` gives its place on the wall and `depth(at:)` how far out of the wall it is, both from the clock. The depth swings between 42 centimeters in front of the wall and 42 behind. Behind it, the occluding wall hides the ball. The ball is drawn last inside `withPlane`, so its `translate` moves nothing else.
- **The ring.** The depth crosses zero four times a lap, and each crossing starts a ring. `ripple(at:)` asks, for one tile, how near the crest of each ring is. A ring starts half a meter out, so it never covers the ball, and it spreads at 80 centimeters a second. The sine makes it rise and die away over two seconds. The function keeps no memory. It works from the clock alone, so the first frame of a lap already holds the last ring of the lap before, and the loop closes.
- **A raised tile.** `drawTile` is the stretch from the paint step. A thin slab lies on its tile when `painted` opens, which is where it takes its pixels. Inside, one copy is stretched from the wall out to `out` under a gray fill, and its sides become the tile's shaded edges. A second copy moves to the front under a white fill, and it is the tile's face.
- **Where the tiles stop.** The rows begin just above the furniture. Nothing in the recording says where the post and the column stand, so a tile raised behind them would draw over them.

Then make it yours:

- Change what crosses the wall. Replace `drawSphere(radius: 0.16)` with `drawBox(size: 0.28)`, and put `rotateY(time / 6 * .tau)` on the line before it. A cube crosses the wall in the ball's place, turning once a lap, and the wall cuts it wherever it stands.
- Tint the wave. Change the face's `fill(.white)` to `fill(Color(hex: 0xFFD9A0))`, and every raised tile takes a warm cast while the wall under it keeps its own color.
- Use a wall of your own. Record one in Room mode, give `PhoneRecording(path:)` its folder, and set `tile` to the size of your tiles. If your tiles' edges do not pass through the wall's middle, add an offset to `middle`.

`swift run OllinLive MySketches/BallInTheWall.swift --export-loop wall.mp4` writes one lap as a video that loops, since the sketch declares its `loopDuration`. The recording plays on the sketch's clock, so the file shows the same frames every time you make it.

## More to do on a surface: a click that stays, a flat drawing, and the room's whole shape

The sketch worked on one wall, with meshes it placed by numbers. More belongs to drawing on what a camera saw. A click can choose the place. Depth can give a wall where the phone reported none. A flat 2D drawing can lie on the wall. And the phone can hand over the whole shape of the room, of which the flat surfaces are only a part. A printed picture is a surface too, one the phone can follow as it moves, and [Chapter 39's markers](39-thephoneasasensor.md#a-picture-it-knows-markers) hand it over as a frame to draw in.

### A click that stays on the wall: pinned points

A click is a place on the canvas. Followed into the room along the camera's line of sight, it meets a surface at one point. That point stays put while the camera moves. It is for choosing a place by eye, such as the four corners of a poster, in a room whose numbers you do not know. The line of sight is a [`Ray3`](../docs/drawing/geometry.md#ray3), the value [Chapter 39's wand](39-thephoneasasensor.md#pointing-at-it-with-the-phone-the-wand) pointed with.

```swift
var pins: [Vector3] = []

override func mousePressed() {
    guard let view = device.latestCamera,
          let wall = device.planes.largest(of: .wall) else { return }
    let ray = view.ray(through: mouse, covering: Vector2(width, height))
    if let spot = wall.plane.intersection(with: ray) { pins.append(spot) }
}
```

`ray(through:covering:)` is the line of sight through a point of a canvas the picture covers. `intersection(with:)` is where that line meets the wall, or `nil` when it misses. A pin is a plain `Vector3` that the sketch keeps. Draw at it on any later frame and it lands on the same spot of the wall. Hold the recording while you click, with `device.recording?.pause()`, so the frame under the pointer is the one the pin is made on. [`PhonePoster`](../examples/3d/phone/phoneposter.md) pins a poster's corners this way, and [a point that stays put](../docs/3d/surfaces.md#pinned-points) has the form that asks the active camera.

### A wall the phone did not report: a surface from depth

Every surface so far came from Room mode, which finds them. A recording made in World mode has none. It holds the picture, the camera's place, and a depth map, which is a distance for every sample of a grid. Where the scene is flat, those samples lie on one plane, and the plane can be worked out from them. It is for a recording that carries no surface, and for choosing a wall by eye among the ones a phone did find. The fit starts at one sample, fits a plane to its neighbors, and takes in every sample around them that lies on it. Rolf Adams and Leanne Bischof set out that way of growing a region from a seed in 1994.

```swift
var wall: PhonePlane?

override func mousePressed() {
    if let clicked = device.surface(under: mouse, covering: Vector2(width, height)) {
        wall = clicked                  // kept in the sketch from here on
    }
}
```

`surface(under:covering:)` returns the surface under a point of the canvas. Where the phone found surfaces, it is the nearest one the line of sight meets. So the same click chooses among a Room recording's walls. Where it found none, the surface is fitted from the depth under the point. Either way the answer is a `PhonePlane`, and `withPlane(_:)` draws on it. Keep the one you are handed. A fitted surface is one frame's reading, and fitted again on every frame it trembles with the depth's noise.

`surface(at:)` asks with a point of the room instead. Turn a click into the point it fell on and keep that point in a `@Param`. The choice is then saved into the sketch, and an export finds the same wall. [`PhoneWallTiles`](../examples/3d/phone/phonewalltiles.md) chooses its wall this way: click a wall in any recording and its tiles come out of that one. [The surface under a click](../docs/3d/surfaces.md#found-from-depth) is the reference, and [a flat surface from depth](../docs/3d/rgbd.md#surface) is the fit itself, for any depth source.

### A flat drawing on a wall: an image on four points

`withPlane(_:)` carries 3D drawing onto a wall. A flat 2D drawing gets there through a layer. `drawImage(_:topLeft:topRight:bottomRight:bottomLeft:)` lays an image on four points of space. The corners go to the four points, and the rest lands where a flat sheet through them would carry it. It is for a new picture over a real poster, a screen, or a sign. The mapping is the one Paul Heckbert set out in 1989 for carrying a square onto any four-sided shape.

<img src="Images/40-AugmentedReality/PosterReplaced.jpg" alt="Three frames of the recording, labeled frame 1, 41, and 61 of 180. In each, the poster on the wall has been covered by a dark sheet with orange and yellow rings and two pale bars, and the sheet keeps to the poster's four corners as the camera moves to the right" width="680">

```swift
let sheet = makeRenderTarget(width: 700, height: 950)       // once, in setup()

withTarget(sheet) {                                         // any 2D drawing
    background(Color(hex: 0x14161B))
    drawCircle(350, 430, 250)
}
drawImage(sheet.image, topLeft: pins[0], topRight: pins[1],
          bottomRight: pins[2], bottomLeft: pins[3])
```

The layer is [Chapter 19](19-layersandeffects.md#a-drawing-you-can-hold-render-targets)'s render target, and the four points are pins like the ones above, taken in order around the sheet. The image is unlit, and it has depth. It hides what is behind it wherever it is not clear, so a layer cleared to nothing leaves the wall showing between its marks. The figure covers the recording's poster with rings drawn in 2D. [An image on four points](../docs/3d/surfaces.md#an-image-on-four-points) is the reference, and [`PhonePoster`](../examples/3d/phone/phoneposter.md) redraws its poster every frame.

### A surface the phone already built: the room mesh

The flat surfaces leave out everything in a room that is not flat. On a phone with LiDAR, ARKit also rebuilds the whole room as a mesh while you walk, and Ollin Capture streams it. [Chapter 38](38-depth.md#from-the-cloud-to-a-surface-surface-reconstruction) rebuilt a surface like it on the Mac, from points. It is for a room to light, to hide things behind, or to bounce something off. Tap **Room** and what arrives already has faces and normals, and every triangle already knows what it is.

<img src="Images/40-AugmentedReality/RoomAsSurface.jpg" alt="Three copies of a small staged room corner side by side: the whole room in one pale material, the same room painted green for floor, blue-gray for walls, tan for a table and pink for a seat, and the same room with the walls dropped so only the floor, table and seat slabs float in place" width="680">

```swift
var room = Mesh(positions: [], indices: [])
var built: Int?

override func draw() {
    if device.sceneMeshVersion != built {      // only when a block changed
        built = device.sceneMeshVersion
        room = device.sceneMesh.mesh
    }
    drawMesh(room)
}
```

The `sceneMeshVersion` check matters. The room arrives in **blocks**. ARKit cuts the space into pieces and keeps improving each piece as you look at it again. So a piece turns up many times, and the newest reading replaces the last. `sceneMeshVersion` changes whenever that happens. A scanned room reaches hundreds of thousands of triangles, and `draw()` runs 60 or 120 times a second. Rebuilding the mesh every frame is the mistake to avoid here.

Then the labels. Every triangle carries a `PhoneSurface`, one of wall, floor, ceiling, table, seat, window, door, or unclassified. So the same room can be asked for three ways, as the three copies in the picture show:

```swift
let scan = device.sceneMesh
scan.mesh                          // all of it, one mesh
scan.mesh { surface in            // a color per triangle
    switch surface {
    case .floor: return Color(hex: 0x5FB681)
    case .wall:  return Color(hex: 0x9AA4BC)
    case .table: return Color(hex: 0xE8B25A)
    case .seat:  return Color(hex: 0xDD7A66)
    default:     return .white
    }
}
scan.mesh(of: .floor, .table, .seat)   // only the labels you ask for
```

A real scan has far more blocks than the picture.

Early in a scan almost everything reads `unclassified`, because ARKit decides what a surface is only once it has seen enough of it. `foundSurfaces` tells you which labels have appeared so far, so a sketch that keys off labels can say so while the room fills in.

Drawn inside `occluding { }`, the mesh hides a drawn thing behind a chair's back as well as behind a wall. A flat surface is steadier and costs less, so reach for the mesh when the thing that hides is not flat. The `3D/Phone/PhoneRoomMesh` example paints the room by label, with a keyboard key to keep only the flat things you could set something down on.

## More to draw on: a face

A wall holds still. A face turns, nods, and changes shape while it talks, and the phone follows all of it. In Face mode it looks through its front camera and hands over the face as a mesh that moves with the skin. [Chapter 39](39-thephoneasasensor.md) read the same face as a gaze. A recording made in that mode plays back like any other, so a face is one more thing in a picture to draw on.

### Paint that follows the skin: a layer on a face

Face paint is a flat drawing that stays on the skin. The mesh makes that possible. Each of its points carries a texture coordinate, which is a place in a flat image, and the points keep their coordinates while they move. So a drawing laid by those coordinates goes wherever the skin goes. It is for a mask, a tattoo, makeup, or a pattern that reacts to the face it is on. Snapchat brought it to millions of phones in September 2015 with its Lenses, on face tracking from a company called Looksery. Apple put a depth camera on the front of the iPhone in 2017, and ARKit has handed over the face as a mesh since then.

<img src="Images/40-AugmentedReality/FaceInItsPicture.jpg" alt="Four frames of a mannequin's head before a tiled wall, labeled by frame, the head turned a little more or the other way in each and its mouth open in the last. Three colored stripes on each cheek, a row of dots across the forehead, and a pale line down the nose keep their places on the skin in every frame. Round dark glasses sit before the eyes, and in the turned frames the arm on the far side passes behind the head" width="680">

```swift
let device = PhoneDevice(playing: try! PhoneRecording(
    path: "Examples/3D/Phone/PhoneFacePaint/Face.ollinrecording"))
var paint: RenderTarget!

override func setup() {
    paint = makeRenderTarget(width: 1024, height: 1024)
    device.start()
}

override func draw() {
    guard let view = device.latestCamera, let face = device.latestFace else { return }
    drawPhonePicture(view)
    camera(view)
    withTarget(paint) {                             // the paint, a flat drawing
        background(Color(white: 0, alpha: 0))
        stroke(Color(hex: 0xF25C3B))
        strokeWeight(18)
        drawLine(230, 600, 380, 612)                // a stripe on one cheek
        drawLine(644, 612, 794, 600)                // and its twin on the other
    }
    withFace(face) {
        occluding { drawMesh(face.occluder()) }
        painted(with: paint.image) { drawMesh(face.mesh()) }
    }
}
```

The recording is the one that ships with the `PhoneFacePaint` example, read by a path from the repository's root. It shows a mannequin's head drawn on the Mac, and one made on a phone in Face mode plays the same way. `withFace(_:)` draws in the head's own meters, as `withPlane(_:)` draws in a wall's. `painted(with:)`, given an image and no camera, lays the image on a mesh by the mesh's own texture coordinates. Where the layer is clear, nothing is drawn. The layer is the face's own map. Across it is across the face, and down it runs from the forehead to the chin, the same for every face. The `occluding` line before it draws the head as depth alone, so the paint on the far cheek of a turned head stays behind the nose. [Drawing on a face in its picture](../docs/3d/phone.md#drawing-on-a-face-in-its-picture) is the reference, and [paint by a mesh's own coordinates](../docs/3d/surfaces.md#paint-by-a-meshs-own-coordinates) covers any mesh.

A front camera's picture is a mirror, and the phone hands the face over mirrored with it. So the paint lands where it should, and writing in the room behind reads backward. `view.isMirrored` says so, and [a face's picture is a mirror](../docs/3d/phone.md#a-faces-picture-is-a-mirror) says how to show the scene unmirrored.

### Something worn: glasses the head hides

Glasses do not follow the skin. They sit on the head and turn with it, and the head hides the arm that passes behind it. That takes two things the face already gives. The head's transform is rigid, so a thing drawn inside `withFace(_:)` turns with the head and ignores a smile. And `face.occluder()` is the head as something that hides.

```swift
withFace(face) {
    occluding { drawMesh(face.occluder()) }
    for eye in PhoneEye.allCases {
        withState {
            translate(face.eyePosition(eye) + Vector3(0, 0, 0.03))      // three centimeters before the eye
            rotateX(.pi / 2)
            drawTorus(radius: 0.024, tube: 0.002)
        }
    }
}
```

The phone measures the face and nothing behind it, so the mesh stops at the temples. `occluder()` adds a rough rest of the head behind the mesh, sized from the face's own width and height. It is kept a little small, so it hides too little before it hides too much. The same call closes the mesh's openings over the eyes from behind.

A thing that should move with the skin, such as a stud or a tear, rides a spot of it. `face.surface(at:)` takes a texture coordinate and returns that spot as a small surface for `withPlane(_:)`. `face.textureCoordinate(along:)` finds the coordinate under a click, and kept in a `@Param` it names that spot on every later frame. [A place on the skin](../docs/3d/phone.md#a-place-on-the-skin) has both.

### A blink to wait on: expressions as events

The phone reads the face's expression as 52 numbers, one for each small movement: an eyelid, a corner of the mouth, the jaw. They descend from the Facial Action Coding System, in which Paul Ekman and Wallace Friesen listed the visible movements of a face in 1978. A number is a level. *Did they just blink?* is a different question, since a blink happens once. An event is for the moment something starts: a burst when the eyes shut, a sound when the mouth opens.

```swift
for event in device.expressions.events() where event.expression == .blink {
    sparkle(at: event.face.worldEyePosition(.left))
}
```

`events()` hands over each expression once, on the reading where it begins, with the face that did it. `.blink`, `.mouthOpen`, `.smile`, and a few more have names, and any of the 52 numbers can be one: `PhoneExpression(.jawLeft)`. Each has two levels. It begins at one and is over only under a lower one, so a mouth held half open opens once. Otto Schmitt described that two-level trigger for a vacuum-tube circuit in 1938. `isShowing(_:)` says whether it is still going on, and `face.expression(.smile)` is the level itself. Out of a recording, the events fall on the same frames in every run. [Expressions as events](../docs/3d/phone.md#expressions-as-events) is the reference, and [`PhoneFacePaint`](../examples/3d/phone/phonefacepaint.md) puts the three entries in one sketch.

## More of a recording: its sound

A recording holds more than a picture and a place. The phone's microphone was on while it filmed, and what it heard is in the folder too.

### What the microphone heard: a recording's sound

A recording made with the microphone allowed keeps the room's sound beside its picture, and a sketch that plays the recording plays that sound. It is for a piece whose room should be heard: a knock on the wall the sketch draws on, a voice, the street outside. The sound has to stay on its picture, and how close is a known number. Broadcasters measured it for a 1998 recommendation of the ITU. A viewer starts to notice sound that comes about 45 thousandths of a second before its picture, and sound that comes about 125 after.

```swift
let device = PhoneDevice(playing: try! PhoneRecording(path: "~/Movies/Knock.ollinrecording"))

override func setup() {
    device.recording?.volume = 0.6      // 0 to 1; isMuted = true for none
    device.start()
}
```

Nothing switches the sound on. It follows the recording, and the recording follows the sketch's clock. Pause the recording and the sound stops. Seek, and it moves. At the end of a lap it starts over with the picture. `volume` sets how loud it is, and `isMuted` turns it off. `--export-video` writes it into the file on the same frames, beside what the sketch's own instruments play, as [sound in an export](../docs/output/export.md#sound) describes. Ollin keeps the sound within two thousandths of a second of its place. The recordings that ship with the examples were drawn on the Mac and are silent, so try this with one of your own. [Its sound](../docs/3d/phone.md#its-sound) is the reference.

## The same sketch, live: on the cable, and on the phone alone

Everything so far played a recording. The same `draw()` runs with a phone plugged in, because a recording and the cable feed one object. The camera's picture comes up the cable, and the result can go back down to the phone's screen. Built for the phone, the same sketch runs there with no cable at all.

### The camera's picture off the cable: a live `PhoneDevice`

A `PhoneDevice` made with no recording reads the phone on the cable, as it did all through Chapter 39. It is for seeing a sketch in the room you are standing in, after working it out on a recording.

```swift
let device = PhoneDevice()

override func setup() {
    device.use(.room)               // ask the phone for Room mode
    device.start()
}
```

`draw()` does not change. Reading the picture is what asks the phone for it. The first `drawPhonePicture(view)` opens a connection of its own, and the phone starts sending its camera as video. Each picture arrives with where the camera stood when it was taken, and that is the camera `latestCamera` hands you. So the pose a sketch draws through is the pose of the picture it draws on. A pinned thing keeps its place while you walk. The picture is `nil` for the first few frames. `drawStatus(device.waitingMessage, style: .info)` says what the sketch is waiting for until a phone answers.

A pin made in a recording is a place in that recording's room, and the room you stand in is another place. So a sketch that serves both keeps a set of places for each. [`PhoneViewfinder`](../examples/3d/phone/phoneviewfinder.md) does that. It reads the phone when one is there and a recording when none is, through one `draw()`. [The camera's picture on the cable](../docs/3d/phone.md#the-cameras-picture-on-the-cable) has the rest.

### A viewfinder: the camera's picture under the sketch

A live AR sketch has a problem a recording did not. The picture is on the Mac, and you are across the room holding the phone. `show(_:)` sends every frame the sketch draws down the cable to the phone's screen, which [Chapter 48](48-handingitover.md#leaving-it-on-the-mac-the-phone-as-the-sketchs-screen) teaches on its own. It keeps whatever mode the sketch asked the phone for. Ask for a camera mode beside it, and the phone in your hand becomes a **viewfinder**. The sketch is still running on the Mac. It is for a sketch that draws in the room, where you have to walk around to see whether things sit right. Film crews call the arrangement a simulcam. On *Avatar*, in 2009, the computer's picture was laid over the camera's and shown in the camera's own monitor while it filmed.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/40-AugmentedReality/ViewfinderLoop-dark.jpg">
  <img src="Images/40-AugmentedReality/ViewfinderLoop.jpg" alt="A diagram of a loop between a phone on the left and a Mac on the right, through a box labeled the cable. Two arrows run from the phone to the Mac, labeled the camera's picture, each with where the camera stood, and surfaces, light, and taps. One arrow runs back, labeled the sketch's frame. On the Mac a card lists draw(): drawPhonePicture(view), camera(view), occluding the surfaces, then your drawing in meters, and a second card reads a tap is a press. The phone's screen and the Mac's live window show the same picture, a room with a small stack of blocks standing on a column" width="680">
</picture>

```swift
import Ollin
import OllinPhone

final class Viewfinder: Sketch {
    let device = PhoneDevice()

    override func setup() {
        device.use(.room)           // the phone follows the room
        device.show(self)           // and its screen shows this sketch
    }

    override func draw() {
        background(.black)
        guard let view = device.latestCamera else { return }
        drawPhonePicture(view)      // the camera's picture, off the cable
        camera(view)                // the camera that took it
        translate(0, 0, -1)
        drawBox(size: 0.2)          // a box that stays put as you walk
    }
}
```

The figure follows one frame around. The camera's picture goes up the cable with where the camera stood. The sketch draws in it, and the finished frame comes back down to the phone. The sketch never leaves the Mac. Save the file under the live window, and the phone shows the edit as soon as the Mac has compiled it.

A tap on the phone is a press on the canvas. `view.ray(through:covering:)` turns the tap into a line of sight into the room, and a surface the phone found says where that line lands. [`PhoneViewfinder`](../examples/3d/phone/phoneviewfinder.md) stands a stack of blocks wherever you tap. The person holding the phone can put the picture away with the arrow in its corner, and bring it back. The picture on the phone has crossed the cable twice, so it trails the camera a little. **Record** sits at the foot of the picture. It records what the camera saw and where it stood, as every recording does, so the piece can be made again from it at the desk, at full quality. [The phone as a viewfinder](../docs/3d/phone.md#the-phone-as-a-viewfinder) has the rest.

### No Mac in the room: the sketch on the phone

A sketch built for the phone reads the phone's own camera. Nothing is on the cable, and no Mac is in the room. It is for a piece that is finished: the viewfinder is where you work on a sketch, and this is the sketch handed over. It is how an AR app on a phone has worked since ARKit arrived in 2017. The app that draws is the app that reads the camera. [Chapter 48](48-handingitover.md#in-your-pocket-the-sketch-on-the-phone) teaches the command that builds it, `ollin phone`.

```swift
let device = PhoneDevice()          // on the phone: the phone's own sensors

override func setup() {
    device.use(.room)               // the sketch chooses the mode
    device.show(self)               // on the phone this sends nothing
}
```

Not one line differs from the viewfinder's. `PhoneDevice()` means the phone, wherever the sketch runs. On the Mac that is the phone on the cable. On the phone it is the phone the sketch is on, and `device.readsOwnSensors` says which. The code that reads each sensor is the capture app's own, built into the library. So a surface, a face, and the camera's place are the same values in all three places: a recording, the cable, and the phone.

Two things change on the phone. Nobody taps a mode there, so `use(_:)` is what starts the camera. And every mode starts its room over. A place the sketch kept from the last mode, or from before the last save, is no longer the same spot.

`ollin phone Examples/3D/Phone/PhoneViewfinder/Sketch.swift` installs the viewfinder example as that app. Its recording goes along, and it plays whenever the phone's sensors have nothing to report. No phone has run this yet. It is proven on the Mac, where the same frames read the same from a recording, the cable, and the phone's own path. [The sketch on the phone itself](../docs/3d/phone.md#the-sketch-on-the-phone-itself) has the rest.

### Keeping what it shows: a picture and a video in Photos

A sketch on the phone keeps what it shows in the phone's photo library: a picture of one frame, or a video with the sketch's own sound. A video is how an effect gets passed around. Snapchat's Lenses made that the habit in 2015, when people filmed themselves with an effect on and sent the clip. Here the person holding the phone shares it from Photos, the way they share anything else. The sketch never posts it anywhere.

It takes no code. A sketch running on a phone shows a small control at the foot of its screen, a camera button and a red one. The camera saves the frame, and the red button starts and stops a video. The control keeps the canvas, so it is never in its own picture. The same things are calls, for a sketch that keeps a frame on a cue of its own:

```swift
saveFrame()                         // the next frame, as a picture in Photos
startRecording()                    // a video, with the sketch's sound
stopRecording { kept in             // where it went: .photos, or a file
    print(kept as Any)
}
```

The first save asks the person to let the app add to Photos, and only to add, so the sketch can never read the library. Refused, the video or the picture is kept in the app's own files, and the control says so in a sentence. A canvas that fills the screen is recorded at the screen's own pixels, and turning the phone ends a take, since every frame of a movie is the same size. `override var showsCaptureControls: Bool { false }` takes the control off a piece that should carry nothing but itself.

No phone has run this yet. In the simulator, a picture and a video land in its photo library, and with Photos refused both are kept in the app's files. [On a phone or a tablet](../docs/output/recording.md#on-a-phone-or-a-tablet) has the rest.

## Where this comes from

Ivan Sutherland built the first display of this kind in 1968. It hung in front of the wearer's eyes and drew wire-frame shapes that kept their place in the room as the head turned. The name came later. Thomas Caudell and David Mizell of Boeing wrote of "augmented reality" in a 1992 paper. It was about a see-through display that showed factory workers where an aircraft's wires go. Ronald Azuma's 1997 survey gave the field its usual definition, in three parts. It combines the real and the virtual, it runs in real time, and its drawing is registered in 3D. The last is this chapter's pin staying on its column. Apple brought it to the phone with ARKit in 2017, and Ollin Capture reads the camera's place and the room's surfaces from it. The picture as paint is projective texture mapping, which Mark Segal and four colleagues introduced in 1992. An image on four points follows Paul Heckbert's 1989 thesis. The mesh that writes depth and no color is the occlusion material every AR toolkit carries. How far sound may part from its picture is from the ITU's recommendation BT.1359 of 1998. Full credits are in the project's [attribution notes](../attribution.md).

## Go deeper

- [A recording of the phone's stream](../docs/3d/phone.md#a-recording): the Record button, playing a recording on the sketch's clock, any frame by its number, [its sound](../docs/3d/phone.md#its-sound), and what is in the folder.
- [The camera's place and lens](../docs/3d/phone.md#the-cameras-place-and-lens): everything a `PhoneCamera` holds, the typed values under the two calls, and [the camera's picture on the cable](../docs/3d/phone.md#the-cameras-picture-on-the-cable).
- [Drawing on a real surface](../docs/3d/surfaces.md): `Plane3`, `withPlane(_:)`, pinned points, the surface under a click, the picture as paint, `occluding { }`, an image on four points, and what none of it does.
- [Drawing on what the phone saw](../docs/3d/phone.md#drawing-on-what-the-phone-saw): the forms of those calls that take a `PhoneCamera` and a `PhonePlane`.
- [The flat surfaces](../docs/3d/phone.md#the-flat-surfaces), [the room's light](../docs/3d/phone.md#the-rooms-light), and [the room mesh](../docs/3d/phone.md#the-room-mesh): each in full.
- [The face](../docs/3d/phone.md#the-face): everything a `PhoneFace` holds, [drawing on a face in its picture](../docs/3d/phone.md#drawing-on-a-face-in-its-picture), [a place on the skin](../docs/3d/phone.md#a-place-on-the-skin), [expressions as events](../docs/3d/phone.md#expressions-as-events), and [the mirror](../docs/3d/phone.md#a-faces-picture-is-a-mirror).
- [The phone as a viewfinder](../docs/3d/phone.md#the-phone-as-a-viewfinder): `show(_:)` beside a camera mode, who holds the screen, and Record over the picture.
- [Recording on a phone or a tablet](../docs/output/recording.md#on-a-phone-or-a-tablet): the control, where a capture goes, what Photos asks and what happens when it says no, and [one frame as a picture](../docs/output/recording.md#saveFrame).
- [Geometry](../docs/drawing/geometry.md#plane3): `Plane3` and `Ray3`, the two values under a surface and a line of sight.
- Worked examples: [`Examples/3D/Phone/PhoneRecordingPins`](../examples/3d/phone/phonerecordingpins.md), [`Examples/3D/Phone/PhoneWallTiles`](../examples/3d/phone/phonewalltiles.md), [`Examples/3D/Phone/PhoneFacePaint`](../examples/3d/phone/phonefacepaint.md), [`Examples/3D/Phone/PhonePoster`](../examples/3d/phone/phoneposter.md), [`Examples/3D/Phone/PhoneViewfinder`](../examples/3d/phone/phoneviewfinder.md), [`Examples/3D/Phone/PhoneRoomPlanes`](../examples/3d/phone/phoneroomplanes.md), and [`Examples/3D/Phone/PhoneRoomMesh`](../examples/3d/phone/phoneroommesh.md).

---

[Contents](index.md#contents) · Previous: [Chapter 39, The iPhone as a sensor](39-thephoneasasensor.md) · Next: [Chapter 41, Listening](41-listening.md)
