xr.utils

High-level utilities and abstractions for OpenXR integration.

The xr.utils module provides ergonomic helpers and glue code that complement the low-level OpenXR API exposed in xr. While xr aims to mirror the native OpenXR specification as closely as possible, xr.utils offers higher-level constructs that simplify common workflows such as matrix manipulation, swapchain management, and pose utilities.

Warning

The API surface of xr.utils is provisional and may evolve more rapidly than the stable xr namespace. Use with awareness of potential changes.

Contents

High-level utilities and abstractions for OpenXR integration.

The xr.utils module provides ergonomic helpers, glue code, and convenience constructs that complement the low-level OpenXR API exposed in xr. While xr aims to mirror the native OpenXR specification as closely as possible, xr.utils offers higher-level patterns that simplify common workflows, such as view matrix construction, swapchain management, and pose utilities.

This module is intended for rapid iteration and may evolve more quickly than the stable xr namespace. Developers should treat its API as provisional and subject to refinement as best practices emerge.

Contents may include: - Matrix and pose utilities for rendering and simulation - Swapchain wrappers for per-view resource management - Threading or lifecycle helpers for session orchestration - Experimental constructs for bridging OpenXR with graphics APIs

seealso:

xr

class xr.utils.GraphicsAPI(value)

Bases: Enum

An enumeration.

D3D = (3,)
OPENGL = (1,)
OPENGL_ES = (2,)
VULKAN = (0,)
class xr.utils.GraphicsContextProvider

Bases: ABC

Abstract base class for activating an OpenGL rendering context.

Concrete implementations should manage context binding/unbinding using framework-specific mechanisms (e.g., Qt, GLFW). Supports both manual and scoped activation models.

Thread safety and proper context sharing must be enforced for offscreen usage.

class GLContextScope(provider: GraphicsContextProvider)

Bases: object

Scoped context activator for OpenGL rendering.

Wraps a GraphicsContextProvider and ensures safe and reversible context activation, either manually or using the with statement.

This does not create or destroy the context—it only manages bindings on the current thread.

Parameters:

provider (GraphicsContextProvider) – The context provider instance

Example (manual usage):

scope = provider.scope() scope.make_current() GL.glDrawArrays(…) scope.done_current()

Example (scoped usage):

with provider.scope():

GL.glClear(GL.GL_COLOR_BUFFER_BIT)

Note

Designed for cross-backend compatibility (e.g., Qt, GLFW). May be extended to support profiling, validation, or debugging.

done_current()

Deactivate the OpenGL context via the provider.

make_current()

Activate the OpenGL context via the provider.

destroy()

Optional cleanup method invoked during __exit__. Override to release platform-specific resources.

abstract done_current() None

Unbind the context from the current thread. Typically used after rendering operations.

abstract make_current() None

Bind this context and surface to the current thread. Must be thread-safe and idempotent.

scope()

Create a scoped context activator compatible with with statement usage.

Returns:

A new scoped context manager

Return type:

GraphicsContextProvider.GLContextScope

class xr.utils.Matrix4x4f(data=None)

Bases: object

Attempt to match Matrix4x4f_ctypes API with numpy backing July 24, 2025

as_numpy() ndarray
static create_from_quaternion(quat: Quaternionf) Matrix4x4f
static create_projection(graphics_api: GraphicsAPI, tan_left, tan_right, tan_up, tan_down, near_z, far_z) Matrix4x4f
static create_projection_fov(graphics_api: GraphicsAPI, fov: Fovf, near_z: float, far_z: float) Matrix4x4f
static create_scale(x: float, y: float, z: float) Matrix4x4f
static create_translation(x: float, y: float, z: float) Matrix4x4f
static create_translation_rotation_scale(translation: Vector3f, rotation: Quaternionf, scale: Sequence[float]) Matrix4x4f
invert_rigid_body() Matrix4x4f
class xr.utils.SessionStateManager(instance: Instance, session: LP_Session_T, view_configuration_type: ViewConfigurationType)

