Core Concepts

VR (WebXR)

Play a MavonEngine game in a VR headset through WebXR — camera rig, controllers, thumbstick locomotion, labels and panels in VR, and mirroring to the browser window.

A Game can be played in a VR headset through WebXR: a Quest's or Pico's browser, or desktop Chrome with a PC headset (SteamVR, Quest Link). The multiplayer template turns it on wherever the browser can do it.

Enabling VR

import Game from '@mavonengine/core/Game'
import XR from '@mavonengine/core/XR'

const game = Game.instance()

if (await XR.isSupported())
  game.enableXR() // adds an "Enter VR" button

enableXR(options) returns the XR object, also at game.xr. Calling it again returns the same one.

OptionDefault
referenceSpace'local-floor'Where the headset's origin sits: on the floor under the player, or 'local' at their head height when the session started
buttontrueShow three.js's Enter VR button. Set it to false and call xr.enter() from your own UI instead
sessionInitExtra session features, e.g. { optionalFeatures: ['hand-tracking'] }
input{}How the controllers show, or false to leave controller input out
mirrorfalseKeep drawing the game in the browser window while a headset plays. Without it the window shows its last frame, blurred. See Mirroring
XR
XR.isSupported()Whether this browser and device can run immersive VR
enter() / exit()Start or end a session. Browsers only start one from a user gesture, like a click
presentingWhether a session is rendering to the headset
sessionThe running XRSession, if any
input / pointerThe controllers (also game.input.xr) and what they point at
enableLocomotion(options)Thumbstick movement
addPanel(panel) / removePanel(panel)Panels shown in VR

The game triggers xrSessionStart (with the XRSession) and xrSessionEnd.

WebXR only runs on https or localhost. To play the dev server on a Quest over USB, forward the port so the headset opens it as localhost:

adb reverse tcp:8050 tcp:8050
# then open http://localhost:8050 in the Quest's browser

Without a headset, the Immersive Web Emulator extension for Chrome emulates one.

Rendering in VR

While a session runs:

  • the headset sets the frame rate, so renderer.maxFps is ignored;
  • the scene is rendered straight to the headset's two eyes, skipping the render pipeline and its effects, which render a single view. The renderer's toneMapping and outputColorSpace stand in for the pipeline's output;
  • resizes are skipped, since the session owns the framebuffer, and caught up when it ends;
  • a reversed depth buffer (reversedDepthBuffer: true in the render parameters) works. The headset is told the depth is reversed, so its reprojection (correcting the picture for head movement since the frame was rendered) doesn't make distant geometry jitter as the head moves;
  • off-screen renders into a render target, such as an environment map or a reflection, use the camera they were given;
  • the session only gets a WebXR Layers projection layer when the browser granted the layers feature, otherwise the WebGL layer. Chrome on Windows with SteamVR has the API without granting it, and showed no frames before.

Frames come through the renderer's animation loop, which a session drives, and the beforeRender event runs on every one of them.

The camera rig

In VR the headset moves camera.instance relative to its parent, so the camera now sits in a rig: camera.rig, a Group in the scene. Move the player's view by moving the rig, or with place(), which works the same on desktop and in VR:

// A third person camera behind the player, every rendered frame
game.on('beforeRender', () => {
  game.camera.place(behindPlayer, player.position)
})
Camera
rigThe camera's parent. On desktop it stays at the origin unless moved, so setting camera.instance.position directly keeps working there
place(position, target, { turn, pinHead })Put the view at position looking at target. On desktop it moves and turns the rig. In VR it moves the rig so the player's head lands at position and only turns it around the vertical axis: the headset keeps control of where the player looks. turn: false only moves it. In VR the player's own head movement (leaning, standing up) moves the view from position; pinHead: true keeps the view at position and lets the head only turn it, for a first person view on a body
turn(angle)Turn the view around the vertical axis through the player's head, e.g. a snap turn. Positive turns left
recenter()Take the headset's current offset as the one place() lines up, e.g. after the player sat down. Done on the first frame of each session
worldPositionWhere the camera is in the world, refreshed every rendered frame

camera.instance.position is relative to the rig, so it is no longer the camera's world position once the rig moves. Use camera.worldPosition for distance checks and shader uniforms: it is the same Vector3 throughout, so it can be handed to a uniform once. The grass and water prefabs, labels, rain and smoke use it.

When a session ends, the rig is reset to the origin, so desktop controls that move the camera itself (orbit, fly) start from where they were, and the camera gets its own field of view back.

Turning the view continuously makes many players queasy. Pass turn: false and turn in steps with camera.turn() instead, as the template does.

Controllers

game.input.xr reads both controllers by hand, with the same API as gamepads. See VR controllers.

Locomotion

enableLocomotion() walks the player with one thumbstick, relative to where they look, and turns with the other, by moving the camera rig every rendered frame:

