Skip to main content

Depth Sensing

Depth sensing measures how far the real world is from the device at each pixel of the view, many times a second, as a depth map. It covers everything the device's cameras or depth sensors see, including people and things that move, so it can hide virtual objects behind a real hand, let content rest at the distance of whatever the user looks at, or make effects react to real surfaces.

A kitchen seen in AR on the left, and the depth map of the same view on the right, where nearer surfaces are darker

AR Camera Depth

Requesting Depth Sensing​

Ask for depth sensing when you start an AR session, with the usage and the data format that you prefer:

camera.camera.startXr(XRTYPE_AR, XRSPACE_LOCALFLOOR, {
depthSensing: {
usagePreference: XRDEPTHSENSINGUSAGE_CPU,
dataFormatPreference: XRDEPTHSENSINGFORMAT_F32
}
});

app.xr.on('start', () => {
if (app.xr.views.availableDepth) {
console.log(`Depth sensing: ${app.xr.views.depthUsage}, ${app.xr.views.depthFormat}`);
}
});

The usage says where the depth map is: in memory that JavaScript reads, XRDEPTHSENSINGUSAGE_CPU, or in a texture on the GPU, XRDEPTHSENSINGUSAGE_GPU. The data format is how each value is stored: as a 32-bit float, XRDEPTHSENSINGFORMAT_F32, as two bytes, XRDEPTHSENSINGFORMAT_L8A8, or as a 16-bit integer, XRDEPTHSENSINGFORMAT_R16U. The engine asks for your preferences first, and then for the others, so the session gets whichever the device offers. Both options are optional, and depthSensing: {} takes any.

app.xr.views.supportedDepth is true when the browser implements depth sensing, and availableDepth is true when a session that has it starts. depthUsage and depthFormat say what the session got, and depthGpuOptimized is true for the GPU usage. What each device offers, as the browsers implement it:

DeviceUsageFormatsDepth maps
Android phonesCPUTwo bytes or 16-bit integers, in millimetersOne
Android XR headsetsCPU32-bit floats, in meters, or the 16-bit formats, in millimetersOne for each eye
Meta Quest 3 and 3SGPUNot documented by Meta. The values aren't proportional to distanceOne for each eye, in the layers of one texture

So code that should run everywhere has to handle both usages. GPU depth sensing needs a WebGL device: see Choosing a Graphics Device.

Measuring a Distance​

With the CPU usage, a view's getDepth(u, v) returns the distance in meters to the real world at a point of the view, where u and v run from 0 to 1, from the view's top-left corner. It returns null while the depth isn't known, and always with the GPU usage. Views are added after the session starts, so read them in update:

app.on('update', () => {
// A phone has one view; a headset has one for each eye
const view = app.xr.views.list[0];
const distance = view?.getDepth(0.5, 0.5) ?? null;
if (distance !== null) {
console.log(`The real world is ${distance.toFixed(2)} m away at the center of the view`);
}
});

The distance is measured along the view's direction, from the plane of the camera. To find the point it describes at the center of the view, go that far ahead of the camera, which is where the AR Depth Sensing Placer example puts its object:

const point = camera.getPosition().clone().add(camera.forward.clone().mulScalar(distance));

The Depth Texture​

With either usage, each view's textureDepth is a Texture that the engine updates with the depth map every frame, for shaders to read. With one view, it's a 2D texture. With one view for each eye, it's a texture array, with a layer for each eye. Its pixel format is app.xr.views.depthPixelFormat:

Data formatPixel formatEach value
XRDEPTHSENSINGFORMAT_F32PIXELFORMAT_R32FA float, in the red channel
XRDEPTHSENSINGFORMAT_L8A8PIXELFORMAT_LA8A 16-bit integer split across two bytes, the luminance and the alpha
XRDEPTHSENSINGFORMAT_R16UPIXELFORMAT_DEPTHA 16-bit integer
note