Bases: object

Handles OpenXR session state transitions, lifecycle control, and frame loop integration.

This class manages the transition between session states, receives runtime events, and coordinates rendering activity. It also gracefully winds down the session during context exit or shutdown.

Raises:

ExitRenderLoop – When the session transitions into an exit state.

exception ExitRenderLoop

Bases: BaseException

Signal raised to indicate the frame loop should exit immediately.

begin_frame() FrameState | None

Poll OpenXR events and start a frame if the session is running.

Returns:

FrameState if the frame is started, None otherwise.

handle_xr_event(event_buffer: EventDataBuffer) None

Dispatch and handle runtime OpenXR events relevant to the session.

Parameters:

event_buffer – A buffer containing one OpenXR event.

class xr.utils.SwapchainInfo(view: ViewConfigurationView, session: LP_Session_T, color_texture_format: int, swapchain_image_type: Type[SWAPCHAIN_IMAGE_TYPE])

Bases: Generic[SWAPCHAIN_IMAGE_TYPE]

Encapsulates rendering resources for a single OpenXR view.

This class manages the creation and lifecycle of an OpenXR swapchain associated with a single xr.ViewConfigurationView, typically corresponding to one eye. It handles swapchain allocation, image enumeration, and cleanup, and provides metadata useful for framebuffer setup.

Parameters:
  • view (xr.ViewConfigurationView) – Configuration metadata for the current view, including recommended image size and sample count.

  • session (xr.Session) – Active OpenXR session used to create the swapchain.

  • color_texture_format (int) – OpenGL-compatible format constant (e.g., GL_RGBA8).

  • swapchain_image_type (Type[SWAPCHAIN_IMAGE_TYPE]) – ctypes structure type representing swapchain image buffers.

Variables:
  • swapchain (xr.Swapchain) – Handle to the OpenXR swapchain object.

  • size (Tuple[int, int]) – Tuple of (width, height) from the view configuration.

  • images (List[SWAPCHAIN_IMAGE_TYPE]) – List of swapchain image buffers suitable for GPU binding.

Seealso:

xr.create_swapchain(), xr.enumerate_swapchain_images(), xr.SwapchainCreateInfo

class xr.utils.SwapchainSet(instance: Instance, system_id: c_ulonglong, session: LP_Session_T, color_texture_format: int, swapchain_image_type: Type[SWAPCHAIN_IMAGE_TYPE], view_configuration_type: ViewConfigurationType = ViewConfigurationType.PRIMARY_STEREO)

Bases: Generic[SWAPCHAIN_IMAGE_TYPE]

Aggregates swapchains for multiple OpenXR views.

This class creates and manages a collection of per-view xr.Swapchain instances, typically one for each eye in a stereo configuration. It uses an internal contextlib.ExitStack to ensure lifecycle safety and deterministic resource cleanup.

Swapchains are initialized using the recommended parameters from the runtime, as reported by xr.enumerate_view_configuration_views().

Parameters:
  • instance (xr.Instance) – The OpenXR runtime instance.

  • system_id (xr.SystemId) – The headset or rendering system providing view capabilities.

  • session (xr.Session) – The active OpenXR session used to create swapchains.

  • color_texture_format (int) – OpenGL format used for swapchain images (e.g., GL_RGBA8).

  • swapchain_image_type (Type[SWAPCHAIN_IMAGE_TYPE]) – ctypes structure representing each swapchain image.

  • view_configuration_type (xr.ViewConfigurationType) – The view configuration, such as stereo or mono.

Variables:
  • views (List[SwapchainInfo]) – List of view-specific swapchain resources.

  • exit_stack (contextlib.ExitStack) – Internal context manager for cleanup logic.

Seealso:

SwapchainInfo, xr.ViewConfigurationView

class xr.utils.XrEventDispatcher(instance)

Bases: object

Polls OpenXR events and dispatches them to subscribed handlers.

Subscribers must be callables that accept a single event argument.

poll()

Polls events from the OpenXR runtime and dispatches them to all subscribers.

