WebXRInterface

package
v0.0.0-...-357ca8a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

WebXR is an open standard that allows creating VR and AR applications that run in the web browser.

As such, this interface is only available when running in Web exports.

WebXR supports a wide range of devices, from the very capable (like Valve Index, HTC Vive, Oculus Rift and Quest) down to the much less capable (like Google Cardboard, Oculus Go, GearVR, or plain smartphones).

Since WebXR is based on JavaScript, it makes extensive use of callbacks, which means that WebXRInterface is forced to use signals, where other XR interfaces would instead use functions that return a result immediately. This makes WebXRInterface quite a bit more complicated to initialize than other XR interfaces.

Here's the minimum code required to start an immersive VR session:

package main

import (
	"graphics.gd/classdb/Button"
	"graphics.gd/classdb/Node3D"
	"graphics.gd/classdb/OS"
	"graphics.gd/classdb/Viewport"
	"graphics.gd/classdb/WebXRInterface"
	"graphics.gd/classdb/XRServer"
	"graphics.gd/variant/Object"
)

type NodeWebXR struct {
	Node3D.Extension[NodeWebXR]

	Button Button.Instance

	webxr_interface WebXRInterface.Instance
	vr_supported    bool
}

func (n *NodeWebXR) Ready() {
	n.Button.AsBaseButton().OnPressed(func() {
		if !n.vr_supported {
			OS.Alert("Your browser doesn't support VR")
			return
		}
		// We want an immersive VR session, as opposed to AR ('immersive-ar') or a
		// simple 3DoF viewer ('viewer').
		n.webxr_interface.SetSessionMode("immersive-vr")
		// 'bounded-floor' is room scale, 'local-floor' is a standing or sitting
		// experience (it puts you 1.6m above the ground if you have 3DoF headset),
		// whereas as 'local' puts you down at the XROrigin.
		// This list means it'll first try to request 'bounded-floor', then
		// fallback on 'local-floor' and ultimately 'local', if nothing else is
		// supported.
		n.webxr_interface.SetRequestedReferenceSpaceTypes("bounded-floor, local-floor, local")
		// In order to use 'local-floor' or 'bounded-floor' we must also
		// mark the features as required or optional. By including 'hand-tracking'
		// as an optional feature, it will be enabled if supported.
		n.webxr_interface.SetRequiredFeatures("local-floor")
		n.webxr_interface.SetOptionalFeatures("bounded-floor, hand-tracking")

		// This will return false if we're unable to even request the session,
		// however, it can still fail asynchronously later in the process, so we
		// only know if it's really succeeded or failed when our
		// _webxr_session_started() or _webxr_session_failed() methods are called.
		if !n.webxr_interface.AsXRInterface().Initialize() {
			OS.Alert("Failed to initialize")
			return
		}
	})

	n.webxr_interface = Object.To[WebXRInterface.Instance](XRServer.FindInterface("WebXR"))
	if n.webxr_interface != WebXRInterface.Nil {
		// WebXR uses a lot of asynchronous callbacks, so we connect to various
		// signals in order to receive them.
		n.webxr_interface.OnSessionSupported(func(session_mode string, supported bool) {
			if session_mode == "immersive-vr" {
				n.vr_supported = supported
			}
		})
		n.webxr_interface.OnSessionStarted(func() {
			n.Button.AsCanvasItem().SetVisible(false)
			// This tells Godot to start rendering to the headset.
			Viewport.Get(n.AsNode()).SetUseXr(true)
			// This will be the reference space type you ultimately got, out of the
			// types that you requested above. This is useful if you want the game to
			// work a little differently in 'bounded-floor' versus 'local-floor'.
			print("Reference space type: ", n.webxr_interface.ReferenceSpaceType())
			// This will be the list of features that were successfully enabled
			// (except on browsers that don't support this property).
			print("Enabled features: ", n.webxr_interface.EnabledFeatures())
		})
		n.webxr_interface.OnSessionEnded(func() {
			n.Button.AsCanvasItem().SetVisible(true)
			// If the user exits immersive mode, then we tell Godot to render to the web
			// page again.
			Viewport.Get(n.AsNode()).SetUseXr(false)
		})
		n.webxr_interface.OnSessionFailed(func(message string) {
			OS.Alert("Failed to initialize: " + message)
		})
	}
}

