# Mesh Detection

Mesh detection gives you the shape of the room and the things in it as triangle meshes. Where [planes](https://developer.playcanvas.com/user-manual/xr/ar/plane-detection.md) are flat outlines, meshes follow the furniture, the walls and everything else that the device has scanned, so virtual objects can bounce off a real sofa or disappear behind a real table.

[Video](https://developer.playcanvas.com/video/xr-mesh-detection.mp4)

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

## Requesting Mesh Detection

Ask for mesh detection when you start an AR session:

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

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

`app.xr.meshDetection.supported` is `true` when the browser implements mesh detection. `available` becomes `true`, and `app.xr.meshDetection` fires `available`, when a session that has it starts. Few devices offer it: see [Platforms](https://developer.playcanvas.com/user-manual/xr/platforms.md#ar-features). A Meta Quest 3 or 3S reports the meshes of the room that the user set up, and `app.xr.initiateRoomCapture()` asks it to start its room setup, as described in [Plane Detection](https://developer.playcanvas.com/user-manual/xr/ar/plane-detection.md#requesting-plane-detection).

## Meshes

`app.xr.meshDetection.meshes` lists the meshes that the device reports. `app.xr.meshDetection` fires `add` for each new mesh and `remove` for each mesh that goes, and each mesh fires `remove` itself. Each is an [`XrMesh`](https://api.playcanvas.com/engine/classes/XrMesh.html):

| Property or method | Description |
| --- | --- |
| `getPosition()`, `getRotation()` | The mesh's pose, in [tracking space](https://developer.playcanvas.com/user-manual/xr/sessions.md#tracking-space) |
| `vertices` | A `Float32Array` of the positions of its vertices, three numbers for each, in the mesh's local space |
| `indices` | A `Uint32Array` of its triangles, three indices for each |
| `label` | What the mesh is, such as `'table'`, `'couch'` or `'global mesh'`, or an empty string |

A Meta Quest reports a mesh of the whole room, labeled `'global mesh'`, and a mesh for each piece of furniture that the user marked during the room setup. A mesh fires `change` when its vertices, indices or label change, and its pose can change in any frame without an event. When the session ends, every mesh is removed.

## Drawing Meshes

Give each mesh an entity that renders it. Its 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 every frame:

```javascript
app.xr.meshDetection.on('add', (xrMesh) => {
    const mesh = new Mesh(app.graphicsDevice);
    mesh.setPositions(xrMesh.vertices);
    mesh.setNormals(calculateNormals(xrMesh.vertices, xrMesh.indices));
    mesh.setIndices(xrMesh.indices);
    mesh.update();

    const material = new StandardMaterial();
    material.diffuse = new Color(0.3, 0.7, 1);
    material.opacity = 0.5;
    material.blendType = BLEND_NORMAL;
    material.update();

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

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

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

To follow changes to a mesh's shape, create the render mesh with dynamic buffers, `mesh.clear(true, true)`, and set its positions, normals and indices again in a `change` handler.

## Hiding Objects Behind Real Ones

A virtual object behind a real table should be hidden by it, or it looks as if it floats in front. To hide it, draw the room's meshes with a material that writes to the depth buffer but not to the color buffer. The meshes are then invisible, so the real world shows through them, but they still hide what is behind them:

```javascript
// Writes depth but no color, so that the real world shows through
const occluderMaterial = new StandardMaterial();
occluderMaterial.redWrite = false;
occluderMaterial.greenWrite = false;
occluderMaterial.blueWrite = false;
occluderMaterial.alphaWrite = false;
occluderMaterial.update();

app.xr.meshDetection.on('add', (xrMesh) => {
    const mesh = new Mesh(app.graphicsDevice);
    mesh.setPositions(xrMesh.vertices);
    // The material is lit, so it needs normals, although it draws no color
    mesh.setNormals(calculateNormals(xrMesh.vertices, xrMesh.indices));
    mesh.setIndices(xrMesh.indices);
    mesh.update();

    const meshInstance = new MeshInstance(mesh, occluderMaterial);
    // Draw before other opaque objects, so that the depth is there when they draw
    meshInstance.drawBucket = 255;

    const occluder = new Entity('occluder');
    occluder.addComponent('render', { meshInstances: [meshInstance] });
    rig.addChild(occluder);

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

    xrMesh.once('remove', () => {
        follow.off();
        occluder.destroy();
        mesh.destroy();
    });
});
```

The occluders must draw before the objects they hide, or those objects are already drawn by the time the occluders write their depth. Opaque mesh instances in the World layer draw in order of their `drawBucket`, from 255 down to 0, and the default is 127. Transparent objects draw after opaque ones, so they're hidden too.

Room meshes are coarse, so the edges of what they hide only roughly follow the real objects, and anything the room setup missed, such as a person, hides nothing. For occlusion that follows the real world pixel by pixel, use [depth sensing](https://developer.playcanvas.com/user-manual/xr/ar/depth-sensing.md) where the device has it.

## Physics

With a static rigid body and a mesh collision shape for each mesh, virtual objects collide with the real room: a ball bounces off the floor and rolls under the table. Build a model of the mesh for the collision shape:

```javascript
app.xr.meshDetection.on('add', (xrMesh) => {
    const mesh = new Mesh(app.graphicsDevice);
    mesh.setPositions(xrMesh.vertices);
    mesh.setIndices(xrMesh.indices);
    mesh.update();

    const model = new Model();
    model.graph = new GraphNode();
    model.meshInstances = [new MeshInstance(mesh, new StandardMaterial(), model.graph)];

    const collider = new Entity('room collider');
    rig.addChild(collider);
    collider.setLocalPosition(xrMesh.getPosition());
    collider.setLocalRotation(xrMesh.getRotation());
    collider.addComponent('collision', { type: 'mesh', model });
    collider.addComponent('rigidbody', { type: 'static' });

    xrMesh.once('remove', () => {
        collider.destroy();
        mesh.destroy();
    });
});
```

The room doesn't move, so the collider takes the mesh's pose once, when it's added. A static rigid body stays where it was created, even if its entity moves later, so this suits an AR session in which the rig stays where it is, as it usually does. Building a collision shape from a large mesh, such as the global mesh, takes a moment, so build it once rather than on every change. See [Collision Shapes](https://developer.playcanvas.com/user-manual/physics/collision-shapes.md#mesh-colliders) and [Physics](https://developer.playcanvas.com/user-manual/physics.md).

## See Also

- [Plane Detection](https://developer.playcanvas.com/user-manual/xr/ar/plane-detection.md) - Flat surfaces, with their labels
- [Depth Sensing](https://developer.playcanvas.com/user-manual/xr/ar/depth-sensing.md) - The distance to the real world at each pixel
- [XrMeshDetection](https://api.playcanvas.com/engine/classes/XrMeshDetection.html) and [XrMesh](https://api.playcanvas.com/engine/classes/XrMesh.html) - API reference