subscribe(callback: Callable[[EventDataBuffer], None])

Register a callback to receive OpenXR events.

Parameters:

callback – A callable that takes one event argument.

xr.utils.projection_from_fovf(fov: Fovf, near: float = 0.05, far: float | None = None) ndarray

Constructs a transposed forward projection matrix from OpenXR FOV angles.

Produces a column-major matrix that maps eye-space to clip-space, suitable for VR rendering. Uses infinite reverse-Z projection by default. If far is specified, constructs a finite-depth variant.

Parameters:
  • fov (xr.Fovf) – Field-of-view angles (radians) with left, right, up, and down.

  • near (float) – Near clipping plane distance; must be positive. Default is 0.05.

  • far (float | None) – Far clipping plane. If None, assumes infinity.

Returns:

Transposed forward projection matrix (4x4) in column-major format (float32).

Return type:

numpy.ndarray

xr.utils.projection_inverse_from_fovf(fov: Fovf, near: float = 0.05, far: float | None = None) ndarray

Constructs a transposed inverse projection matrix from OpenXR FOV angles.

Produces a column-major inverse matrix suitable for reversing clip-to-eye-space transformations in VR. Defaults to infinite reverse-Z depth unless far is provided.

Parameters:
  • fov (xr.Fovf) – Field-of-view angles (radians) with left, right, up, and down.

  • near (float) – Near clipping plane distance; must be positive. Default is 0.05.

  • far (float | None) – Far clipping plane. If None, assumes infinity.

Returns:

Transposed inverse projection matrix (4x4) in column-major format (float32).

Return type:

numpy.ndarray

xr.utils.rotation_from_quaternionf(quat: Quaternionf) ndarray

Constructs a transposed 3×3 rotation matrix from an OpenXR-style quaternion.

Converts a unit quaternion (w, x, y, z) into a right-handed rotation matrix suitable for transforming vectors from local to world space or vice versa. Output is in column-major order to align with OpenGL-style usage, and assumes the quaternion is normalized (unit length). No scale or shear is applied.

Parameters:

quat (xr.Quaternionf) – Quaternion representing rotation, with components (x, y, z, w). Expected to be normalized.

Returns:

3×3 rotation matrix (float32), transposed for column-major layout.

Return type:

numpy.ndarray

xr.utils.view_matrix_from_posef(pose: Posef) ndarray

Construct a view matrix from an OpenXR pose.

This function computes a 4×4 view matrix from a given xr.Posef, which includes orientation (as a quaternion) and position (as a 3D vector). The resulting matrix transforms world-space coordinates into view-space, suitable for rendering from the perspective of the pose.

The view matrix is computed as the inverse of the world transform: \(V = R^T \cdot T^{-1}\), where R is the rotation matrix and T is the translation matrix. The result is returned in column-major (Fortran-style) order to match OpenXR and graphics API conventions.

Parameters:

pose (xr.Posef) – The pose representing the viewer’s position and orientation in world space.

Returns:

A 4×4 view matrix in column-major order.

Return type:

numpy.ndarray

Seealso:

xr.utils.rotation_from_quaternionf(), xr.Posef

xr.utils.view_matrix_inverse_from_posef(pose: Posef) ndarray

Construct an inverse view matrix from an OpenXR pose.

Computes a 4×4 world transform matrix from the given xr.Posef. This matrix applies the pose’s position and orientation in world-space coordinates and is commonly used for camera-relative rendering, physics simulations, or head-to-world transformations.

The matrix is assembled from a rotation (derived from the pose’s quaternion) and translation (from the pose’s 3D position), in the form: \(M = R \cdot T\).

The result is returned in column-major (Fortran-style) order, matching OpenXR and graphics API conventions.

Parameters:

pose (xr.Posef) – The pose describing orientation and position in world space.

Returns:

A 4×4 transformation matrix in column-major order.

Return type:

numpy.ndarray

Seealso:

xr.utils.rotation_from_quaternionf(), xr.Posef