There are a couple ways to handle "controller" input:

- Using XRController3D nodes and their OnXrcontroller3d.ButtonPressed and OnXrcontroller3d.ButtonReleased signals. This is how controllers are typically handled in XR apps in Godot, however, this will only work with advanced VR controllers like the Oculus Touch or Index controllers, for example.

- Using the OnSelect, OnSqueeze and related signals. This method will work for both advanced VR controllers, and non-traditional input sources like a tap on the screen, a spoken voice command or a button press on the device itself.

You can use both methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interactions with more advanced devices.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Advanced

type Advanced = class

Advanced exposes a 1:1 low-level instance of the class, undocumented, for those who know what they are doing.

type Any

type Any interface {
	gd.IsClass
	AsWebXRInterface() Instance
}

type Extension

type Extension[T gdclass.Interface] struct{ gdclass.Extension[T, Instance] }

Extension can be embedded in a new struct to create an extension of this class. T should be the type that is embedding this Extension

func (*Extension[T]) AsObject

func (self *Extension[T]) AsObject() [1]gd.Object

func (*Extension[T]) AsRefCounted

func (self *Extension[T]) AsRefCounted() [1]gd.RefCounted

func (*Extension[T]) AsWebXRInterface

func (self *Extension[T]) AsWebXRInterface() Instance

func (*Extension[T]) AsXRInterface

func (self *Extension[T]) AsXRInterface() XRInterface.Instance

type ID

type ID Object.ID

ID is a typed object ID (reference) to an instance of this class, use it to store references to objects with unknown lifetimes, as an ID will not panic on use if the underlying object has been destroyed.

func (ID) Instance

func (id ID) Instance() (Instance, bool)

type Instance

type Instance [1]gdclass.WebXRInterface

Instance of the class with convieniently typed arguments and results.

var Nil Instance

Nil is a nil/null instance of the class. Equivalent to the zero value.

func New

func New() Instance

func (Instance) AsObject

func (self Instance) AsObject() [1]gd.Object

func (Instance) AsRefCounted

func (self Instance) AsRefCounted() [1]gd.RefCounted

func (Instance) AsWebXRInterface

func (self Instance) AsWebXRInterface() Instance

func (Instance) AsXRInterface

func (self Instance) AsXRInterface() XRInterface.Instance

func (Instance) EnabledFeatures

func (self Instance) EnabledFeatures() string

A comma-separated list of features that were successfully enabled by XRInterface.Initialize when setting up the WebXR session.

This may include features requested by setting RequiredFeatures and OptionalFeatures, and will only be available after OnSessionStarted has been emitted.

Note: This may not be support by all web browsers, in which case it will be an empty string.

func (Instance) GetAvailableDisplayRefreshRates

func (self Instance) GetAvailableDisplayRefreshRates() []float32

Returns display refresh rates supported by the current HMD. Only returned if this feature is supported by the web browser and after the interface has been initialized.

func (Instance) GetDisplayRefreshRate

func (self Instance) GetDisplayRefreshRate() Float.X

Returns the display refresh rate for the current HMD. Not supported on all HMDs and browsers. It may not report an accurate value until after using SetDisplayRefreshRate.

func (Instance) GetInputSourceTargetRayMode

func (self Instance) GetInputSourceTargetRayMode(input_source_id int) TargetRayMode

Returns the target ray mode for the given 'input_source_id'.

This can help interpret the input coming from that input source. See XRInputSource.targetRayMode for more information.

func (Instance) GetInputSourceTracker

func (self Instance) GetInputSourceTracker(input_source_id int) XRControllerTracker.Instance

Gets an XRControllerTracker for the given 'input_source_id'.