In engine 2.24, the depth texture stays empty in a CPU session with a view for each eye, as on an Android XR headset. Use getDepth() there.

Multiply a value by the view's depthValueToMeters to get meters: 1 for floats in meters, 0.001 for integers in millimeters. A depth map doesn't always line up with the view, so transform the view's UV coordinates with the view's depthUvMatrix before you read the texture. The matrix can change when the depth map's size does, which the view reports with a depth:resize event, but that also happens before the view's add event, so set the matrix every frame.

This shader draws the depth as shades of gray, on a plane that covers the view. It reads both two-byte and float values, from a 2D texture or from a texture array:

const vertexGLSL = /* glsl */ `
attribute vec3 aPosition;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
void main(void) {
gl_Position = matrix_viewProjection * matrix_model * vec4(aPosition, 1.0);
}
`;

const fragmentGLSL = /* glsl */ `
uniform vec4 screen_size;
uniform mat4 matrix_depth_uv;
uniform float depth_raw_to_meters;

#ifdef XRDEPTH_ARRAY
uniform int view_index;
uniform highp sampler2DArray depthMap;
#else
uniform sampler2D depthMap;
#endif

void main(void) {
vec2 uvScreen = gl_FragCoord.xy * screen_size.zw;

#ifdef XRDEPTH_ARRAY
// Both eyes share the render target, side by side
uvScreen = uvScreen * vec2(2.0, 1.0) - vec2(view_index, 0.0);
vec3 uv = vec3((matrix_depth_uv * vec4(uvScreen, 0.0, 1.0)).xy, view_index);
#else
vec2 uv = (matrix_depth_uv * vec4(uvScreen.x, 1.0 - uvScreen.y, 0.0, 1.0)).xy;
#endif

#ifdef XRDEPTH_FLOAT
float depth = texture2D(depthMap, uv).r;
#else
vec2 packed = texture2D(depthMap, uv).ra;
float depth = dot(packed, vec2(255.0, 256.0 * 255.0));
#endif

// Black at the camera, white at 4 meters and beyond
depth = min(depth * depth_raw_to_meters / 4.0, 1.0);
gl_FragColor = vec4(depth, depth, depth, 1.0);
}
`;

const material = new ShaderMaterial();

const plane = new Entity('depth view');
plane.addComponent('render', { type: 'plane', material });
plane.setLocalPosition(0, 0, -1);
plane.setLocalEulerAngles(90, 0, 0);
plane.setLocalScale(4, 1, 4);
plane.enabled = false;
camera.addChild(plane);

app.on('update', () => {
const view = app.xr.views.list[0];
if (!app.xr.views.availableDepth || !view?.textureDepth) {
plane.enabled = false;
return;
}

if (!material.shaderDesc) {
// Compile the shader for this session's texture type and data format
material.setDefine('XRDEPTH_ARRAY', app.xr.views.list.length > 1);
material.setDefine('XRDEPTH_FLOAT', app.xr.views.depthPixelFormat === PIXELFORMAT_R32F);
material.shaderDesc = {
uniqueName: 'DepthView',
vertexGLSL,
fragmentGLSL,
attributes: { aPosition: SEMANTIC_POSITION }
};
material.update();
}

material.setParameter('depthMap', view.textureDepth);
material.setParameter('matrix_depth_uv', view.depthUvMatrix.data);
material.setParameter('depth_raw_to_meters', view.depthValueToMeters);
plane.enabled = true;
});

screen_size and view_index are built-in uniforms that the engine sets for each view. The shader handles two-byte and float values, and a device with 16-bit integers needs a branch of its own. GPU depth values aren't always proportional to distance: a Meta Quest stores them in a non-linear form, as a depth buffer does, so this shader shows its depth map with the wrong shades.

To hide virtual objects behind real ones, compare the real depth with the depth of each fragment of your objects in their shaders, and discard the fragments that are farther away. The engine doesn't do this for you. For a simpler, coarser way, see Hiding Objects Behind Real Ones.

See Also​