# Plane Detection

Plane detection gives you the flat surfaces that the device has found in the room: the floor, the walls and ceiling, tables, doors and windows. Each plane has an outline, an orientation and, on most devices, a label that says what it is. Use them to place content on a surface of a kind, such as a table, or to show the user what the device has found.

[Image: A kitchen seen in AR, with the planes that the device has found drawn over it and labeled: the floor in blue, the walls in orange, the counters, the island and the dining table in green as tables, and the ceiling and the windows in gray]

[Live example: AR Plane Detection](https://playcanvas.com/examples/#/xr/ar-plane-detection) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/ar-plane-detection/example.mjs))

## Requesting Plane Detection

Ask for plane detection when you start an AR session:

```javascript
camera.camera.startXr(XRTYPE_AR, XRSPACE_LOCALFLOOR, {
    planeDetection: true
});

app.xr.on('start', () => {
    if (!app.xr.planeDetection.available) {
        console.log('This session has no plane detection');
    }
});
```

`app.xr.planeDetection.supported` is `true` when the browser implements plane detection. `available` becomes `true`, and `app.xr.planeDetection` fires `available`, when a session that has it starts. Check it in a `start` handler of `app.xr`, rather than in the callback of `startXr()`, which is called just before the features are set up.

Where the planes come from depends on the device. A Meta Quest reports the room that the user set up in the headset's space setup, so it has the planes as soon as the session starts. A phone finds planes in its camera image while the user moves it around, so they appear over the first few seconds. If the user hasn't set up the room, `app.xr.initiateRoomCapture()` asks the device to start its room setup, on devices that have one:

```javascript
app.xr.initiateRoomCapture((err) => {
    if (err) {
        console.log(`Room setup is unavailable: ${err.message}`);
    }
});
```

## Planes

`app.xr.planeDetection.planes` lists the planes that the device reports. `app.xr.planeDetection` fires `add` for each new plane and `remove` for each plane that goes, and each plane fires `remove` itself:

```javascript
app.xr.planeDetection.on('add', (plane) => {
    console.log(`Found a ${plane.orientation ?? 'sloping'} plane: ${plane.label || 'unlabeled'}`);

    plane.once('remove', () => {
        console.log(`Lost a plane: ${plane.label || 'unlabeled'}`);
    });
});
```

Each plane is an [`XrPlane`](https://api.playcanvas.com/engine/classes/XrPlane.html):

| Property or method | Description |
| --- | --- |
| `getPosition()`, `getRotation()` | The plane's pose, in [tracking space](https://developer.playcanvas.com/user-manual/xr/sessions.md#tracking-space). Its local Y axis is the plane's normal |
| `points` | Its outline: the corners of a polygon, in order, in the plane's local space. Each point has `x`, `y` and `z`, and `y` is always 0 |
| `orientation` | `'horizontal'`, `'vertical'`, or `null` for a plane that slopes or that the device can't classify |
| `label` | What the plane is, such as `'floor'`, `'wall'`, `'ceiling'`, `'table'`, `'door'` or `'window'`, or an empty string |
| `id` | A number that identifies the plane for as long as the session runs |

The labels come from the [WebXR semantic labels](https://github.com/immersive-web/semantic-labels) registry, but a device can report others, so treat a label you don't know like an empty one. When the session ends, every plane is removed.

## Drawing Planes

To show the user the surfaces, give each plane an entity with a mesh of its outline. The plane's pose is in tracking space, so make the entity a child of the [rig](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig) and set its local position and rotation. The pose can change in any frame without an event, so set it every frame:

```javascript
// A color for each label, and gray for the others
const colors = {
    floor: new Color(0.2, 0.5, 1),
    wall: new Color(1, 0.55, 0.15),
    table: new Color(0.2, 0.85, 0.4)
};

app.xr.planeDetection.on('add', (plane) => {
    const material = new StandardMaterial();
    material.useLighting = false;
    material.emissive = colors[plane.label] ?? new Color(0.7, 0.7, 0.7);
    material.opacity = 0.4;
    material.blendType = BLEND_NORMAL;
    material.cull = CULLFACE_NONE;
    material.update();

    // Fill the outline with a fan of triangles from its first point
    const mesh = new Mesh(app.graphicsDevice);
    mesh.clear(true, true);
    const build = () => {
        const positions = [];
        const indices = [];
        for (const point of plane.points) {
            positions.push(point.x, point.y, point.z);
        }
        for (let i = 1; i < plane.points.length - 1; i++) {
            indices.push(0, i, i + 1);
        }
        mesh.setPositions(positions);
        mesh.setIndices(indices);
        mesh.update();
    };
    build();
    plane.on('change', build);

    const entity = new Entity(plane.label || 'plane');
    entity.addComponent('render', {
        meshInstances: [new MeshInstance(mesh, material)]
    });
    rig.addChild(entity);

    const follow = app.on('update', () => {
        entity.setLocalPosition(plane.getPosition());
        entity.setLocalRotation(plane.getRotation());
    });

    plane.once('remove', () => {
        follow.off();
        entity.destroy();
        mesh.destroy();
        material.destroy();
    });
});
```

A fan of triangles from the first point fills a convex outline. The material draws both sides of each triangle, as the order of the points, and with it the side that each triangle faces, can differ between devices.

## Placing Content on a Surface

Labels let you put content where it belongs: a vase on a table, a painting on a wall. This finds the first table and puts an object in the middle of it:

```javascript
const table = app.xr.planeDetection.planes.find((plane) => plane.label === 'table');

if (table) {
    // The middle of the table's outline, in the plane's local space
    const min = new Vec3(Infinity, 0, Infinity);
    const max = new Vec3(-Infinity, 0, -Infinity);
    for (const point of table.points) {
        min.set(Math.min(min.x, point.x), 0, Math.min(min.z, point.z));
        max.set(Math.max(max.x, point.x), 0, Math.max(max.z, point.z));
    }
    const middle = new Vec3().add2(min, max).mulScalar(0.5);

    // From the plane's local space to tracking space
    const transform = new Mat4().setTRS(table.getPosition(), table.getRotation(), Vec3.ONE);
    transform.transformPoint(middle, middle);

    // vase is a child of the rig, so its local position is in tracking space
    vase.setLocalPosition(middle);
}
```

The plane's position is its center, as the device defines it, which isn't always the middle of its outline. The code sets only the vase's position, so the vase stays upright. To lay content flat against a plane that isn't horizontal, such as a painting on a wall, also set its rotation from the plane's, whose local Y axis is the plane's normal.

## Changes

The device refines its planes as it learns more about the room. A plane fires `change` when its outline, orientation or label changes, and its pose can change in any frame. A device can also merge planes, which removes some and adds others, so key what you draw or place to the plane objects, and clean up on `remove`, as the drawing code above does.

Planes are flat, and only cover the surfaces the device has classified. For the shape of everything in the room, such as furniture, see [Mesh Detection](https://developer.playcanvas.com/user-manual/xr/ar/mesh-detection.md).

## See Also

- [Mesh Detection](https://developer.playcanvas.com/user-manual/xr/ar/mesh-detection.md) - The shape of the room and its furniture
- [Hit Testing](https://developer.playcanvas.com/user-manual/xr/ar/hit-testing.md) - Finding the surface the user points at
- [WebXR: Plane Detection](https://developer.playcanvas.com/tutorials/webxr-plane-detection/) - A tutorial that draws detected planes in the Editor
- [XrPlaneDetection](https://api.playcanvas.com/engine/classes/XrPlaneDetection.html) and [XrPlane](https://api.playcanvas.com/engine/classes/XrPlane.html) - API reference