In the context of WebXR, an input source can be an advanced VR controller like the Oculus Touch or Index controllers, or even a tap on the screen, a spoken voice command or a button press on the device itself. When a non-traditional input source is used, interpret the position and orientation of the XRPositionalTracker as a ray pointing at the object the user wishes to interact with.

Use this method to get information about the input source that triggered one of these signals:

- OnSelectstart

- OnSelect

- OnSelectend

- OnSqueezestart

- OnSqueeze

- OnSqueezestart

func (Instance) ID

func (self Instance) ID() ID

func (Instance) IsInputSourceActive

func (self Instance) IsInputSourceActive(input_source_id int) bool

Returns true if there is an active input source with the given 'input_source_id'.

func (Instance) IsSessionSupported

func (self Instance) IsSessionSupported(session_mode string)

Checks if the given 'session_mode' is supported by the user's browser.

Possible values come from WebXR's XRSessionMode, including: "immersive-vr", "immersive-ar", and "inline".

This method returns nothing, instead it emits the OnSessionSupported signal with the result.

func (Instance) OnDisplayRefreshRateChanged

func (self Instance) OnDisplayRefreshRateChanged(cb func(), flags ...Signal.Flags)

Emitted after the display's refresh rate has changed.

func (Instance) OnReferenceSpaceReset

func (self Instance) OnReferenceSpaceReset(cb func(), flags ...Signal.Flags)

Emitted to indicate that the reference space has been reset or reconfigured.

When (or whether) this is emitted depends on the user's browser or device, but may include when the user has changed the dimensions of their play space (which you may be able to access via XRInterface.GetPlayArea) or pressed/held a button to recenter their position.

See WebXR's XRReferenceSpace reset event for more information.

func (Instance) OnSelect

func (self Instance) OnSelect(cb func(input_source_id int), flags ...Signal.Flags)

Emitted after one of the input sources has finished its "primary action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnSelectend

func (self Instance) OnSelectend(cb func(input_source_id int), flags ...Signal.Flags)

Emitted when one of the input sources has finished its "primary action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnSelectstart

func (self Instance) OnSelectstart(cb func(input_source_id int), flags ...Signal.Flags)

Emitted when one of the input source has started its "primary action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnSessionEnded

func (self Instance) OnSessionEnded(cb func(), flags ...Signal.Flags)

Emitted when the user ends the WebXR session (which can be done using UI from the browser or device).

At this point, you should do get_viewport().use_xr = false to instruct Godot to resume rendering to the screen.

func (Instance) OnSessionFailed

func (self Instance) OnSessionFailed(cb func(message string), flags ...Signal.Flags)

Emitted by XRInterface.Initialize if the session fails to start.

'message' may optionally contain an error message from WebXR, or an empty string if no message is available.

func (Instance) OnSessionStarted

func (self Instance) OnSessionStarted(cb func(), flags ...Signal.Flags)

Emitted by XRInterface.Initialize if the session is successfully started.

At this point, it's safe to do get_viewport().use_xr = true to instruct Godot to start rendering to the XR device.

func (Instance) OnSessionSupported

func (self Instance) OnSessionSupported(cb func(session_mode string, supported bool), flags ...Signal.Flags)

Emitted by IsSessionSupported to indicate if the given 'session_mode' is supported or not.

func (Instance) OnSqueeze

func (self Instance) OnSqueeze(cb func(input_source_id int), flags ...Signal.Flags)

Emitted after one of the input sources has finished its "primary squeeze action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnSqueezeend

func (self Instance) OnSqueezeend(cb func(input_source_id int), flags ...Signal.Flags)

Emitted when one of the input sources has finished its "primary squeeze action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnSqueezestart

func (self Instance) OnSqueezestart(cb func(input_source_id int), flags ...Signal.Flags)

Emitted when one of the input sources has started its "primary squeeze action".

Use GetInputSourceTracker and GetInputSourceTargetRayMode to get more information about the input source.

func (Instance) OnVisibilityStateChanged

func (self Instance) OnVisibilityStateChanged(cb func(), flags ...Signal.Flags)