game.xr!.enableLocomotion({ speed: 2, turn: 'snap' })
OptionDefault
speed2Walking speed at full stick, in meters per second
moveHand / turnHand'left' / 'right'The stick that moves and the one that turns
turn'snap''snap' turns in steps on a flick, 'smooth' continuously, false leaves turning to the player's body
snapAngle30°How far a snap turn turns, in radians
turnSpeed90°How fast a smooth turn turns at full stick, in radians per second
flyfalseMove where the head looks, up and down too, instead of staying level

It moves freely and goes through walls, which suits free roaming. A game with physics or its own character moves that instead and places the view with camera.place(). getMoveDirection(stick) gives a stick's direction in the world, relative to where the player looks:

import XRLocomotion from '@mavonengine/core/XRLocomotion'

// Not enabled: only used for the stick's direction
const locomotion = new XRLocomotion(game.camera, game.input.xr!)

const direction = locomotion.getMoveDirection(game.input.xr!.left.stick)
player.move(direction) // e.g. send it to the server

The template's VRControls.ts works this way: the left stick (or WASD) walks the character through the same CL_MOVE command as the keyboard, so the server needs nothing for VR, and the right stick (or Q / E) snap turns the chase view around it.

Labels and panels in VR

A headset shows none of the page's HTML, so what a game shows in VR has to be in the scene.

Labels

ObjectLabel (and UILabel) keep working: while a headset plays, the label is drawn in the scene as a TextLabel instead of its HTML element. By default it reads the element's text; override xrText() to choose what shows, lines split on \n, or return undefined to show nothing in VR. Override xrLabelOptions() to style it.

class PlayerLabel extends ObjectLabel {
  protected xrText() {
    return this.chatBubble ? `${this.chatBubble}\n${this.name}` : this.name
  }
}

TextLabel can be used on its own: text on a sprite that always faces the viewer, unlit and out of tone mapping and fog, drawn over the scene unless depthTest is set.

import TextLabel from '@mavonengine/core/ui/TextLabel'

const label = new TextLabel('Checkpoint', { angularSize: 2 })
label.position.set(0, 3, 0)
game.scene.add(label)
// With angularSize, keep its size in view every rendered frame
game.on('beforeRender', () => label.update(game.camera.instance))
OptionDefault
font'600 40px system-ui, sans-serif'CSS font, at the size the text is drawn on the canvas
color / backgroundwhite / translucent blackbackground: '' for none
padding / radiusa third of the font's height / half the paddingIn canvas pixels
height0.25Its height in the world, in meters
angularSizeKeep it the same size in view at any distance, as an angle in degrees (2 reads like 14 px text on a monitor)
depthTestfalseHidden by the scene in front of it

setText() and setIcon() redraw it only when they change.

Panels

XRPanel is a flat panel with a canvas on it, for a menu, a scoreboard or a message. Draw on its ctx, call redraw(), and add it with xr.addPanel(). It shows while in VR and open, sits in the camera rig so it moves with the player, and the controllers point at it with a line and a dot, the trigger as the button:

import XRPanel from '@mavonengine/core/ui/XRPanel'

const menu = game.xr!.addPanel(new XRPanel({ width: 1, height: 0.6 }))
menu.ctx.fillStyle = '#111'
menu.ctx.fillRect(0, 0, menu.canvas.width, menu.canvas.height)
menu.ctx.fillStyle = '#fff'
menu.ctx.font = '64px system-ui'
menu.ctx.fillText('Resume', 80, 300)
menu.redraw()

menu.on('click', ({ hand, x, y }) => {
  // x and y in canvas pixels from the top left
  if (y > 220 && y < 340)
    menu.close()
})

menu.open()
OptionDefault
width / height1 / 0.6Its size in meters
pixelsPerMeter1000How sharp the canvas is
follow'head''head' opens it in front of the player and glides it back once they look well away; 'none' leaves mesh where the game puts it, in the rig's space
distance / drop1.5 / 0.15How far in front of the head it floats, and how far below eye level
followAngle35How far, in degrees, the view turns away before it follows

Panels get pointermove, pointerleave, pointerdown, pointerup and click. xr.pointer.pointingAt(hand) says which panel a controller points at, so the game can leave the trigger to the menu instead of shooting.

Mirroring to the browser window

Without a mirror, the browser window shows its last frame, blurred, with Playing in VR over it while a headset plays. The game's own UI stays on top. With enableXR({ mirror: true }), or xr.mirror = true at any time, the scene is drawn once more after every headset frame instead, onto the page from the player's head, with the window's shape. mirror: { fov: 70 } sets its field of view. It's for someone watching or a stream, and reuses the headset frame's shadow maps.

It costs the headset frames: three.js rebuilds every object's render pipeline whenever the camera changes between the headset's eyes and the mirror's. A Valve Index in Chrome on Windows ran at 45 Hz with it and 90 Hz without. So the template leaves it off:

XR.isSupported().then((supported) => {
  if (supported)
    game.enableXR()
})