Emitted when VisibilityState has changed.

func (Instance) OptionalFeatures

func (self Instance) OptionalFeatures() string

A comma-seperated list of optional features used by XRInterface.Initialize when setting up the WebXR session.

If a user's browser or device doesn't support one of the given features, initialization will continue, but you won't be able to use the requested feature.

This doesn't have any effect on the interface when already initialized.

See the MDN documentation on WebXR's session features for a list of possible values.

func (Instance) ReferenceSpaceType

func (self Instance) ReferenceSpaceType() string

The reference space type (from the list of requested types set in the RequestedReferenceSpaceTypes property), that was ultimately used by XRInterface.Initialize when setting up the WebXR session.

Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures.

func (Instance) RequestedReferenceSpaceTypes

func (self Instance) RequestedReferenceSpaceTypes() string

A comma-seperated list of reference space types used by XRInterface.Initialize when setting up the WebXR session.

The reference space types are requested in order, and the first one supported by the user's device or browser will be used. The ReferenceSpaceType property contains the reference space type that was ultimately selected.

This doesn't have any effect on the interface when already initialized.

Possible values come from WebXR's XRReferenceSpaceType. If you want to use a particular reference space type, it must be listed in either RequiredFeatures or OptionalFeatures.

func (Instance) RequiredFeatures

func (self Instance) RequiredFeatures() string

A comma-seperated list of required features used by XRInterface.Initialize when setting up the WebXR session.

If a user's browser or device doesn't support one of the given features, initialization will fail and OnSessionFailed will be emitted.

This doesn't have any effect on the interface when already initialized.

See the MDN documentation on WebXR's session features for a list of possible values.

func (Instance) SessionMode

func (self Instance) SessionMode() string

The session mode used by XRInterface.Initialize when setting up the WebXR session.

This doesn't have any effect on the interface when already initialized.

Possible values come from WebXR's XRSessionMode, including: "immersive-vr", "immersive-ar", and "inline".

func (Instance) SetDisplayRefreshRate

func (self Instance) SetDisplayRefreshRate(refresh_rate Float.X)

Sets the display refresh rate for the current HMD. Not supported on all HMDs and browsers. It won't take effect right away until after OnDisplayRefreshRateChanged is emitted.

func (*Instance) SetObject

func (self *Instance) SetObject(obj [1]gd.Object) bool

func (Instance) SetOptionalFeatures

func (self Instance) SetOptionalFeatures(value string)

SetOptionalFeatures sets the property returned by [GetOptionalFeatures].

func (Instance) SetRequestedReferenceSpaceTypes

func (self Instance) SetRequestedReferenceSpaceTypes(value string)

SetRequestedReferenceSpaceTypes sets the property returned by [GetRequestedReferenceSpaceTypes].

func (Instance) SetRequiredFeatures

func (self Instance) SetRequiredFeatures(value string)

SetRequiredFeatures sets the property returned by [GetRequiredFeatures].

func (Instance) SetSessionMode

func (self Instance) SetSessionMode(value string)

SetSessionMode sets the property returned by [GetSessionMode].

func (Instance) Virtual

func (self Instance) Virtual(name string) reflect.Value

func (Instance) VisibilityState

func (self Instance) VisibilityState() string

Indicates if the WebXR session's imagery is visible to the user.

Possible values come from WebXR's XRVisibilityState, including "hidden", "visible", and "visible-blurred".

type TargetRayMode

type TargetRayMode int //gd:WebXRInterface.TargetRayMode
const (
	// We don't know the target ray mode.
	TargetRayModeUnknown TargetRayMode = 0
	// Target ray originates at the viewer's eyes and points in the direction they are looking.
	TargetRayModeGaze TargetRayMode = 1
	// Target ray from a handheld pointer, most likely a VR touch controller.
	TargetRayModeTrackedPointer TargetRayMode = 2
	// Target ray from touch screen, mouse or other tactile input device.
	TargetRayModeScreen TargetRayMode = 3
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL