<pre class="metadata">
Shortname: webxr
Title: WebXR Device API
Group: immersivewebwg
Status: ED
TR: https://www.w3.org/TR/webxr/
ED: https://immersive-web.github.io/webxr/
Previous Version: https://www.w3.org/TR/2019/WD-webxr-20191010/
Repository: immersive-web/webxr
Level: 1
Mailing List Archives: https://lists.w3.org/Archives/Public/public-immersive-web/

!Participate: <a href="https://github.com/immersive-web/webxr/issues/new">File an issue</a> (<a href="https://github.com/immersive-web/webxr/issues">open issues</a>)
!Participate: <a href="https://lists.w3.org/Archives/Public/public-immersive-web/">Mailing list archive</a>
!Participate: <a href="irc://irc.w3.org:6665/">W3C's #immersive-web IRC</a>

Editor: Brandon Jones 87824, Google http://google.com/, bajones@google.com
Editor: Nell Waliczek 93109, Amazon [Microsoft until 2018] https://amazon.com/, nhw@amazon.com

Abstract: This specification describes support for accessing virtual reality (VR) and augmented reality (AR) devices, including sensors and head-mounted displays, on the Web.
</pre>

<pre class="link-defaults">
spec:infra;
    type:dfn; text:string
</pre>

<pre class="anchors">
spec:infra; urlPrefix: https://infra.spec.whatwg.org/
    type:dfn; for:list; text:extend; url: list-extend
spec: High Resolution Time; urlPrefix: https://www.w3.org/TR/hr-time/
    type: typedef; text: DOMHighResTimeStamp; url: dom-domhighrestimestamp
spec: WebGL; urlPrefix: https://www.khronos.org/registry/webgl/specs/latest/1.0/
    type: interface; text: WebGLFramebuffer; url: WebGLFramebuffer
    type: interface; text: WebGLRenderingContext; url: WebGLRenderingContext
    type: interface; text: WebGLRenderingContextBase; url: WebGLRenderingContextBase
    type: typedef; text: INVALID_OPERATION; url: WebGLRenderingContextBase
    type: typedef; text: INVALID_FRAMEBUFFER_OPERATION; url: WebGLRenderingContextBase
    type: typedef; text: FRAMEBUFFER_UNSUPPORTED; url: WebGLRenderingContextBase
    type: method; text: uniformMatrix4fv; url: 5.14.10
    type: method; text: framebufferTexture2D;  url: 5.14.6
    type: method; text: framebufferRenderbuffer;  url: 5.14.6
    type: method; text: getFramebufferAttachmentParameter;  url: 5.14.6
    type: method; text: deleteFramebuffer;  url: 5.14.6
    type: method; text: checkFramebufferStatus;  url: 5.14.6
    type: dictionary; text: WebGLContextAttributes; url: #WebGLContextAttributes
    type: dfn; text: Create the WebGL context; url:#2.1
    type: dfn; text: default framebuffer; url:#2.2
    type: dfn; text: WebGL viewport; url:#5.14.4
    type: dfn; text: WebGL context lost flag; url:#webgl-context-lost-flag
    type: dfn; text: handle the context loss; url:#CONTEXT_LOST
    type: dfn; text: Restore the context; url: #restore-the-drawing-buffer
    type: dfn; text: actual context parameters; url: #actual-context-parameters
    type: dfn; text: create a drawing buffer; url: #create-a-drawing-buffer
    type: dfn; text: WebGL task source; url: #5.15
spec: WebGL 2.0; urlPrefix: https://www.khronos.org/registry/webgl/specs/latest/2.0/
    type: interface; text: WebGL2RenderingContext; url: WebGL2RenderingContext
spec: Orientation Sensor; urlPrefix: https://w3c.github.io/orientation-sensor/
    type: interface; text: AbsoluteOrientationSensor
    type: interface; text: RelativeOrientationSensor
spec: WebIDL; urlPrefix: https://www.w3.org/TR/WebIDL-1/#
    type: dfn; text: invoke the Web IDL callback function; url:es-invoking-callback-functions
spec:html; urlPrefix: https://html.spec.whatwg.org/multipage/
    type:method; for:HTMLCanvasElement; text:getContext(contextId); url: canvas.html#dom-canvas-getcontext
    type:method; for:Window; text:requestAnimationFrame(callback); url: imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe
    type: dfn; text: currently focused area; url: interaction.html#currently-focused-area-of-a-top-level-browsing-context
    type: dfn; text: responsible; url: webappapis.html#responsible-document
    type: dfn; text: rendering opportunity; url: webappapis.html#rendering-opportunity
    type: dfn; text: same origin-domain; url: origin.html#same-origin-domain
    type: dfn; text: active document; url: browsers.html#active-document
    type: dfn; text: browsing context; url: browsers.html#browsing-context
spec: SecureContexts; urlPrefix: https://w3c.github.io/webappsec-secure-contexts/#
    type: dfn; text: secure context; url: secure-contexts

spec: ECMAScript; urlPrefix: https://tc39.github.io/ecma262/#
    type: method; text: IsDetachedBuffer; url: sec-isdetachedbuffer
spec: dom; urlPrefix: https://dom.spec.whatwg.org/#
    type:algorithm; text:fire an event; url: concept-event-fire

</pre>

<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="favicon-96x96.png">

<style>
  .head h1:after {
    content: url(images/spec-logo.png);
    float: right;
  }

  .unstable::before {
    content: "This section is not stable";
    display: block;
    font-weight: bold;
    text-align: right;
    color: red;
  }
  .unstable {
    border: thin solid pink;
    border-radius: .5em;
    padding: .5em;
    margin: .5em calc(-0.5em - 1px);
    background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='290'><text transform='rotate(-45)' text-anchor='middle' font-family='sans-serif' font-weight='bold' font-size='70' y='210' opacity='.1'>Unstable</text></svg>");
    background-repeat: repeat;
    background-color: #FFF4F4;
  }
  .unstable h3:first-of-type {
    margin-top: 0.5rem;
  }

  .unstable.example:not(.no-marker)::before {
    content: "Example " counter(example) " (Unstable)";
    float: none;
  }

  .non-normative::before {
    content: "This section is non-normative.";
    font-style: italic;
  }
  .tg {
    border-collapse: collapse;
    border-spacing: 0;
  }
  .tg th {
    border-style: solid;
    border-width: 1px;
    background: #90b8de;
    color: #fff;
    font-family: sans-serif;
    font-weight: bold;
    border-color: grey;
  }
  .tg td {
    padding: 4px 5px;
    background-color: rgb(221, 238, 255);
    font-family: monospace;
    border-style: solid;
    border-width: 1px;
    border-color: grey;
    overflow: hidden;
    word-break: normal;
  }
</style>

Introduction {#intro}
============

<section class="non-normative">

Hardware that enables Virtual Reality (VR) and Augmented Reality (AR) applications are now broadly available to consumers, offering an immersive computing platform with both new opportunities and challenges. The ability to interact directly with immersive hardware is critical to ensuring that the web is well equipped to operate as a first-class citizen in this environment.

Immersive computing introduces strict requirements for high-precision, low-latency communication in order to deliver an acceptable experience. It also brings unique [[#security|security]] concerns for a platform like the web. The WebXR Device API provides the interfaces necessary to enable developers to build compelling, comfortable, and safe immersive applications on the web across a wide variety of hardware form factors.

Other web interfaces, such as the {{RelativeOrientationSensor}} and {{AbsoluteOrientationSensor}}, can be repurposed to surface input from some devices to polyfill the WebXR Device API in limited situations. These interfaces cannot support multiple features of high-end immersive experiences, however, such as [=6DoF=] tracking, presentation to headset peripherals, or tracked input devices.

</section>

Terminology {#terminology}
-----------

This document uses the acronym <b>XR</b> throughout to refer to the spectrum of hardware, applications, and techniques used for Virtual Reality, Augmented Reality, and other related technologies. Examples include, but are not limited to:

 * Head-mounted displays, whether they are opaque, transparent, or utilize video passthrough
 * Mobile devices with positional tracking
 * Fixed displays with head tracking capabilities

The important commonality between them being that they offer some degree of spatial tracking with which to simulate a view of virtual content.

Terms like "XR device", "XR Application", etc. are generally understood to apply to any of the above. Portions of this document that only apply to a subset of these devices will indicate so as appropriate.

The terms [=3DoF=] and [=6DoF=] are used throughout this document to describe the tracking capabilities of [=/XR devices=].

 - A <dfn>3DoF</dfn> device, short for "Three Degrees of Freedom", is one that can only track rotational movement. This is common in devices which rely exclusively on accelerometer and gyroscope readings to provide tracking. [=3DoF=] devices do not respond translational movements from the user, though they may employ algorithms to estimate translational changes based on modeling of the neck or arms.
 - A <dfn>6DoF</dfn> device, short for "Six Degrees of Freedom", is one that can track both rotation and translation, enabling for precise 1:1 tracking in space. This typically requires some level of understanding of the user's environment. That environmental understanding may be achieved via inside-out tracking, where sensors on the tracked device itself (such as cameras or depth sensors) are used to determine the device's position, or outside-in tracking, where external devices placed in the user's environment (like a camera or light emitting device) provides a stable point of reference against which the [=/XR device=] can determine its position.

Application flow {#applicationflow}
----------------

<section class="non-normative">

Most applications using the WebXR Device API will follow a similar usage pattern:

  * Query {{XR/isSessionSupported()|navigator.xr.isSessionSupported()}} to determine if the desired type of XR content is supported by the hardware and UA.
  * If so, advertise the XR content to the user.
  * Wait for the user to [=triggered by user activation|trigger a user activation event=] indicating they want to begin viewing XR content.
  * Request an {{XRSession}} within the user activation event with {{XR/requestSession()|navigator.xr.requestSession()}}.
  * If the {{XRSession}} request succeeds, use it to run a [[#frame|frame loop]] to respond to XR input and produce images to display on the [=XRSession/XR device=] in response.
  * Continue running the [[#frame|frame loop]] until the [=shut down the session|session is shut down=] by the UA or the user indicates they want to exit the XR content.

</section>

Model {#model}
=====

XR device {#xr-device-concept}
---------

An <dfn for="">XR device</dfn> is a physical unit of hardware that can present imagery to the user. On desktop clients, this is usually a headset peripheral. On mobile clients, it may represent the mobile device itself in conjunction with a viewer harness. It may also represent devices without stereo-presentation capabilities but with more advanced tracking.

An [=/XR device=] has a <dfn>list of supported modes</dfn> (a [=/list=] of [=/strings=]) that [=list/contains=] the enumeration values of {{XRSessionMode}} that the [=/XR device=] supports.

The user-agent MUST have an <dfn>inline XR device</dfn>, which is an [=/XR device=] that MUST [=list/contains|contain=] {{XRSessionMode/"inline"}} in its [=list of supported modes=]. The [=inline XR device=] SHOULD report as much pose information of the physical device the user agent is rendering to as possible. This device MAY be the same as the [=XR/immersive XR device=] if one is present, but doesn't have to be.

Note: On phones, the [=inline XR device=] may report pose information derived from the phone's internal sensors, such as the gyroscope and accelerometer. On desktops and laptops without similar sensors, the [=inline XR device=] will not be able to report a pose. In case the user agent is already running on an [=/XR device=], the [=inline XR device=] will be the same device, and may support multiple [=view|views=].

Initialization {#initialization}
==============

navigator.xr {#navigator-xr-attribute}
------------

<pre class="idl">
partial interface Navigator {
  [SecureContext, SameObject] readonly attribute XR xr;
};
</pre>

The <dfn attribute for="Navigator">xr</dfn> attribute's getter MUST return the {{XR}} object that is associated with the [=context object=].

XR {#xr-interface}
----

<pre class="idl">
[SecureContext, Exposed=Window] interface XR : EventTarget {
  // Methods
  Promise&lt;boolean&gt; isSessionSupported(XRSessionMode mode);
  [NewObject] Promise&lt;XRSession&gt; requestSession(XRSessionMode mode, optional XRSessionInit options = {});

  // Events
  attribute EventHandler ondevicechange;
};
</pre>

The user agent MUST create an {{XR}} object when a {{Navigator}} object is created and associate it with that object.

An {{XR}} object is the entry point to the API, used to query for XR features available to the user agent and initiate communication with XR hardware via the creation of {{XRSession}}s.

An {{XR}} object has a <dfn>list of immersive XR devices</dfn> (a [=/list=] of [=/XR device=]), which MUST be initially an empty [=/list=].

An {{XR}} object has an <dfn for=XR>immersive XR device</dfn> (null or [=/XR device=]) which is initially null and represents the active [=/XR device=] from the [=list of immersive XR devices=].

The user agent MUST be able to <dfn>enumerate immersive XR devices</dfn> attached to the system, at which time each available device is placed in the [=list of immersive XR devices=]. Subsequent algorithms requesting enumeration MUST reuse the cached [=list of immersive XR devices=]. Enumerating the devices [=should not initialize device tracking=]. After the first enumeration the user agent MUST begin monitoring device connection and disconnection, adding connected devices to the [=list of immersive XR devices=] and removing disconnected devices.

<div class="algorithm" data-algorithm="xr-device-selection">

Each time the [=list of immersive XR devices=] changes the user agent should <dfn>select an immersive XR device</dfn> by running the following steps:

  1. Let |oldDevice| be the [=XR/immersive XR device=].
  1. If the [=list of immersive XR devices=] is an empty [=/list=], set the [=XR/immersive XR device=] to <code>null</code>.
  1. If the [=list of immersive XR devices=]'s [=list/size=] is one, set the [=XR/immersive XR device=] to the [=list of immersive XR devices=][0].
  1. Set the [=XR/immersive XR device=] as follows:
    <dl class="switch">
      <dt> If there are any active {{XRSession}}s and the [=list of immersive XR devices=] [=list/contains=] |oldDevice|
      <dd> Set the [=XR/immersive XR device=] to |oldDevice|
      <dt> Otherwise
      <dd> Set the [=XR/immersive XR device=] to a device of the user agent's choosing
    </dl>
  1. If this is the first time devices have been enumerated or |oldDevice| equals the [=XR/immersive XR device=], abort these steps.
  1. [=Shut down the session|Shut down=] any active {{XRSession}}s.
  1. Set the [=XR compatible=] boolean of all {{WebGLRenderingContextBase}} instances to <code>false</code>.
  1. [=Queue a task=] to [=fire an event=] named {{devicechange!!event}} on the [=context object=].

</div>

Note: The user agent is allowed to use any criteria it wishes to [=select an immersive XR device=] when the [=list of immersive XR devices=] contains multiple devices. For example, the user agent may always select the first item in the list, or provide settings UI that allows users to manage device priority. Ideally the algorithm used to select the default device is stable and will result in the same device being selected across multiple browsing sessions.

<div class="algorithm" data-algorithm="ensure-device-selected">

The user agent <dfn>ensures an immersive XR device is selected</dfn> by running the following steps:

  1. If the [=context object=]'s [=XR/immersive XR device=] is not null, abort these steps.
  1. [=Enumerate immersive XR devices=].
  1. [=Select an immersive XR device=].

</div>

The <dfn attribute for="XR">ondevicechange</dfn> attribute is an [=Event handler IDL attribute=] for the {{devicechange}} event type.

<div class="algorithm" data-algorithm="session-supported">
The <dfn method for="XR">isSessionSupported(|mode|)</dfn> method queries if a given |mode| is supported by the user agent and device capabilities.

When this method is invoked, it MUST run the following steps:

  1. Let |promise| be [=a new Promise=].
  1. If |mode| is {{XRSessionMode/"inline"}}, [=/resolve=] |promise| with <code>true</code> and return it.
  1. Run the following steps [=in parallel=]:
    1. If the requesting document's origin is not allowed to use the "xr-spatial-tracking" [[#feature-policy|feature policy]], [=reject=] |promise| with a "{{SecurityError}}" {{DOMException}} and abort these steps.
    1. [=ensures an immersive XR device is selected|Ensure an immersive XR device is selected=].
    1. If the [=XR/immersive XR device=] is null, [=/resolve=] |promise| with <code>false</code> and abort these steps.
    1. If the [=XR/immersive XR device=]'s [=list of supported modes=] does not [=list/contain=] |mode|, [=/resolve=] |promise| with <code>false</code> and abort these steps.
    1. [=/Resolve=] |promise| with <code>true</code>.
  1. Return |promise|.

</div>

Calling {{XR/isSessionSupported()}} MUST NOT trigger device-selection UI as this would cause many sites to display XR-specific dialogs early in the document lifecycle without user activation. Additionally, calling {{XR/isSessionSupported()}} MUST NOT interfere with any running XR applications on the system, and MUST NOT cause XR-related applications to launch such as system trays or storefronts.

<div class="example">
The following code checks to see if {{immersive-vr}} sessions are supported.

<pre highlight="js">
navigator.xr.isSessionSupported('immersive-vr').then((supported) => {
  if (supported) {
    // 'immersive-vr' sessions are supported.
    // Page should advertise support to the user.
  } else {
    // 'immersive-vr' sessions are not supported.
  }
}
</pre>
</div>

The {{XR}} object has a <dfn>pending immersive session</dfn> boolean, which MUST be initially <code>false</code>, an <dfn>active immersive session</dfn>, which MUST be initially <code>null</code>, and a <dfn>list of inline sessions</dfn>, which MUST be initially empty.

<div class="algorithm" data-algorithm="request-session">

The <dfn method for="XR">requestSession(|mode|, |options|)</dfn> method attempts to initialize an {{XRSession}} for the given |mode| if possible, entering immersive mode if necessary.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |promise| be [=a new Promise=].
  1. Let |immersive| be <code>true</code> if |mode| is an [=immersive session=] mode, and <code>false</code> otherwise.
  1. Check whether the session request is allowed as follows:
    <dl class="switch">
      <dt>If |immersive| is <code>true</code></dt>
      <dd>
        1. Check if an [=immersive session request is allowed=], and if not [=reject=] |promise| with a "{{SecurityError}}" {{DOMException}} and return |promise|.
        1. If [=pending immersive session=] is <code>true</code> or [=active immersive session=] is not <code>null</code>, [=reject=] |promise| with an "{{InvalidStateError}}" {{DOMException}} and return |promise|.
        1. Set [=pending immersive session=] to <code>true</code>.
      </dd>
      <dt>Otherwise</dt>
      <dd>Check if an [=inline session request is allowed=], and if not [=reject=] |promise| with a "{{SecurityError}}" {{DOMException}} and return |promise|.</dd>
    </dl>
  1. Run the following steps [=in parallel=]:
    1. Choose |device| as follows:
        <dl class="switch">
          <dt>If |immersive| is <code>true</code></dt>
          <dd>
              1. [=ensures an immersive XR device is selected|Ensure an immersive XR device is selected=].
              1. Set |device| to the [=XR/immersive XR device=].
          </dd>
          <dt>Otherwise</dt>
          <dd>Set |device| to the [=inline XR device=].</dd>
        </dl>
    1. [=Queue a task=] to perform the following steps:
        1. If |device| is <code>null</code> or |device|'s [=list of supported modes=] does not [=list/contain=] |mode|, run the following steps:
            1. [=Reject=] |promise| with a "{{NotSupportedError}}" {{DOMException}}.
            1. If |immersive| is <code>true</code>, set [=pending immersive session=] to <code>false</code>.
            1. Abort these steps.
        1. Let |session| be a new {{XRSession}} object.
        1. [=Initialize the session=] with |session|, |mode|, and |device|.
        1. [=Resolve the requested features=] given by |options|' {{XRSessionInit/requiredFeatures}} and |options|' {{XRSessionInit/optionalFeatures}} values for |session|, and let |resolved| be the returned value.
        1. If |resolved| is <code>false</code>, run the following steps:
            1. [=Reject=] |promise| with a "{{NotSupportedError}}" {{DOMException}}.
            1. If |immersive| is <code>true</code>, set [=pending immersive session=] to <code>false</code>.
            1. Abort these steps.
        1. Potentially set the [=active immersive session=] as follows:
            <dl class="switch">
              <dt> If |immersive| is <code>true</code>
              <dd> Set the [=active immersive session=] to |session|, and set [=pending immersive session=] to <code>false</code>.
              <dt> Otherwise
              <dd> Append |session| to the [=list of inline sessions=].
            </dl>
        1. [=/Resolve=] |promise| with |session|.
  1. Return |promise|.

</div>

<div class="example">
The following code attempts to retrieve an {{immersive-vr}} {{XRSession}}.

<pre highlight="js">
let xrSession;

navigator.xr.requestSession("immersive-vr").then((session) => {
  xrSession = session;
});
</pre>
</div>

XRSessionMode {#xrsessionmode-enum}
-------------

The {{XRSessionMode}} enum defines the modes that an {{XRSession}} can operate in.

<pre class="idl">
enum XRSessionMode {
  "inline",
  "immersive-vr",
  "immersive-ar"
};
</pre>

  - A session mode of <dfn enum-value for="XRSessionMode">inline</dfn> indicates that the session's output will be shown as an element in the HTML document. {{inline}} session content MUST be displayed in mono (i.e., with a single [=view=]). It MAY allow for [=viewer=] tracking. User agents MUST allow {{inline}} sessions to be created.
  - A session mode of <dfn enum-value for="XRSessionMode">immersive-vr</dfn> indicates that the session's output will be given [=exclusive access=] to the [=XR/immersive XR device=] display and that content <b>is not</b> intended to be integrated with the user's environment.
  - The behavior of the <dfn enum-value for="XRSessionMode">immersive-ar</dfn> session mode is defined in the <a href="https://immersive-web.github.io/webxr-ar-module/">WebXR AR Module</a> and MUST NOT be added to the [=XR/immersive XR device=]'s [=list of supported modes=] unless the UA implements that module.

In this document, the term <dfn>inline session</dfn> is synonymous with an {{inline}} session and the term <dfn>immersive session</dfn> refers to either an {{immersive-vr}} or {{immersive-ar}} session.

[=Immersive sessions=] MUST provide some level of [=viewer=] tracking, and content MUST be shown at the proper scale relative to the user and/or the surrounding environment. Additionally, [=Immersive sessions=] MUST be given <dfn>exclusive access</dfn> to the [=XR/immersive XR device=], meaning that while the [=immersive session=] is {{XRVisibilityState/"visible"}} the HTML document is not shown on the [=XR/immersive XR device=]'s display, nor does content from any other source have exclusive access. [=Exclusive access=] does not prevent the user agent from overlaying its own UI, however this UI SHOULD be minimal.

Note: Future specifications or modules may expand the definition of [=immersive session=] include additional session modes.

Note: Examples of ways [=exclusive access=] may be presented include stereo content displayed on a virtual reality headset.

Note: As an example of overlaid UI, the user-agent or operating system in an [=immersive session=] may show notifications over the rendered content.

Feature Dependencies {#feature-dependencies}
--------------------

Some features of an {{XRSession}} may not be universally available for a number of reasons, among which is the fact not all XR devices can support the full set of features. Another consideration is that some features expose [=sensitive information=] which may require a clear signal of [=user intent=] before functioning.

Since it is a poor user experience to initialize the underlying XR platform and create an {{XRSession}} only to immediately notify the user that the applications cannot function correctly, developers can indicate <dfn>required features</dfn> by passing an {{XRSessionInit}} dictionary to {{XR/requestSession()}}. This will block the creation of the {{XRSession}} if any of the [=required features=] are unavailable due to device limitations or in the absence of a clear signal of [=user intent=] to expose [=sensitive information=] related to the feature.

Additionally, developers are encouraged to design experiences which progressively enhance their functionality when run one more capable devices. <dfn>Optional features</dfn> which the experience does not require but will take advantage of when available must also be indicated in an {{XRSessionInit}} dictionary to ensure that [=user intent=] can be determined before enabling the feature if necessary.

<pre class="idl">
dictionary XRSessionInit {
  sequence&lt;any&gt; requiredFeatures;
  sequence&lt;any&gt; optionalFeatures;
};
</pre>

The <dfn dict-member for="XRSessionInit">requiredFeatures</dfn> array contains any [=Required features=] for the experience. If any value in the list is not a recognized [=feature descriptor=] the {{XRSession}} will not be created. If any feature listed in the {{XRSessionInit/requiredFeatures}} array is not supported by the [=XRSession/XR device=] or, if necessary, has not received a clear signal of [=user intent=] the {{XRSession}} will not be created.

The <dfn dict-member for="XRSessionInit">optionalFeatures</dfn> array contains any [=Optional features=] for the experience. If any value in the list is not a recognized [=feature descriptor=] it will be ignored. Features listed in the {{XRSessionInit/optionalFeatures}} array will be enabled if supported by the [=XRSession/XR device=] and, if necessary, given a clear signal of [=user intent=], but will not block creation of the {{XRSession}} if absent.

Values given in the feature lists are considered a valid <dfn>feature descriptor</dfn> if the value is one of the following:

 - Any {{XRReferenceSpaceType}} enum value

Future iterations of this specification and additional modules may expand the list of accepted [=feature descriptors=].

Note: Features are accepted as an array of <code>any</code> values to ensure forwards compatibility. It allows unrecognized optional values to be properly ignored as new [=feature descriptor=] types are added.

Depending on the {{XRSessionMode}} requested, certain [=feature descriptors=] are added to the {{XRSessionInit/requiredFeatures}} or {{XRSessionInit/optionalFeatures}} lists by default. The following table describes the <dfn>default features</dfn> associated with each session type and feature list:

<table class="tg">
  <thead>
    <tr>
      <th>Feature</th>
      <th>Sessions</th>
      <th>List</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{XRReferenceSpaceType/"viewer"}}</td>
      <td>[=Inline sessions=] and [=immersive sessions=]</td>
      <td>{{XRSessionInit/requiredFeatures}}</td>
    </tr>
    <tr>
      <td>{{XRReferenceSpaceType/"local"}}</td>
      <td>[=Immersive sessions=]</td>
      <td>{{XRSessionInit/requiredFeatures}}</td>
    </tr>
  </tbody>
</table>

The combined list of [=feature descriptors=] given by the {{XRSessionInit/requiredFeatures}} and {{XRSessionInit/optionalFeatures}} are collectively considered the <dfn>requested features</dfn> for an {{XRSession}}.

Some [=feature descriptors=], when present in the [=requested features=] list, are subject to [[#feature-policy|feature policy]] and/or requirements that [=user intent=] to use the feature is well understood, via either [=explicit consent=] or [=implicit consent=]. The following table describes the <dfn>feature requirements</dfn> that must be satisfied prior to being enabled:

<table class="tg">
  <thead>
    <tr>
      <th>Feature</th>
      <th>Feature Policy Required</th>
      <th>Consent Required</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{XRReferenceSpaceType/"local"}}</td>
      <td>"xr-spatial-tracking"</td>
      <td>[=Inline sessions=] require consent</td>
    </tr>
    <tr>
      <td>{{XRReferenceSpaceType/"local-floor"}}</td>
      <td>"xr-spatial-tracking"</td>
      <td>Always requires consent</td>
    </tr>
    <tr>
      <td>{{XRReferenceSpaceType/"bounded-floor"}}</td>
      <td>"xr-spatial-tracking"</td>
      <td>Always requires consent</td>
    </tr>
    <tr>
      <td>{{XRReferenceSpaceType/"unbounded"}}</td>
      <td>"xr-spatial-tracking"</td>
      <td>Always requires consent</td>
    </tr>
  </tbody>
</table>

Note: {{XRReferenceSpaceType/"local"}} is always included in the [=requested features=] of [=immersive sessions=] as a [=default feature=], and as such [=immersive sessions=] always need to obtain [=explicit consent=] or [=implicit consent=].

[=Requested features=] can only be enabled for a session if the [=XRSession/XR device=] is <dfn>capable of supporting</dfn> the feature, which means that the feature is known to be supported by the [=XRSession/XR device=] in some configurations, even if the current configuration has not yet been verified as supporting the feature. The user agent MAY apply more rigorous constraints if desired in order to yield a more consistent user experience.

Note: For example, several VR devices support either configuring a safe boundary for the user to move around within or skipping boundary configuration and operating in a mode where the user is expected to stand in place. Such a device can be considered to be [=capable of supporting=] {{"bounded-floor"}} {{XRReferenceSpace}}s even if they are currently not configured with safety boundaries, because it's expected that the user could configure the device appropriately if the experience required it. This is to allow user agents to avoid fully initializing the [=XRSession/XR device=] or waiting for the user's environment to be recognized prior to [=resolve the requested features|resolving the requested features=] if desired. If, however, the user agent knows that the boundary state at the time the session is requested without additional initialization it may choose to reject the {{"bounded-floor"}} feature if the safety boundary not already configured.

<div class="algorithm" data-algorithm="resolve-features">

To <dfn>resolve the requested features</dfn> given |requiredFeatures| and |optionalFeatures| for an {{XRSession}} |session|, the user agent MUST run the following steps:

  1. Let |consentRequired| be an empty [=/list=] of {{DOMString}}.
  1. Let |consentOptional| be an empty [=/list=] of {{DOMString}}.
  1. Add every [=feature descriptor=] in the [=default features=] table associated with |session|'s [=XRSession/mode=] to the indicated feature list if it is not already present.
  1. For each |feature| in |requiredFeatures| perform the following steps:
    1. If |feature| is not a valid [=feature descriptor=], return <code>false</code>.
    1. If the requesting document's origin is not allowed to use any [[#feature-policy|feature policy]] required by |feature| as indicated by the [=feature requirements=] table, return <code>false</code>.
    1. If |session|'s [=XRSession/XR device=] is not [=capable of supporting=] the functionality described by |feature| or the user agent has otherwise determined to reject the feature, return <code>false</code>.
    1. If the functionality described by |feature| requires [=explicit consent=], append it to |consentRequired|.
    1. Else append |feature| to |session|'s [=list of enabled features=].
  1. For each |feature| in |optionalFeatures| perform the following steps:
    1. If |feature| is not a valid [=feature descriptor=], continue to the next entry.
    1. If the requesting document's origin is not allowed to use any [[#feature-policy|feature policy]] required by |feature| as indicated by the [=feature requirements=] table, continue to the next entry.
    1. If |session|'s [=XRSession/XR device=] is not [=capable of supporting=] the functionality described by |feature| or the user agent has otherwise determined to reject the feature, continue to the next entry.
    1. If the functionality described by |feature| requires [=explicit consent=], append it to |consentOptional|.
    1. Else append |feature| to |session|'s [=list of enabled features=].
  1. If |consentRequired| or |consentOptional| are not empty, request [=explicit consent=] to use the functionality described by those features.
  1. For each |feature| in |consentRequired| perform the following steps:
    1. If a clear signal of [=user intent=] to enable |feature| has not been given, return <code>false</code>.
    1. Else append |feature| to |session|'s [=list of enabled features=].
  1. For each |feature| in |consentOptional| perform the following steps:
    1. If a clear signal of [=user intent=] to enable |feature| has not been given, continue to the next entry.
    1. Else append |feature| to |session|'s [=list of enabled features=].
  1. Return <code>true</code>

</div>

Session {#session}
=======

XRSession {#xrsession-interface}
---------

Any interaction with XR hardware is done via an {{XRSession}} object, which can only be retrieved by calling {{requestSession()}} on the {{XR}} object. Once a session has been successfully acquired, it can be used to {{XRFrame/getViewerPose()|poll the viewer pose}}, query information about the user's environment, and present imagery to the user.

The user agent, when possible, <dfn>SHOULD NOT initialize device tracking</dfn> or rendering capabilities until an {{XRSession}} has been acquired. This is to prevent unwanted side effects of engaging the XR systems when they're not actively being used, such as increased battery usage or related utility applications from appearing when first navigating to a page that only wants to test for the presence of XR hardware in order to advertise XR features. Not all XR platforms offer ways to detect the hardware's presence without initializing tracking, however, so this is only a strong recommendation.

<pre class="idl">
enum XRVisibilityState {
  "visible",
  "visible-blurred",
  "hidden",
};

[SecureContext, Exposed=Window] interface XRSession : EventTarget {
  // Attributes
  readonly attribute XRVisibilityState visibilityState;
  [SameObject] readonly attribute XRRenderState renderState;
  [SameObject] readonly attribute XRInputSourceArray inputSources;

  // Methods
  void updateRenderState(optional XRRenderStateInit state = {});
  [NewObject] Promise&lt;XRReferenceSpace&gt; requestReferenceSpace(XRReferenceSpaceType type);

  long requestAnimationFrame(XRFrameRequestCallback callback);
  void cancelAnimationFrame(long handle);

  Promise&lt;void&gt; end();

  // Events
  attribute EventHandler onend;
  attribute EventHandler oninputsourceschange;
  attribute EventHandler onselect;
  attribute EventHandler onselectstart;
  attribute EventHandler onselectend;
  attribute EventHandler onsqueeze;
  attribute EventHandler onsqueezestart;
  attribute EventHandler onsqueezeend;
  attribute EventHandler onvisibilitychange;
};
</pre>

Each {{XRSession}} has a <dfn for="XRSession">mode</dfn>, which is one of the values of {{XRSessionMode}}.

<div class="algorithm" data-algorithm="initialize-session">

To <dfn>initialize the session</dfn>, given |session|, |mode|, and |device|, the user agent MUST run the following steps:
  1. Set |session|'s [=XRSession/mode=] to |mode|.
  1. Set |session|'s [=XRSession/XR device=] to |device|.
  1. [=Initialize the render state=].
  1. If no other features of the user agent have done so already, perform the necessary platform-specific steps to initialize the device's tracking and rendering capabilities, including showing any necessary instructions to the user.

Note: Some devices require additional user instructions for activation. For example, going into immersive mode on a phone-based headset device requires inserting the phone into the headset, and doing so on a desktop browser connected to an external headset requires wearing the headset. It is the responsibility of the user agent &mdash; not the author &mdash; to ensure any such instructions are shown.

</div>

A number of different circumstances may <dfn>shut down the session</dfn>, which is permanent and irreversible. Once a session has been shut down the only way to access the [=XRSession/XR device=]'s tracking or rendering capabilities again is to request a new session. Each {{XRSession}} has an <dfn>ended</dfn> boolean, initially set to <code>false</code>, that indicates if it has been shut down.

<div class="algorithm" data-algorithm="shut-down-session">

When an {{XRSession}} is shut down the following steps are run:

  1. Let |session| be the target {{XRSession}} object.
  1. Set |session|'s [=ended=] value to <code>true</code>.
  1. If the [=active immersive session=] is equal to |session|, set the [=active immersive session=] to <code>null</code>.
  1. Remove |session| from the [=list of inline sessions=].
  1. [=Reject=] any outstanding promises returned by |session| with an {{InvalidStateError}}, except for any promises returned by {{XRSession/end()}}.
  1. If no other features of the user agent are actively using them, perform the necessary platform-specific steps to shut down the device's tracking and rendering capabilities. This MUST include:
    - Releasing [=exclusive access=] to the [=XRSession/XR device=] if |session| is an [=immersive session=].
    - Deallocating any graphics resources acquired by |session| for presentation to the [=XRSession/XR device=].
    - Putting the [=XRSession/XR device=] in a state such that a different source may be able to initiate a session with the same device if |session| is an [=immersive session=].
  1. [=Queue a task=] that fires an {{XRSessionEvent}} named {{end!!event}} on |session|.

</div>

<div class="algorithm" data-algorithm="end-session">

The <dfn method for="XRSession">end()</dfn> method provides a way to manually shut down a session. When invoked, it MUST run the following steps:

  1. Let |promise| be [=a new Promise=].
  1. [=Shut down the session|Shut down=] the target {{XRSession}} object.
  1. [=Queue a task=] to perform the following steps:
    1. Wait until any platform-specific steps related to shutting down the session have completed.
    1. [=/Resolve=] |promise|.
  1. Return |promise|.

</div>

Each {{XRSession}} has a <dfn for="XRSession">list of enabled features</dfn>, which is a [=/list=] of [=feature descriptors=] which MUST be initially an empty [=/list=]

Each {{XRSession}} has an <dfn>active render state</dfn> which is a new {{XRRenderState}}, and a <dfn>pending render state</dfn>, which is an {{XRRenderState}} which is initially <code>null</code>.

The <dfn attribute for="XRSession">renderState</dfn> attribute returns the {{XRSession}}'s [=active render state=].

Each {{XRSession}} has a <dfn>minimum inline field of view</dfn> and a <dfn>maximum inline field of view</dfn>, defined in radians. The values MUST be determined by the user agent and MUST fall in the range of <code>0</code> to <code>PI</code>.

Each {{XRSession}} has a <dfn>minimum near clip plane</dfn> and a <dfn>maximum far clip plane</dfn>, defined in meters. The values MUST be determined by the user agent and MUST be non-negative. The [=minimum near clip plane=] SHOULD be less than <code>0.1</code>. The [=maximum far clip plane=] SHOULD be greater than <code>1000.0</code> (and MAY be infinite).

<div class="algorithm" data-algorithm="update-render-state">

The <dfn method for="XRSession">updateRenderState(|newState|)</dfn> method queues an update to the [=active render state=] to be applied on the next frame. Unset fields of the {{XRRenderStateInit}} |newState| passed to this method will not be changed.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |session| be the target {{XRSession}}.
  1. If |session|'s [=ended=] value is <code>true</code>, throw an {{InvalidStateError}} and abort these steps.
  1. If |newState|'s {{XRRenderStateInit/baseLayer}}'s was created with an {{XRSession}} other than |session|, throw an {{InvalidStateError}} and abort these steps.
  1. If |newState|'s {{XRRenderStateInit/inlineVerticalFieldOfView}} is set and |session| is an [=immersive session=], throw an {{InvalidStateError}} and abort these steps.
  1. Let |activeState| be |session|'s [=active render state=].
  1. If |session|'s [=pending render state=] is <code>null</code>, set it to a copy of |activeState|.
  1. If |newState|'s {{XRRenderStateInit/depthNear}} value is set, set |session|'s [=pending render state=]'s {{XRRenderState/depthNear}} to |newState|'s {{XRRenderStateInit/depthNear}}.
  1. If |newState|'s {{XRRenderStateInit/depthFar}} value is set, set |session|'s [=pending render state=]'s {{XRRenderState/depthFar}} to |newState|'s {{XRRenderStateInit/depthFar}}.
  1. If |newState|'s {{XRRenderStateInit/inlineVerticalFieldOfView}} is set, set |session|'s [=pending render state=]'s {{XRRenderState/inlineVerticalFieldOfView}} to |newState|'s {{XRRenderStateInit/inlineVerticalFieldOfView}}.
  1. If |newState|'s {{XRRenderStateInit/baseLayer}} is set, set |session|'s [=pending render state=]'s {{XRRenderState/baseLayer}} to |newState|'s {{XRRenderStateInit/baseLayer}}.

</div>

<div class="algorithm" data-algorithm="apply-pending-render-state">

When requested, the {{XRSession}} MUST <dfn>apply the pending render state</dfn> by running the following steps:

  1. Let |session| be the target {{XRSession}}.
  1. Let |activeState| be |session|'s [=active render state=].
  1. Let |newState| be |session|'s [=pending render state=].
  1. Set |session|'s [=pending render state=] to <code>null</code>.
  1. Set |activeState| to |newState|.
  1. If |activeState|'s {{XRRenderState/inlineVerticalFieldOfView}} is less than |session|'s [=minimum inline field of view=] set |activeState|'s {{XRRenderState/inlineVerticalFieldOfView}} to |session|'s [=minimum inline field of view=].
  1. If |activeState|'s {{XRRenderState/inlineVerticalFieldOfView}} is greater than |session|'s [=maximum inline field of view=] set |activeState|'s {{XRRenderState/inlineVerticalFieldOfView}} to |session|'s [=maximum inline field of view=].
  1. If |activeState|'s {{XRRenderState/depthNear}} is less than |session|'s [=minimum near clip plane=] set |activeState|'s {{XRRenderState/depthNear}} to |session|'s [=minimum near clip plane=].
  1. If |activeState|'s {{XRRenderState/depthFar}} is less than |session|'s [=maximum far clip plane=] set |activeState|'s {{XRRenderState/depthFar}} to |session|'s [=maximum far clip plane=].
  1. Let |baseLayer| be |activeState|'s {{XRRenderState/baseLayer}}.
  1. Set |activeState|'s [=XRRenderState/composition disabled=] and [=XRRenderState/output canvas=] as follows:
    <dl class="switch">
      <dt> If |session|'s [=XRSession/mode=] is {{XRSessionMode/"inline"}} and |baseLayer| is an instance of an {{XRWebGLLayer}} with [=XRWebGLLayer/composition disabled=] set to <code>true</code>
      <dd> Set |activeState|'s [=XRRenderState/composition disabled=] boolean to <code>true</code>.
      <dd> Set |activeState|'s [=XRRenderState/output canvas=] to |baseLayer|'s [=XRWebGLLayer/context=]'s {{WebGLRenderingContext|canvas}}.
      <dt> Otherwise
      <dd> Set |activeState|'s [=XRRenderState/composition disabled=] boolean to <code>false</code>.
      <dd> Set |activeState|'s [=XRRenderState/output canvas=] to <code>null</code>.
    </dl>

</div>

<div class="algorithm" data-algorithm="request-reference-space">
The <dfn method for="XRSession">requestReferenceSpace(|type|)</dfn> method constructs a new {{XRReferenceSpace}} of a given |type|, if possible.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |promise| be [=a new Promise=].
  1. Run the following steps [=in parallel=]:
    1. [=Create a reference space=], |referenceSpace|, with the {{XRReferenceSpaceType}} |type|.
    1. If |referenceSpace| is <code>null</code>, [=reject=] |promise| with a {{NotSupportedError}} and abort these steps.
    1. [=/Resolve=] |promise| with |referenceSpace|.
  1. Return |promise|.

</div>

Each {{XRSession}} has a <dfn>list of active XR input sources</dfn> (a [=/list=] of {{XRInputSource}}) which MUST be initially an empty [=/list=].

Each {{XRSession}} has an <dfn for="XRSession">XR device</dfn>, which is an [=/XR device=] set at initialization.

The <dfn attribute for="XRSession">inputSources</dfn> attribute returns the {{XRSession}}'s [=list of active XR input sources=].

The user agent MUST monitor any [=XR input source=]s associated with the [=XRSession/XR device=], including detecting when [=XR input source=]s are added, removed, or changed.

<div class="algorithm" data-algorithm="on-input-source-added">

When <dfn for="XRSession" lt="add input source">new [=XR input source=]s become available</dfn> for {{XRSession}} |session|, the user agent MUST run the following steps:

  1. Let |added| be a new [=/list=].
  1. For each new [=XR input source=]:
    1. Let |inputSource| be a new {{XRInputSource}}.
    1. Add |inputSource| to |added|.
  1. [=Queue a task=] to perform the following steps:
    1. [=list/Extend=] |session|'s [=list of active XR input sources=] with |added|.
    1. Fire an {{XRInputSourcesChangeEvent}} named {{inputsourceschange!!event}} on |session| with {{XRInputSourcesChangeEvent/added}} set to |added|.

</div>

<div class="algorithm" data-algorithm="on-input-source-removed">

When any previously added <dfn for="XRSession" lt="remove input source">[=XR input source=]s are no longer available</dfn> for {{XRSession}} |session|, the user agent MUST run the following steps:

  1. Let |removed| be a new [=/list=].
  1. For each [=XR input source=] that is no longer available:
    1. Let |inputSource| be the {{XRInputSource}} in |session|'s [=list of active XR input sources=] associated with the [=XR input source=].
    1. Add |inputSource| to |removed|.
  1. [=Queue a task=] to perform the following steps:
    1. [=list/Remove=] each {{XRInputSource}} in |removed| from |session|'s [=list of active XR input sources=].
    1. Fire an {{XRInputSourcesChangeEvent}} named {{inputsourceschange!!event}} on |session| with {{XRInputSourcesChangeEvent/removed}} set to |removed|.

</div>

<div class="algorithm" data-algorithm="on-input-source-change">

When the <dfn for="XRSession" export lt="change input source">{{XRInputSource/handedness}}, {{XRInputSource/targetRayMode}}, {{XRInputSource/profiles}}, or presence of a {{XRInputSource/gripSpace}} for any [=XR input source=]s change</dfn> for {{XRSession}} |session|, the user agent MUST run the following steps:

  1. Let |added| be a new [=/list=].
  1. Let |removed| be a new [=/list=].
  1. For each changed [=XR input source=]:
    1. Let |oldInputSource| be the {{XRInputSource}} in |session|'s [=list of active XR input sources=] previously associated with the [=XR input source=].
    1. Let |newInputSource| be a new {{XRInputSource}}.
    1. Add |oldInputSource| to |removed|.
    1. Add |newInputSource| to |added|.
  1. [=Queue a task=] to perform the following steps:
    1. [=list/Remove=] each {{XRInputSource}} in |removed| from |session|'s [=list of active XR input sources=].
    1. [=list/Extend=] |session|'s [=list of active XR input sources=] with |added|.
    1. Fire an {{XRInputSourcesChangeEvent}} named {{inputsourceschange!!event}} on |session| with{{XRInputSourcesChangeEvent/added}} set to |added| and {{XRInputSourcesChangeEvent/removed}} set to |removed|.

</div>

Each {{XRSession}} has a <dfn for="XRSession">visibility state</dfn> value, which is an enum which MUST be set to whichever of the following values best matches the state of session.

  - A state of <dfn enum-value for="XRVisibilityState">visible</dfn> indicates that imagery rendered by the {{XRSession}} can be seen by the user and {{XRSession/requestAnimationFrame()}} callbacks are processed at the [=XRSession/XR device=]'s native refresh rate. Input is processed by the {{XRSession}} normally.

  - A state of <dfn enum-value for="XRVisibilityState">visible-blurred</dfn> indicates that imagery rendered by the {{XRSession}} may be seen by the user, but is not the primary focus. {{XRSession/requestAnimationFrame()}} callbacks MAY be [=throttling|throttled=]. Input is not processed by the {{XRSession}}.

  - A state of <dfn enum-value for="XRVisibilityState">hidden</dfn> indicates that imagery rendered by the {{XRSession}} cannot be seen by the user. {{XRSession/requestAnimationFrame()}} callbacks will not be processed until the [=visibility state=] changes. Input is not processed by the {{XRSession}}.

The <dfn attribute for="XRSession">visibilityState</dfn> attribute returns the {{XRSession}}'s [=visibility state=]. The <dfn attribute for="XRSession">onvisibilitychange</dfn> attribute is an [=Event handler IDL attribute=] for the {{visibilitychange}} event type.

The [=visibility state=] MAY be changed by the user agent at any time other than during the processing of an [=XR animation frame=], and the user agent SHOULD monitor the XR platform when possible to observe when session visibility has been affected external to the user agent and update the [=visibility state=] accordingly.

Note: The {{XRSession}}'s [=visibility state=] does not necessarily imply the visibility of the HTML document. Depending on the system configuration the page may continue to be visible while an [=immersive session=] is active. (For example, a headset connected to a PC may continue to display the page on the monitor while the headset is viewing content from an [=immersive session=].) Developers should continue to rely on the [Page Visibility API](https://w3c.github.io/page-visibility/) to determine page visibility.

Each {{XRSession}} has a <dfn for="XRSession">viewer reference space</dfn>, which is an {{XRReferenceSpace}} of type {{XRReferenceSpaceType/"viewer"}} with an [=identity transform=] [=XRSpace/origin offset=]. The [=XRSession/viewer reference space=] has a <dfn for="XRSession/viewer reference space">list of views</dfn>, which is a [=/list=] of [=view=]s corresponding to the views provided by the [=XRSession/XR device=]. If the {{XRSession}}'s {{XRSession/renderState}}'s [=XRRenderState/composition disabled=] boolean is set to <code>true</code> the [=list of views=] MUST contain a single [=view=].

The <dfn attribute for="XRSession">onend</dfn> attribute is an [=Event handler IDL attribute=] for the {{end}} event type.

The <dfn attribute for="XRSession">oninputsourceschange</dfn> attribute is an [=Event handler IDL attribute=] for the {{inputsourceschange}} event type.

The <dfn attribute for="XRSession">onselectstart</dfn> attribute is an [=Event handler IDL attribute=] for the {{selectstart}} event type.

The <dfn attribute for="XRSession">onselectend</dfn> attribute is an [=Event handler IDL attribute=] for the {{selectend}} event type.

The <dfn attribute for="XRSession">onselect</dfn> attribute is an [=Event handler IDL attribute=] for the {{XRSession/select}} event type.


The <dfn attribute for="XRSession">onsqueezestart</dfn> attribute is an [=Event handler IDL attribute=] for the {{squeezestart}} event type.

The <dfn attribute for="XRSession">onsqueezeend</dfn> attribute is an [=Event handler IDL attribute=] for the {{squeezeend}} event type.

The <dfn attribute for="XRSession">onsqueeze</dfn> attribute is an [=Event handler IDL attribute=] for the {{XRSession/squeeze}} event type.

XRRenderState {#xrrenderstate-interface}
-------------

An {{XRRenderState}} represents a set of configurable values which affect how an {{XRSession}}'s output is composited. The [=active render state=] for a given {{XRSession}} can only change between frame boundaries, and updates can be queued up via {{XRSession/updateRenderState()}}.

<pre class="idl">
dictionary XRRenderStateInit {
  double depthNear;
  double depthFar;
  double inlineVerticalFieldOfView;
  XRWebGLLayer? baseLayer;
};

[SecureContext, Exposed=Window] interface XRRenderState {
  readonly attribute double depthNear;
  readonly attribute double depthFar;
  readonly attribute double? inlineVerticalFieldOfView;
  readonly attribute XRWebGLLayer? baseLayer;
};
</pre>

Each {{XRRenderState}} has a <dfn for="XRRenderState">output canvas</dfn>, which is an {{HTMLCanvasElement}} initially set to <code>null</code>. The [=XRRenderState/output canvas=] is the DOM element that will display any content rendered for an {{XRSessionMode/"inline"}} {{XRSession}}.

Each {{XRRenderState}} also has <dfn for="XRRenderState">composition disabled</dfn> boolean, which is initially <code>false</code>. The {{XRRenderState}} is considered to be have [=XRRenderState/composition disabled=] if rendering commands performed for an {{XRSessionMode/"inline"}} {{XRSession}} are executed in such a way that they are directly displayed into [=XRRenderState/output canvas=], rather than first being processed by the [=XR Compositor=].

Note: At this point the {{XRRenderState}} will only have an [=XRRenderState/output canvas=] if it has [=XRRenderState/composition disabled=], but future versions of the specification are likely to introduce methods for setting [=XRRenderState/output canvas=]' that support more advanced uses like mirroring and layer compositing that will require composition.

<div class="algorithm" data-algorithm="initialize-renderstate">

When an {{XRRenderState}} object is created for an {{XRSession}} |session|, the user agent MUST <dfn>initialize the render state</dfn> by running the following steps:

  1. Let |state| be the newly created {{XRRenderState}} object.
  1. Initialize |state|'s {{XRRenderState/depthNear}} to <code>0.1</code>.
  1. Initialize |state|'s {{XRRenderState/depthFar}} to <code>1000.0</code>.
  1. Initialize |state|'s {{XRRenderState/inlineVerticalFieldOfView}} as follows:
    <dl class="switch">
      <dt> If |session| is an [=inline session=]
      <dd> Initialize |state|'s {{XRRenderState/inlineVerticalFieldOfView}} to <code>PI * 0.5</code>.
      <dt> Else
      <dd> Initialize |state|'s {{XRRenderState/inlineVerticalFieldOfView}} to <code>null</code>.
    </dl>
  1. Initialize |state|'s {{XRRenderState/baseLayer}} to <code>null</code>.

</div>

The <dfn attribute for="XRRenderState">depthNear</dfn> attribute defines the distance, in meters, of the near clip plane from the [=viewer=]. The <dfn attribute for="XRRenderState">depthFar</dfn> attribute defines the distance, in meters, of the far clip plane from the [=viewer=].

{{XRRenderState/depthNear}} and {{XRRenderState/depthFar}} are used in the computation of the {{XRView/projectionMatrix}} of {{XRView}}s. When the {{XRView/projectionMatrix}} is used during rendering, only geometry with a distance to the [=viewer=] that falls between {{XRRenderState/depthNear}} and {{XRRenderState/depthFar}} will be drawn. They also determine how the values of an {{XRWebGLLayer}} depth buffer are interpreted. {{XRRenderState/depthNear}} MAY be greater than {{XRRenderState/depthFar}}.

Note: Typically when constructing a perspective projection matrix for rendering the developer specifies the viewing frustum and the near and far clip planes. When displaying to an [=immersive XR device=] the correct viewing frustum is determined by some combination of the optics, displays, and cameras being used. The near and far clip planes, however, may be modified by the application since the appropriate values depend on the type of content being rendered.

The <dfn attribute for="XRRenderState">inlineVerticalFieldOfView</dfn> attribute defines the default vertical field of view in radians used when computing projection matrices for {{XRSessionMode/"inline"}} {{XRSession}}s. The projection matrix calculation also takes into account the aspect ratio of the [=XRRenderState/output canvas=]. This value MUST be <code>null</code> for [=immersive sessions=].

The <dfn attribute for="XRRenderState">baseLayer</dfn> attribute defines an {{XRWebGLLayer}} which the [=XR compositor=] will obtain images from.

Animation Frames {#animation-frames}
----------------

The primary way an {{XRSession}} provides information about the tracking state of the [=XRSession/XR device=] is via callbacks scheduled by calling {{requestAnimationFrame()}} on the {{XRSession}} instance.

<pre class="idl">
callback XRFrameRequestCallback = void (DOMHighResTimeStamp time, XRFrame frame);
</pre>

Each {{XRFrameRequestCallback}} object has a <dfn for="XRFrameRequestCallback">cancelled</dfn> boolean initially set to <code>false</code>.

Each {{XRSession}} has a <dfn>list of animation frame callbacks</dfn>, which is initially empty, and an <dfn>animation frame callback identifier</dfn>, which is a number which is initially zero.

<div class="algorithm" data-algorithm="request-animation-frame">

The <dfn method for="XRSession">requestAnimationFrame(|callback|)</dfn> method queues up |callback| for being run the next time the user agent wishes to run an animation frame for the device.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |session| be the target {{XRSession}} object.
  1. Increment |session|'s [=animation frame callback identifier=] by one.
  1. Append |callback| to |session|'s [=list of animation frame callbacks=], associated with |session|'s [=animation frame callback identifier=]’s current value.
  1. Return |session|'s [=animation frame callback identifier=]’s current value.

</div>

<div class="algorithm" data-algorithm="cancel-animation-frame">

The <dfn method for="XRSession">cancelAnimationFrame(|handle|)</dfn> method cancels an existing animation frame callback given its [=animation frame callback identifier=] |handle|.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |session| be the target {{XRSession}} object.
  1. Find the entry in |session|'s [=list of animation frame callbacks=] that is associated with the value |handle|.
  1. If there is such an entry, set its [=cancelled=] boolean to <code>true</code> and remove it from |session|'s [=list of animation frame callbacks=].

</div>

<div class="algorithm" data-algorithm="run-animation-frames">

When an {{XRSession}} |session| receives updated [=viewer=] state for timestamp |now| from the [=XRSession/XR device=], it runs an <dfn>XR animation frame</dfn>, which MUST run the following steps regardless of if the [=list of animation frame callbacks=] is empty or not:

  1. Let |frame| be a new {{XRFrame}} with [=XRFrame/time=] |now| and {{XRFrame/session}} |session|.
  1. If |session|'s [=pending render state=] is not <code>null</code>, [=apply the pending render state=].
  1. If |session|'s {{XRSession/renderState}}'s {{XRRenderState/baseLayer}} is <code>null</code>, abort these steps.
  1. If |session|'s  [=XRSession/mode=] is {{XRSessionMode/"inline"}} and |session|'s {{XRSession/renderState}}'s [=XRRenderState/output canvas=] is <code>null</code>, abort these steps.
  1. Let |callbacks| be a list of the entries in |session|'s [=list of animation frame callback=], in the order in which they were added to the list.
  1. Set |session|'s [=list of animation frame callbacks=] to the empty list.
  1. Set |frame|'s [=active=] boolean to <code>true</code>.
  1. Set |frame|'s [=animationFrame=] boolean to <code>true</code>.
  1. [=XRFrame/Apply frame updates=] for |frame|.
  1. For each entry in |callbacks|, in order:
    1. If the entry's [=cancelled=] boolean is <code>true</code>, continue to the next entry.
    1. [=Invoke the Web IDL callback function=], passing |now| and |frame| as the  arguments
    1. If an exception is thrown, [=report the exception=].
  1. Set |frame|'s [=active=] boolean to <code>false</code>.

</div>

The behavior of the {{Window}} interface's {{Window/requestAnimationFrame()}} method is not changed by the presence of any active {{XRSession}}, nor does calling {{requestAnimationFrame()}} on any {{XRSession}} interact with {{Window}}'s {{Window/requestAnimationFrame()}} in any way. An [=active immersive session=] MAY affect the [=rendering opportunity=] of a [=browsing context=] if it causes the page to be obscured.

<div class="example">
If an [=immersive session=] prevents [=rendering opportunity|rendering opportunities=] then callbacks supplied to {{Window}} {{Window/requestAnimationFrame()}} may not be processed while the session is active. This depends on the type of device being used and is most likely to happen depend on mobile or standalone devices where the immersive content completely obscures the HTML document. As such, developers must not rely on {{Window}} {{Window/requestAnimationFrame()}} callbacks to schedule {{XRSession}} {{XRSession/requestAnimationFrame()}} callbacks and visa-versa, even if they share the same rendering logic. Applications that do not follow this guidance may not execute properly on all platforms. A more effective pattern for applications that wish to transition between these two types of animation loops is demonstrated below:

<pre highlight="js">
let xrSession = null;

function onWindowAnimationFrame(time) {
  window.requestAnimationFrame(onWindowAnimationFrame);

  // This may be called while an immersive session is running on some devices,
  // such as a desktop with a tethered headset. To prevent two loops from
  // rendering in parallel, skip drawing in this one until the session ends.
  if (!xrSession) {
    renderFrame(time, null);
  }
}

// The window animation loop can be started immediately upon the page loading.
window.requestAnimationFrame(onWindowAnimationFrame);

function onXRAnimationFrame(time, xrFrame) {
  xrSession.requestAnimationFrame(onXRAnimationFrame);
  renderFrame(time, xrFrame);
}

function renderFrame(time, xrFrame) {
  // Shared rendering logic.
}

// Assumed to be called by a user gesture event elsewhere in code.
function startXRSession() {
  navigator.xr.requestSession('immersive-vr').then((session) => {
    xrSession = session;
    xrSession.addEventListener('end', onXRSessionEnded);
    // Do necessary session setup here.
    // Begin the session's animation loop.
    xrSession.requestAnimationFrame(onXRAnimationFrame);
  });
}

function onXRSessionEnded() {
  xrSession = null;
}
</pre>

Applications which use {{XRSessionMode/"inline"}} sessions for rendering to the HTML document do not need to take any special steps to coordinate the animation loops, since the user agent will automatically suspend the animation loops of any {{XRSessionMode/"inline"}} sessions while an [=immersive session=] is active.
</div>

The XR Compositor {#compositor}
-----------------

The user agent MUST maintain an <dfn>XR Compositor</dfn> which handles presentation to the [=XRSession/XR device=] and frame timing. The compositor MUST use an independent rendering context whose state is isolated from that of any graphics contexts created by the document. The compositor MUST prevent the page from corrupting the compositor state or reading back content from other pages or applications. The compositor MUST also run in separate thread or processes to decouple performance of the page from the ability to present new imagery to the user at the appropriate framerate. The compositor MAY composite additional device or user agent UI over rendered content, like device menus.

Note: Future extensions to this spec may utilize the compositor to composite multiple layers coming from the same page as well.

Frame Loop {#frame}
==========

XRFrame {#xrframe-interface}
-------

An {{XRFrame}} represents a snapshot of the state of all of the tracked objects for an {{XRSession}}. Applications can acquire an {{XRFrame}} by calling {{XRSession/requestAnimationFrame()}} on an {{XRSession}} with an {{XRFrameRequestCallback}}. When the callback is called it will be passed an {{XRFrame}}. Events which need to communicate tracking state, such as the {{select}} event, will also provide an {{XRFrame}}.

<pre class="idl">
[SecureContext, Exposed=Window] interface XRFrame {
  [SameObject] readonly attribute XRSession session;

  XRViewerPose? getViewerPose(XRReferenceSpace referenceSpace);
  XRPose? getPose(XRSpace space, XRSpace baseSpace);
};
</pre>

Each {{XRFrame}} has an <dfn for="XRFrame">active</dfn> boolean which is initially set to <code>false</code>, and an <dfn for="XRFrame">animationFrame</dfn> boolean which is initially set to <code>false</code>.

The <dfn attribute for="XRFrame">session</dfn> attribute returns the {{XRSession}} that produced the {{XRFrame}}.

Each {{XRFrame}} represents the state of all tracked objects for a given <dfn for="XRFrame">time</dfn>, and either stores or is able to query concrete information about this state at the [=XRFrame/time=].

<div class="algorithm" data-algorithm="get-viewer-pose">

The <dfn method for="XRFrame">getViewerPose(|referenceSpace|)</dfn> method provides the pose of the [=viewer=] relative to |referenceSpace| as an {{XRViewerPose}}, at the {{XRFrame}}'s [=XRFrame/time=].

When this method is invoked, the user agent MUST run the following steps:

  1. Let |frame| be the target {{XRFrame}}
  1. Let |session| be |frame|'s {{XRFrame/session}} object.
  1. If |frame|'s [=animationFrame=] boolean is <code>false</code>, throw an {{InvalidStateError}} and abort these steps.
  1. Let |pose| be a new {{XRViewerPose}} object.
  1. [=Populate the pose=] of |session|'s [=XRSession/viewer reference space=] in |referenceSpace| at the time represented by |frame| into |pose|.
  1. If |pose| is <code>null</code> return <code>null</code>.
  1. Let |xrviews| be an empty [=/list=].
  1. For each [=view=] |view| in the [=XRSession/viewer reference space/list of views=] on the[=XRSession/viewer reference space=] of {{XRFrame/session}}, perform the following steps:
      1. Let |xrview| be a new {{XRView}} object.
      1. Initialize |xrview|'s [=XRView/underlying view=] to |view|.
      1. Initialize |xrview|'s {{XRView/eye}} to |view|'s [=view/eye=].
      1. Initialize |xrview|'s [=XRView/frame=] to |frame|.
      1. Let |offset| be an {{XRRigidTransform}} equal to the [=view offset=] of |view|
      1. Set |xrview|'s {{XRView/transform}} property to the result of [=multiply transforms|multiplying=] the {{XRViewerPose}}'s {{XRPose/transform}} by the |offset| transform
      1. [=list/Append=] |xrview| to |xrviews|
  1. Set |pose|'s {{XRViewerPose/views}} to |xrviews|
  1. Return |pose|.

</div>

<div class="algorithm" data-algorithm="get-pose">

The <dfn method for="XRFrame">getPose(|space|, |baseSpace|)</dfn> method provides the pose of |space| relative to |baseSpace| as an {{XRPose}}, at the time represented by the {{XRFrame}}.

When this method is invoked, the user agent MUST run the following steps:

  1. Let |frame| be the target {{XRFrame}}
  1. Let |pose| be a new {{XRPose}} object.
  1. [=Populate the pose=] of |space| in |baseSpace| at the time represented by |frame| into |pose|.
  1. Return |pose|.

</div>

A <dfn>frame update</dfn> is an algorithm that can be run given an {{XRFrame}}, which is intended to be run each {{XRFrame}}.

Every {{XRSession}} has a <dfn for=XRSession>list of frame updates</dfn>, which is a [=/list=] of [=frame updates=], initially the empty [=/list=].

<div class="algorithm" data-algorithm="apply-frame-updates">

To <dfn for=XRFrame>apply frame updates</dfn> for an {{XRFrame}} |frame|, the user agent MUST run the following steps:

 1. For each |frame update| in |frame|'s {{XRFrame/session}}'s [=XRSession/list of frame updates=], perform the following steps:
    1. Run |frame update| with |frame|.

</div>

NOTE: This spec does not define any [=frame updates=], but other specifications may add some.

Spaces {#spaces}
======

A core feature of the WebXR Device API is the ability to provide spatial tracking. Spaces are the interface that enable applications to reason about how tracked entities are spatially related to the user's physical environment and each other.

XRSpace {#xrspace-interface}
-------

An {{XRSpace}} represents a virtual coordinate system with an origin that corresponds to a physical location. Spatial data that is requested from the API or given to the API is always expressed in relation to a specific {{XRSpace}} at the time of a specific {{XRFrame}}. Numeric values such as pose positions are coordinates in that space relative to its origin. The interface is intentionally opaque.

<pre class="idl">
[SecureContext, Exposed=Window] interface XRSpace : EventTarget {

};
</pre>

Each {{XRSpace}} has a <dfn for="XRSpace">session</dfn> which is set to the {{XRSession}} that created the {{XRSpace}}.

Each {{XRSpace}} has a <dfn for="XRSpace">native origin</dfn> that is tracked by the [=XRSession/XR device=]'s underlying tracking system, and an <dfn for="XRSpace">effective origin</dfn>, which is the basis of the {{XRSpace}}'s <dfn for="XRSpace">coordinate system</dfn>. The transform from the effective space to the [=native origin=]'s space is defined by an <dfn for="XRSpace">origin offset</dfn>, which is an {{XRRigidTransform}} initially set to an [=identity transform=].

The [=effective origin=] of an {{XRSpace}} can only be observed in the coordinate system of another {{XRSpace}} as an {{XRPose}}, returned by an {{XRFrame}}'s {{XRFrame/getPose()}} method. The spatial relationship between {{XRSpace}}s MAY change between {{XRFrame}}s.

<div class="algorithm" data-algorithm="populate-the-pose">

To <dfn>populate the pose</dfn> of an {{XRSpace}} |space| in an {{XRSpace}} |baseSpace| at the time represented by an {{XRFrame}} |frame| into an {{XRPose}} |pose|, the user agent MUST run the following steps:

  1. If |frame|'s [=active=] boolean is <code>false</code>, throw an {{InvalidStateError}} and abort these steps.
  1. Let |session| be |frame|'s {{XRFrame/session}} object.
  1. If |space|'s [=XRSpace/session=] does not equal |session|, throw an {{InvalidStateError}} and abort these steps.
  1. If |baseSpace|'s [=XRSpace/session=] does not equal |session|, throw an {{InvalidStateError}} and abort these steps.
  1. Check if [=poses may be reported=] and, if not, throw a {{SecurityError}} and abort these steps.
  1. Let |limit| be the result of whether [=poses must be limited=] between |space| and |baseSpace|.
  1. Let |transform| be |pose|'s {{XRPose/transform}}.
  1. Query the [=/XR device=]'s tracking system for |space|'s pose relative to |baseSpace| at the |frame|'s [=XRFrame/time=], then perform the following steps:
    <dl class="switch">
      <dt> If |limit| is <code>false</code> and the tracking system provides a [=6DoF=] pose whose position is actively tracked or statically known for |space|'s pose relative to |baseSpace|:
        <dd> Set |transform|'s {{XRRigidTransform/orientation}} to the orientation of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=].
        <dd> Set |transform|'s {{XRRigidTransform/position}} to the position of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=].
        <dd> Set |pose|'s {{XRPose/emulatedPosition}} to <code>false</code>.

      <dt> Else if |limit| is <code>false</code> and the tracking system provides a [=3DoF=] pose or a [=6DoF=] pose whose position is neither actively tracked nor statically known for |space|'s pose relative to |baseSpace|:
        <dd> Set |transform|'s {{XRRigidTransform/orientation}} to the orientation of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=].
        <dd> Set |transform|'s {{XRRigidTransform/position}} to the tracking system's best estimate of the position of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=]. This MAY include a computed offset such as a neck or arm model. If a position estimate is not available, the last known position MUST be used.
        <dd> Set |pose|'s {{XRPose/emulatedPosition}} to <code>true</code>.

      <dt> Else if |space|'s pose relative to |baseSpace| has been determined in the past:
        <dd> Set |transform|'s {{XRRigidTransform/position}} to the last known position of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=].
        <dd> Set |transform|'s {{XRRigidTransform/orientation}} to the last known orientation of |space|'s [=effective origin=] in |baseSpace|'s [=coordinate system=].
        <dd> Set |pose|'s {{XRPose/emulatedPosition}} boolean to <code>true</code>.
      
      <dt> Else if |space|'s pose relative to |baseSpace| has never been determined:
        <dd> Set |pose| to <code>null</code>.
    </dl>

Note: The {{XRPose}}'s {{XRPose/emulatedPosition}} boolean does not indicate whether |baseSpace|'s position is emulated or not, only whether evaluating |space|'s position relative to |baseSpace| relies on emulation. For example, a controller with [=3DoF=] tracking would report poses with an {{XRPose/emulatedPosition}} of <code>true</code> when its {{targetRaySpace}} or {{gripSpace}} are queried against an {{XRReferenceSpace}}, but would report an {{XRPose/emulatedPosition}} of <code>false</code> if the pose of the {{targetRaySpace}} was queried in {{gripSpace}}, because the relationship between those two spaces should be known exactly.

</div>

XRReferenceSpace {#xrreferencespace-interface}
----------------

An {{XRReferenceSpace}} is one of several common {{XRSpace}}s that applications can use to establish a spatial relationship with the user's physical environment.

{{XRReferenceSpace}}s are generally expected to remain static for the duration of the {{XRSession}}, with the most common exception being mid-session reconfiguration by the user. The [=native origin=] for every {{XRReferenceSpace}} describes a coordinate system where <code>+X</code> is considered "Right", <code>+Y</code> is considered "Up", and <code>-Z</code> is considered "Forward".

<pre class="idl">
enum XRReferenceSpaceType {
  "viewer",
  "local",
  "local-floor",
  "bounded-floor",
  "unbounded"
};

[SecureContext, Exposed=Window]
interface XRReferenceSpace : XRSpace {
  [NewObject] XRReferenceSpace getOffsetReferenceSpace(XRRigidTransform originOffset);

  attribute EventHandler onreset;
};
</pre>

Each {{XRReferenceSpace}} has a <dfn for="XRReferenceSpace">type</dfn>, which is an {{XRReferenceSpaceType}}.

An {{XRReferenceSpace}} is most frequently obtained by calling {{XRSession/requestReferenceSpace()}}, which creates an instance of an {{XRReferenceSpace}} (or an interface extending it) if the {{XRReferenceSpaceType}} enum value passed into the call [=reference space is supported|is supported=]. The type indicates the tracking behavior that the reference space will exhibit:

  - Passing a type of <dfn enum-value for="XRReferenceSpaceType">viewer</dfn> creates an {{XRReferenceSpace}} instance. It represents a tracking space with a [=native origin=] which tracks the position and orientation of the [=viewer=]. Every {{XRSession}} MUST support {{XRReferenceSpaceType/"viewer"}} {{XRReferenceSpace}}s.

  - Passing a type of <dfn enum-value for="XRReferenceSpaceType">local</dfn> creates an {{XRReferenceSpace}} instance. It represents a tracking space with a [=native origin=] near the viewer at the time of creation. The exact position and orientation will be initialized based on the conventions of the underlying platform. When using this reference space the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with [=6DoF=] tracking, {{local}} reference spaces should emphasize keeping the origin stable relative to the user's environment.

  - Passing a type of <dfn enum-value for="XRReferenceSpaceType">local-floor</dfn> creates an {{XRReferenceSpace}} instance. It represents a tracking space with a [=native origin=] at the floor in a safe position for the user to stand. The <code>y</code> axis equals <code>0</code> at floor level, with the <code>x</code> and <code>z</code> position and orientation initialized based on the conventions of the underlying platform. If the floor level isn't known it MUST be estimated, with some <dfn>estimated floor level</dfn>. If the [=estimated floor level=] is determined with a non-default value, it MUST be [=rounding|rounded=] sufficiently to prevent fingerprinting. When using this reference space the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with [=6DoF=] tracking, {{local-floor}} reference spaces should emphasize keeping the origin stable relative to the user's environment.

    Note: If the floor level of a {{XRReferenceSpaceType/"local-floor"}} reference space is adjusted to prevent fingerprinting, [=rounding|rounded=] to the nearest 1cm is suggested.

  - Passing a type of <dfn enum-value for="XRReferenceSpaceType">bounded-floor</dfn> creates an {{XRBoundedReferenceSpace}} instance. It represents a tracking space with its [=native origin=] at the floor, where the user is expected to move within a pre-established boundary, given as the {{boundsGeometry}}. Tracking in a {{bounded-floor}} reference space is optimized for keeping the [=native origin=] and {{boundsGeometry}} stable relative to the user's environment.

  - Passing a type of <dfn enum-value for="XRReferenceSpaceType">unbounded</dfn> creates an {{XRReferenceSpace}} instance. It represents a tracking space where the user is expected to move freely around their environment, potentially even long distances from their starting point. Tracking in an {{unbounded}} reference space is optimized for stability around the user's current position, and as such the [=native origin=] may drift over time.

Devices that support {{XRReferenceSpaceType/"local"}} reference spaces MUST support {{XRReferenceSpaceType/"local-floor"}} reference spaces, through emulation if necessary, and vice versa.

The <dfn attribute for="XRReferenceSpace">onreset</dfn> attribute is an [=Event handler IDL attribute=] for the {{reset}} event type.

<div class="algorithm" data-algorithm="create-reference-space">

When an {{XRReferenceSpace}} is requested, the user agent MUST <dfn>create a reference space</dfn> by running the following steps:

  1. Let |session| be the {{XRSession}} object that requested creation of a reference space.
  1. Let |type| be set to the {{XRReferenceSpaceType}} passed to {{requestReferenceSpace()}}.
  1. If the [=reference space is supported=] for |type| and |session|, run the following steps:
    1. Initialize |referenceSpace| as follows:
        <dl class="switch">
          <dt> If |type| is {{bounded-floor}}
          <dd> Let |referenceSpace| be a new {{XRBoundedReferenceSpace}}.
          <dt> Otherwise
          <dd> Let |referenceSpace| be a new {{XRReferenceSpace}}.
        </dl>
    1. Initialize |referenceSpace|'s [=XRReferenceSpace/type=] to |type|.
    1. Initialize |referenceSpace|'s [=XRSpace/session=] to |session|.
    1. Return |referenceSpace|
  1. Return <code>null</code>.

</div>

<div class="algorithm" data-algorithm="reference-space-supported">
To check if a <dfn>reference space is supported</dfn> for a given reference space type |type| and {{XRSession}} |session|, run the following steps:

  1. If |type| is not [=list/contain|contained=] in |session|'s [=list of enabled features=] return <code>false</code>.
  1. If |type| is {{viewer}}, return <code>true</code>.
  1. If |type| is {{local}} or {{local-floor}}, and |session| is an [=immersive session=], return <code>true</code>.
  1. If |type| is {{local}} or {{local-floor}}, and the [=XRSession/XR device=] supports reporting orientation data, return <code>true</code>.
  1. If |type| is {{bounded-floor}} and |session| is an [=immersive session=], return the result of whether [=bounded reference spaces are supported=] by the [=XRSession/XR device=].
  1. If |type| is {{unbounded}}, |session| is an [=immersive session=], and the [=XRSession/XR device=] supports stable tracking near the user over an unlimited distance, return <code>true</code>.
  1. Return <code>false</code>.

</div>

<div class="algorithm" data-algorithm="get-offset-space">
The <dfn method for="XRReferenceSpace">getOffsetReferenceSpace(|originOffset|)</dfn> method MUST perform the following steps when invoked:

  1. Let |base| be the {{XRReferenceSpace}} the method was called on.
  1. Initialize |offsetSpace| as follows:
    <dl class="switch">
      <dt> If |base| is an instance of {{XRBoundedReferenceSpace}}
      <dd> Let |offsetSpace| be a new {{XRBoundedReferenceSpace}} and set |offsetSpace|'s {{boundsGeometry}} to |base|'s {{boundsGeometry}}, with each point multiplied by the {{XRRigidTransform/inverse}} of |originOffset|.
      <dt> Else
      <dd> Let |offsetSpace| be a new {{XRReferenceSpace}}.
    </dl>
  1. Set |offsetSpace|'s [=native origin=] to |base|'s [=native origin=].
  1. Set |offsetSpace|'s [=origin offset=] to the result of [=multiply transforms|multiplying=] |base|'s [=origin offset=] by |originOffset|.
  1. Return |offsetSpace|.

</div>

Note: It's expected that some applications will use {{getOffsetReferenceSpace()}} to implement scene navigation controls based on mouse, keyboard, touch, or gamepad input. This will result in {{getOffsetReferenceSpace()}} being called frequently, at least once per-frame during periods of active input. As a result UAs are strongly encouraged to make the creation of new {{XRReferenceSpace}}s with {{getOffsetReferenceSpace()}} a lightweight operation.

XRBoundedReferenceSpace {#xrboundedreferencespace-interface}
-----------------------

{{XRBoundedReferenceSpace}} extends {{XRReferenceSpace}} to include {{boundsGeometry}}, indicating the pre-configured boundaries of the users space.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRBoundedReferenceSpace : XRReferenceSpace {
  readonly attribute FrozenArray&lt;DOMPointReadOnly&gt; boundsGeometry;
};
</pre>

The origin of an {{XRBoundedReferenceSpace}} MUST be positioned at the floor, such that the <code>y</code> axis equals <code>0</code> at floor level. The <code>x</code> and <code>z</code> position and orientation are initialized based on the conventions of the underlying platform, typically expected to be near the center of the room facing in a logical forward direction.

Note: Other XR platforms sometimes refer to the type of tracking offered by a {{bounded-floor}} reference space as "room scale" tracking. An {{XRBoundedReferenceSpace}} is not intended to describe multi-room spaces, areas with uneven floor levels, or very large open areas. Content that needs to handle those scenarios should use an {{unbounded}} reference space.

Each {{XRBoundedReferenceSpace}} has a <dfn for="XRBoundedReferenceSpace">native bounds geometry</dfn> describing the border around the {{XRBoundedReferenceSpace}}, which the user can expect to safely move within. The polygonal boundary is given as an array of {{DOMPointReadOnly}}s, which represents a loop of points at the edges of the safe space. The points describe offsets from the [=XRSpace/native origin=] in meters. Points MUST be given in a clockwise order as viewed from above, looking towards the negative end of the Y axis. The {{DOMPointReadOnly/y}} value of each point MUST be <code>0</code> and the {{DOMPointReadOnly/w}} value of each point MUST be <code>1</code>. The bounds can be considered to originate at the floor and extend infinitely high. The shape it describes MAY be convex or concave.

Each point in the [=native bounds geometry=] MUST be [=limiting|limited=] to a reasonable distance from the reference space's [=native origin=].

Note: It is suggested that points of the [=native bounds geometry=] be [=limiting|limited=] to 15 meters from the [=XRSpace/native origin=] in all directions.

Each point in the [=native bounds geometry=] MUST also be [=quantization|quantized=] sufficiently to prevent fingerprinting.  For user's safety, quantized points values MUST NOT fall outside the bounds reported by the platform.

Note: It is suggested that points of the [=native bounds geometry=] be [=quantization|quantized=] to the nearest 5cm.

The <dfn attribute for="XRBoundedReferenceSpace">boundsGeometry</dfn> attribute is an array of {{DOMPointReadOnly}}s such that each entry is equal to the entry in the {{XRBoundedReferenceSpace}}'s [=XRBoundedReferenceSpace/native bounds geometry=] premultiplied by the {{XRRigidTransform/inverse}} of the [=XRSpace/origin offset=]. In other words, it provides the same border in {{XRBoundedReferenceSpace}} coordinates relative to the [=XRSpace/effective origin=].


<div class="algorithm" data-algorithm="bounded-space-supported">
To check if <dfn>bounded reference spaces are supported</dfn> run the following steps:
    1. If the [=XRSession/XR device=] cannot report boundaries, return false.
    1. If the [=XRSession/XR device=] cannot identify the height of the user's physical floor, return false.
    1. Return true.
</div>


Note: Content should not require the user to move beyond the {{boundsGeometry}}. It is possible for the user to move beyond the bounds if their physical surroundings allow for it, resulting in position values outside of the polygon they describe. This is not an error condition and should be handled gracefully by page content.

Note: Content generally should not provide a visualization of the {{boundsGeometry}}, as it's the user agent's responsibility to ensure that safety critical information is provided to the user.

Views {#views}
=====

XRView {#xrview-interface}
------

An {{XRView}} describes a single <dfn>view</dfn> into an XR scene for a given frame.

Each [=view=] corresponds to a display or portion of a display used by an XR device to present imagery to the user. They are used to retrieve all the information necessary to render content that is well aligned to the [=view=]'s physical output properties, including the field of view, eye offset, and other optical properties. [=Views=] may cover overlapping regions of the user's vision. No guarantee is made about the number of [=views=] any XR device uses or their order, nor is the number of [=views=] required to be constant for the duration of an {{XRSession}}.

A [=view=] has an associated internal <dfn>view offset</dfn>, which is an {{XRRigidTransform}} describing the position and orientation of the [=view=] in the [=XRSession/viewer reference space=]'s [=coordinate system=].

A [=view=] has an associated <dfn for="view">projection matrix</dfn> which is a [=matrix=] describing the projection to be used when rendering the [=view=], provided by the underlying XR device. The [=view/projection matrix=] MAY include transformations such as shearing that prevent the projection from being accurately described by a simple frustum.

A [=view=] has an associated <dfn for="view">eye</dfn> which is an {{XREye}} describing which eye this view is expected to be shown to. If the view does not have an intrinsically associated eye (the display is monoscopic, for example) this value MUST be set to {{XREye/"none"}}.

Note: Many HMDs will request that content render two [=views=], one for the left eye and one for the right, while most magic window devices will only request one [=view=], but applications should never assume a specific view configuration. For example: A magic window device may request two views if it is capable of stereo output, but may revert to requesting a single view for performance reasons if the stereo output mode is turned off. Similarly, HMDs may request more than two views to facilitate a wide field of view or displays of different pixel density.

<pre class="idl">
enum XREye {
  "none",
  "left",
  "right"
};

[SecureContext, Exposed=Window] interface XRView {
  readonly attribute XREye eye;
  readonly attribute Float32Array projectionMatrix;
  [SameObject] readonly attribute XRRigidTransform transform;
};
</pre>

The <dfn attribute for="XRView">eye</dfn> attribute describes is the [=view/eye=] of the underlying [=view=]. This attribute's primary purpose is to ensure that pre-rendered stereo content can present the correct portion of the content to the correct eye.

The <dfn attribute for="XRView">projectionMatrix</dfn> attribute is the [=view/projection matrix=] of the underlying [=view=]. It is <b>strongly recommended</b> that applications use this matrix without modification or decomposition. Failure to use the provided projection matrices when rendering may cause the presented frame to be distorted or badly aligned, resulting in varying degrees of user discomfort. This attribute MUST be computed by [=XRView/obtain the projection matrix|obtaining the projection matrix=] for the {{XRView}}.

The <dfn attribute for="XRView">transform</dfn> attribute is the {{XRRigidTransform}} of the viewpoint. It represents the position and orientation of the viewpoint in the {{XRReferenceSpace}} provided in {{XRFrame/getViewerPose()}}.

Each {{XRView}} has an associated <dfn for="XRView">frame</dfn> which is the {{XRFrame}} that produced it.

Each {{XRView}} has an associated <dfn for="XRView">underlying view</dfn> which is the underlying [=view=] that it represents.

Each {{XRView}} has an associated <dfn for="XRView">internal projection matrix</dfn> which stores the [=view/projection matrix=] of its [=XRView/underlying view=]. It is initially <code>null</code>.

Note: The {{XRView/transform}} can be used to position camera objects in many rendering libraries. If a more traditional view matrix is needed by the application one can be retrieved by calling <code>view.transform.inverse.matrix</code>.


<div class=algorithm data-algorithm="obtain-xrview-projection">

To <dfn for=XRView>obtain the projection matrix</dfn> for a given {{XRView}} |view|

  1. If |view|'s [=XRView/internal projection matrix=] is not <code>null</code>, perform the following steps:
    1. If the operation {{IsDetachedBuffer}} on [=XRView/internal projection matrix=]  is <code>false</code>, return |view|'s [=XRView/internal projection matrix=].
  1. Set |view|'s [=XRView/internal projection matrix=] to a new [=matrix=] which is equal to |view|'s [=XRView/underlying view=]'s [=view/projection matrix=].
  1. Return |view|'s [=XRView/internal projection matrix=].

</div>


XRViewport {#xrviewport-interface}
----------

An {{XRViewport}} object describes a viewport, or rectangular region, of a graphics surface.

<pre class="idl">
[SecureContext, Exposed=Window] interface XRViewport {
  readonly attribute long x;
  readonly attribute long y;
  readonly attribute long width;
  readonly attribute long height;
};
</pre>

The <dfn attribute for="XRViewport">x</dfn> and <dfn attribute for="XRViewport">y</dfn> attributes define an offset from the surface origin and the <dfn attribute for="XRViewport">width</dfn> and <dfn attribute for="XRViewport">height</dfn> attributes define the rectangular dimensions of the viewport.

The exact interpretation of the viewport values depends on the conventions of the graphics API the viewport is associated with:

 - When used with an {{XRWebGLLayer}} the {{XRViewport/x}} and {{XRViewport/y}} attributes specify the lower left corner of the viewport rectangle, in pixels, with the viewport rectangle extending {{XRViewport/width}} pixels to the right of {{XRViewport/x}} and {{XRViewport/height}} pixels above {{XRViewport/y}}. The values can be passed to the [=WebGL viewport=] function directly.

<div class="example">
The following code loops through all of the {{XRView}}s of an {{XRViewerPose}}, queries an {{XRViewport}} from an {{XRWebGLLayer}} for each, and uses them to set the appropriate [=WebGL viewport=]s for rendering.

<pre highlight="js">
xrSession.requestAnimationFrame((time, xrFrame) => {
  let viewer = xrFrame.getViewerPose(xrReferenceSpace);

  gl.bindFramebuffer(xrWebGLLayer.framebuffer);
  for (xrView of viewer.views) {
    let xrViewport = xrWebGLLayer.getViewport(xrView);
    gl.viewport(xrViewport.x, xrViewport.y, xrViewport.width, xrViewport.height);

    // WebGL draw calls will now be rendered into the appropriate viewport.
  }
});
</pre>
</div>

Geometric Primitives {#geometricprimitives}
====================

Matrices {#matrices}
--------

WebXR provides various transforms in the form of <dfn lt="matrix">matrices</dfn>. WebXR uses the WebGL conventions when communicating matrices, in which 4x4 matrices are given as 16 element {{Float32Array}}s with column major storage, and are applied to column vectors by premultiplying the matrix from the left. They may be passed directly to WebGL's {{uniformMatrix4fv}} function, used to create an equivalent {{DOMMatrix}}, or used with a variety of third party math libraries.

<div class="example">
Matrices returned from the WebXR Device API will be a 16 element {{Float32Array}} laid out like so:
<pre>
[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15]
</pre>

Applying this matrix as a transform to a column vector specified as a {{DOMPointReadOnly}} like so:
<pre>{x:X, y:Y, z:Z, w:1}</pre>

Produces the following result:
<pre>
a0 a4 a8  a12  *  X  =  a0 * X + a4 * Y +  a8 * Z + a12
a1 a5 a9  a13     Y     a1 * X + a5 * Y +  a9 * Z + a13
a2 a6 a10 a14     Z     a2 * X + a6 * Y + a10 * Z + a14
a3 a7 a11 a15     1     a3 * X + a7 * Y + a11 * Z + a15
</pre>
</div>

Normalization {#normalization}
-------------

There are several algorithms which call for a vector or quaternion to be normalized, which means to scale the components to have a collective magnitude of <code>1.0</code>.

<div class="algorithm" data-algorithm="normalize">

To <dfn>normalize</dfn> a list of components the UA MUST perform the following steps:

  1. Let |length| be the square root of the sum of the squares of each component.
  1. If |length| is <code>0</code>, throw an {{InvalidStateError}}  and abort these steps.
  1. Divide each component by |length| and set the component.

</div>

XRRigidTransform {#xrrigidtransform-interface}
----------------

An {{XRRigidTransform}} is a transform described by a {{XRRigidTransform/position}} and {{XRRigidTransform/orientation}}. When interpreting an {{XRRigidTransform}} the {{XRRigidTransform/orientation}} is always applied prior to the {{XRRigidTransform/position}}.

An {{XRRigidTransform}} contains an <dfn for=XRRigidTransform>internal matrix</dfn> which is a [=/matrix=].

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRRigidTransform {
  constructor(optional DOMPointInit position = {}, optional DOMPointInit orientation = {});
  [SameObject] readonly attribute DOMPointReadOnly position;
  [SameObject] readonly attribute DOMPointReadOnly orientation;
  readonly attribute Float32Array matrix;
  [SameObject] readonly attribute XRRigidTransform inverse;
};
</pre>

<div class="algorithm" data-algorithm="construct-rigid-transform">

The <dfn constructor for="XRRigidTransform">XRRigidTransform(|position|, |orientation|)</dfn> constructor MUST perform the following steps when invoked:

  1. Let |transform| be a new {{XRRigidTransform}}.
  1. If |position| is not a {{DOMPointInit}} initialize |transform|'s {{XRRigidTransform/position}} to <code>{ x: 0.0, y: 0.0, z: 0.0, w: 1.0 }</code>.
  1. If |position|'s {{DOMPointReadOnly/w}} value is not 1.0, throw a {{TypeError}}.
  1. Initialize |transform|'s {{XRRigidTransform/position}}’s {{DOMPointReadOnly/x}} value to |position|'s x dictionary member, {{DOMPointReadOnly/y}} value to |position|'s y dictionary member, {{DOMPointReadOnly/z}} value to |position|'s z dictionary member and {{DOMPointReadOnly/w}} to <code>1.0</code>.
  1. Initialize |transform|'s {{XRRigidTransform/orientation}} as follows:
    <dl class="switch">
      <dt> If |orientation| is not a {{DOMPointInit}}
      <dd> Initialize |transform|'s {{XRRigidTransform/orientation}} to <code>{ x: 0.0, y: 0.0, z: 0.0, w: 1.0 }</code>.
      <dt> Else
      <dd> Initialize |transform|'s {{XRRigidTransform/orientation}}’s {{DOMPointReadOnly/x}} value to |orientation|'s x dictionary member, {{DOMPointReadOnly/y}} value to |orientation|'s y dictionary member, {{DOMPointReadOnly/z}} value to |orientation|'s z dictionary member and {{DOMPointReadOnly/w}} value to |orientation|'s w dictionary member.
    </dl>
  1. Initialize |transform|'s [=XRRigidTransform/internal matrix=] to <code>null</code>.
  1. [=Normalize=] {{DOMPointReadOnly/x}}, {{DOMPointReadOnly/y}}, {{DOMPointReadOnly/z}}, and {{DOMPointReadOnly/w}} components of |transform|'s {{XRRigidTransform/orientation}}.
  1. Return |transform|.

</div>

The <dfn attribute for="XRRigidTransform">position</dfn> attribute is a 3-dimensional point, given in meters, describing the translation component of the transform. The {{XRRigidTransform/position}}'s {{DOMPointReadOnly/w}} attribute MUST be <code>1.0</code>.

The <dfn attribute for="XRRigidTransform">orientation</dfn> attribute is a quaternion describing the rotational component of the transform. The {{XRRigidTransform/orientation}} MUST be normalized to have a length of <code>1.0</code>.

The <dfn attribute for="XRRigidTransform">matrix</dfn> attribute returns the transform described by the {{XRRigidTransform/position}} and {{XRRigidTransform/orientation}} attributes as a [=matrix=]. This attribute MUST be computed by [=XRRigidTransform/obtain the matrix|obtaining the matrix=] for the {{XRRigidTransform}}.

Note: This matrix when premultiplied onto a column vector will rotate the vector by the 3D rotation described by {{XRRigidTransform/orientation}}, and then translate it by {{XRRigidTransform/position}}. Mathematically in column-vector notation, this is <code>M = T * R</code>, where <code>T</code> is a translation matrix corresponding to {{XRRigidTransform/position}} and  <code>R</code> is a rotation matrix corresponding to {{XRRigidTransform/orientation}}.

<div class=algorithm data-algorithm="obtain-xrrigidtransform-matrix">

To <dfn for=XRRigidTransform>obtain the matrix</dfn> for a given {{XRRigidTransform}} |transform|

  1. If |transform|'s [=XRRigidTransform/internal matrix=] is not <code>null</code>, perform the following steps:
    1. If the operation {{IsDetachedBuffer}} on [=XRRigidTransform/internal matrix=] is <code>false</code>, return |transform|'s [=XRRigidTransform/internal matrix=].
  1. Let |translation| be a new [=matrix=] which is a column-vector translation matrix corresponding to {{XRRigidTransform/position}}. Mathematically, if {{XRRigidTransform/position}} is <code>(x, y, z)</code>, this matrix is

        <img src="images/translation_matrix.svg" alt="Mathematical expression for column-vector translation matrix" />
  1. Let |rotation| be a new [=matrix=] which is a column-vector rotation matrix corresponding to {{XRRigidTransform/orientation}}. Mathematically, if {{XRRigidTransform/orientation}} is the unit quaternion <code>(q<sub>x</sub>, q<sub>y</sub>, q<sub>z</sub>, q<sub>w</sub>)</code>, this matrix is
 
        <img src="images/rotation_matrix.svg" alt="Mathematical expression for column-vector rotation matrix" />
  1. Set |transform|'s [=XRRigidTransform/internal matrix=] to a new [=matrix=] set to the result of multiplying |translation| and |rotation| with |translation| on the left (<code>translation * rotation</code>). Mathematically, this matrix is

       <img src="images/rigid_matrix.svg" alt="Mathematical expression for matrix of multiplying translation and rotation with translation on the left" />
  1. Return |transform|'s [=XRRigidTransform/internal matrix=].

</div>

The <dfn attribute for="XRRigidTransform">inverse</dfn> attribute returns an {{XRRigidTransform}} which, if applied to an object that had previously been transformed by the original {{XRRigidTransform}}, would undo the transform and return the object to its initial pose. This attribute SHOULD be lazily evaluated. The {{XRRigidTransform}} returned by {{inverse}} MUST return the originating {{XRRigidTransform}} as its {{inverse}}.

An {{XRRigidTransform}} with a {{XRRigidTransform/position}} of <code>{ x: 0, y: 0, z: 0 w: 1 }</code> and an {{XRRigidTransform/orientation}} of <code>{ x: 0, y: 0, z: 0, w: 1 }</code> is known as an <dfn>identity transform</dfn>.

<div class="algorithm" data-algorithm="multiply transforms">

To <dfn lt="multiply transforms">multiply two {{XRRigidTransform}}s</dfn>, |B| and |A|, the UA MUST perform the following steps:

  1. Let |result| be a new {{XRRigidTransform}} object.
  1. Set |result|'s {{XRRigidTransform/matrix}} to the result of premultiplying |B|'s {{XRRigidTransform/matrix}} from the left onto |A|'s {{XRRigidTransform/matrix}}.
  1. Set |result|'s {{XRRigidTransform/orientation}} to the quaternion that describes the rotation indicated by the top left 3x3 sub-matrix of |result|'s {{XRRigidTransform/matrix}}.
  1. Set |result|'s {{XRRigidTransform/position}} to the vector given by the fourth column of |result|'s {{XRRigidTransform/matrix}}.
  1. Return |result|.

|result| is a transform from |A|'s source space to |B|'s destination space.

Note: This is equivalent to constructing an {{XRRigidTransform}} whose {{XRRigidTransform/orientation}} is the composition of the orientation of |A| and |B|, and whose {{XRRigidTransform/position}} is equal to |A|'s {{XRRigidTransform/position}} rotated by |B|'s {{XRRigidTransform/orientation}}, added to |B|'s {{XRRigidTransform/position}}.
</div>

Pose {#pose}
====

XRPose {#xrpose-interface}
------

An {{XRPose}} describes a position and orientation in space relative to an {{XRSpace}}.

<pre class="idl">
[SecureContext, Exposed=Window] interface XRPose {
  [SameObject] readonly attribute XRRigidTransform transform;
  readonly attribute boolean emulatedPosition;
};
</pre>

The <dfn attribute for="XRPose">transform</dfn> attribute describes the position and orientation relative to the base {{XRSpace}}.

The <dfn attribute for="XRPose">emulatedPosition</dfn> attribute is <code>false</code> when the {{XRPose/transform}} represents an actively tracked [=6DoF=] pose based on sensor readings, or <code>true</code> if its {{XRRigidTransform/position}} value includes a <dfn for="XRPose">computed offset</dfn>, such as that provided by a neck or arm model. [=Estimated floor level=]s MUST NOT be considered when determining if an {{XRPose}} includes a [=XRPose/computed offset=].

XRViewerPose {#xrviewerpose-interface}
------------

An {{XRViewerPose}} is an {{XRPose}} describing the state of a <dfn>viewer</dfn> of the XR scene as tracked by the [=XRSession/XR device=]. A [=viewer=] may represent a tracked piece of hardware, the observed position of a users head relative to the hardware, or some other means of computing a series of viewpoints into the XR scene. {{XRViewerPose}}s can only be queried relative to an {{XRReferenceSpace}}. It provides, in addition to the {{XRPose}} values, an array of [=view=]s which include rigid transforms to indicate the viewpoint and projection matrices. These values should be used by the application when rendering a frame of an XR scene.

<pre class="idl">
[SecureContext, Exposed=Window] interface XRViewerPose : XRPose {
  [SameObject] readonly attribute FrozenArray&lt;XRView&gt; views;
};
</pre>

The <dfn attribute for="XRViewerPose">views</dfn> array is a sequence of {{XRView}}s describing the viewpoints of the XR scene, relative to the {{XRReferenceSpace}} the {{XRViewerPose}} was queried with. Every [=view=] of the XR scene in the array must be rendered in order to display correctly on the [=XRSession/XR device=]. Each {{XRView}} includes rigid transforms to indicate the viewpoint and projection matrices, and can be used to query {{XRViewport}}s from layers when needed.

Note: The {{XRViewerPose}}'s {{XRPose/transform}} can be used to position graphical representations of the [=viewer=] for spectator views of the scene or multi-user interaction.

Input {#input}
=====

XRInputSource {#xrinputsource-interface}
-------------

An {{XRInputSource}} represents an <dfn>XR input source</dfn>, which is any input mechanism which allows the user to perform targeted actions in the same virtual space as the [=viewer=]. Example [=XR input source=]s include, but are not limited to, handheld controllers, optically tracked hands, and gaze-based input methods that operate on the [=viewer=]'s pose. Input mechanisms which are not explicitly associated with the [=/XR device=], such as traditional gamepads, mice, or keyboards SHOULD NOT be considered [=XR input source=]s.

<pre class="idl">
enum XRHandedness {
  "none",
  "left",
  "right"
};

enum XRTargetRayMode {
  "gaze",
  "tracked-pointer",
  "screen"
};

[SecureContext, Exposed=Window]
interface XRInputSource {
  readonly attribute XRHandedness handedness;
  readonly attribute XRTargetRayMode targetRayMode;
  [SameObject] readonly attribute XRSpace targetRaySpace;
  [SameObject] readonly attribute XRSpace? gripSpace;
  [SameObject] readonly attribute FrozenArray&lt;DOMString&gt; profiles;
};
</pre>

Note: The {{XRInputSource}} interface is also extended by the <a href="https://immersive-web.github.io/webxr-gamepads-module/">WebXR Gamepads Module</a>

The <dfn attribute for="XRInputSource">handedness</dfn> attribute describes which hand the [=XR input source=] is associated with, if any. Input sources with no natural handedness (such as headset-mounted controls) or for which the handedness is not currently known MUST set this attribute {{XRHandedness/"none"}}.

The <dfn attribute for="XRInputSource">targetRayMode</dfn> attribute describes the method used to produce the target ray, and indicates how the application should present the target ray to the user if desired.

  - <dfn enum-value for="XRTargetRayMode">gaze</dfn> indicates the target ray will originate at the viewer and follow the direction it is facing. (This is commonly referred to as a "gaze input" device in the context of head-mounted displays.)
  - <dfn enum-value for="XRTargetRayMode">tracked-pointer</dfn> indicates that the target ray originates from either a handheld device or other hand-tracking mechanism and represents that the user is using their hands or the held device for pointing. The orientation of the target ray relative to the tracked object MUST follow platform-specific ergonomics guidelines when available. In the absence of platform-specific guidance, the target ray SHOULD point in the same direction as the user's index finger if it was outstretched.
  - <dfn enum-value for="XRTargetRayMode">screen</dfn> indicates that the input source was an interaction with the canvas element associated with an inline session's output context, such as a mouse click or touch event.

The <dfn attribute for="XRInputSource">targetRaySpace</dfn> attribute is an {{XRSpace}} that has a [=native origin=] tracking the position and orientation of the preferred pointing ray of the {{XRInputSource}}, as defined by the {{targetRayMode}}.

The <dfn attribute for="XRInputSource">gripSpace</dfn> attribute is an {{XRSpace}} that has a [=native origin=] tracking to the pose that should be used to render virtual objects such that they appear to be held in the user's hand. If the user were to hold a straight rod, this {{XRSpace}} places the [=native origin=] at the centroid of their curled fingers and where the <code>-Z</code> axis points along the length of the rod towards their thumb. The <code>X</code> axis is perpendicular to the back of the hand being described, with back of the users right hand pointing towards <code>+X</code> and the back of the user's left hand pointing towards <code>-X</code>. The <code>Y</code> axis is implied by the relationship between the <code>X</code> and <code>Z</code> axis, with <code>+Y</code> roughly pointing in the direction of the user's arm.

The {{gripSpace}} MUST be <code>null</code> if the input source isn't inherently trackable such as for input sources with a {{targetRayMode}} of {{XRTargetRayMode/"gaze"}} or {{XRTargetRayMode/"screen"}}.

The <dfn attribute for="XRInputSource">profiles</dfn> attribute is a [=/list=] of [=input profile name=]s indicating both the prefered visual representation and behavior of the input source.

An <dfn for="XRInputSource">input profile name</dfn> is a lowercase {{DOMString}} containing no spaces, with separate words concatenated with a hyphen (<code>-</code>) character. A descriptive name should be chosen, using the prefered verbiage of the device vendor when possible. If the platform provides an appropriate identifier, such as a USB vendor and product ID, it MAY be used. Values that uniquely identify a single device, such as serial numbers, MUST NOT be used. The [=input profile name=] MUST NOT contain an indication of device handedness. If multiple user agents expose the same device, they SHOULD make an effort to report the same [=input profile name=]. The <a href="https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry">WebXR Input Profiles Registry</a> is the recommended location for managing [=input profile name=]s.

Profiles are given in descending order of specificity. Any [=input profile name=]s given after the first entry in the list should provide fallback values that represent alternative representations of the device. This may include a more generic or prior version of the device, a more widely recognized device that is sufficiently similar, or a broad description of the device type (such as "generic-trigger-touchpad"). If multiple profiles are given, the layouts they describe must all represent a superset or subset of every other profile in the list.

If the {{XRSession}}'s [=mode=] is {{XRSessionMode/"inline"}}, {{XRInputSource/profiles}} MUST be an empty list.

If the input device cannot be reliably identified, or the user agent wishes to mask the input device being used, it MAY choose to only report generic [=input profile name=]s or an empty list.

<p class="note">
For example, the Samsung HMD Odyssey's controller is a design variant of the standard Windows Mixed Reality controller. Both controllers share the same input layout. As a result, the {{XRInputSource/profiles}} for a Samsung HMD Odyssey controller could be: <code>["samsung-odyssey", "microsoft-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]</code>. The appearance of the controller is most precisely communicated by the first profile in the list, with the second profile describing an acceptable substitute, and the last profile a generic fallback that describes the device in the roughest sense. (It's a controller with a trigger, squeeze button, touchpad and thumbstick.)
</br></br>
Similarly, the Valve Index controller is backwards compatible with the HTC Vive controller, but the Index controller has additional buttons and axes. As a result, the {{XRInputSource/profiles}} for the Valve Index controller could be: <code>["valve-index", "htc-vive", "generic-trigger-squeeze-touchpad-thumbstick"]</code>. In this case the input layout described by the <code>"valve-index"</code> profile is a superset of the layout described by the <code>"htc-vive"</code> profile. Also, the <code>"valve-index"</code> profile indicates the precise appearance of the controller, while the <code>"htc-vive"</code> controller has a significantly different appearance. In this case the UA would have deemed that difference acceptable. And as in the first example, the last profile is a generic fallback.
</br></br>
(Exact strings are examples only. Actual profile names are managed in the <a href="https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry">WebXR Input Profiles Registry</a>.)
</p>

Note: {{XRInputSource}}s in an {{XRSession}}'s {{XRSession/inputSources}} array are "live". As such values within them are updated in-place. This means that it doesn't work to save a reference to an {{XRInputSource}}'s attribute on one frame and compare it to the same attribute in a subsequent frame to test for state changes, because they will be the same object. Therefore developers that wish to compare input state from frame to frame should copy the content of the state in question.

An [=XR input source=] is a <dfn>primary input source</dfn> if it supports a <dfn>primary action</dfn>. The [=primary action=] is a platform-specific action that, when engaged, produces {{XRSession/selectstart}}, {{XRSession/selectend}}, and {{XRSession/select}} events. Examples of possible [=primary action=]s are pressing a trigger, touchpad, or button, speaking a command, or making a hand gesture. If the platform guidelines define a recommended primary input then it should be used as the [=primary action=], otherwise the user agent is free to select one. The device MUST support at least one [=primary input source=].

An [=XR input source=] is an <dfn>auxiliary input source</dfn> if it does not support a [=primary action=], for example [=transient input sources=] associated with secondary screen touches on a multitouch device.

<div class="algorithm" data-algorithm="on-input-start">

When an [=XR input source=] |source| for {{XRSession}} |session| begins its [=primary action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to [=fire an input source event=] with name {{selectstart!!event}}, frame |frame|, and source |source|.

</div>

<div class="algorithm" data-algorithm="on-input-end">

When an [=XR input source=] |source| for {{XRSession}} |session| ends its [=primary action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to perform the following steps:
    1. [=Fire an input source event=] with name {{select!!event}}, frame |frame|, and source |source|.
    1. [=Fire an input source event=] with name {{selectend!!event}}, frame |frame|, and source |source|.

</div>

Each [=XR input source=] MAY define a <dfn>primary squeeze action</dfn>. The [=primary squeeze action=] is a platform-specific action that, when engaged, produces {{XRSession/squeezestart}}, {{XRSession/squeezeend}}, and {{XRSession/squeeze}} events. The [=primary squeeze action=] should be used for actions roughly mapping to squeezing or grabbing. Examples of possible [=primary squeeze action=]s are pressing a grip trigger or making a grabbing hand gesture. If the platform guidelines define a recommended primary squeeze action then it should be used as the [=primary squeeze action=], otherwise the user agent MAY select one.

<div class="algorithm" data-algorithm="on-squeeze-start">

When an [=XR input source=] |source| for {{XRSession}} |session| begins its [=primary squeeze action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to [=fire an input source event=] with name {{squeezestart!!event}}, frame |frame|, and source |source|.

</div>

<div class="algorithm" data-algorithm="on-squeeze-end">

When an [=XR input source=] |source| for {{XRSession}} |session| ends its [=primary squeeze action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to perform the following steps:
    1. [=Fire an input source event=] with name {{squeeze!!event}}, frame |frame|, and source |source|.
    1. [=Fire an input source event=] with name {{squeezeend!!event}}, frame |frame|, and source |source|.

</div>

Sometimes platform-specific behavior can result in a [=primary action=] or [=primary squeeze action=] being interrupted or cancelled. For example, a [=/XR input source=] may be removed from the [=XRSession/XR device=] after the [=primary action=] or [=primary squeeze action=] is started but before it ends.

<div class="algorithm" data-algorithm="on-input-cancelled">

When an [=XR input source=] |source| for {{XRSession}} |session| has its [=primary action=] cancelled the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to [=fire an input source event=] an {{XRInputSourceEvent}} with name {{selectend!!event}}, frame |frame|, and source |source|.

</div>

<div class="algorithm" data-algorithm="on-squeeze-cancelled">

When an [=XR input source=] |source| for {{XRSession}} |session| has its [=primary squeeze action=] cancelled the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| with [=XRFrame/time=] being the time the action occurred.
  1. [=Queue a task=] to [=fire an input source event=] an {{XRInputSourceEvent}} with name {{squeezeend!!event}}, frame |frame|, and source |source|.

</div>

Transient input {#transient-input}
---------------

Some [=/XR device=]s may support <dfn>transient input sources</dfn>, where the [=XR input source=] is only meaningful while performing a <dfn>transient action</dfn>, either the [=primary action=] for a [=primary input source=], or a device-specific <dfn>auxiliary action</dfn> for an [=auxiliary input source=]. An example would be mouse, touch, or stylus input against an {{XRSessionMode/"inline"}} {{XRSession}}, which MUST produce a transient {{XRInputSource}} with a {{targetRayMode}} set to {{screen}}, treated as a [=primary action=] for the [[POINTEREVENTS#dfn-primary-pointer]], and as a non-primary [=auxiliary action=] for a non-primary pointer. [=Transient input sources=] are only present in the session's [=list of active XR input sources=] for the duration of the [=transient action=].

[=Transient input sources=] follow the following sequence when handling [=transient actions=] instead of the algorithms for non-transient [=primary actions=]:

<div class="algorithm" data-algorithm="on-transient-input-start">

When a [=transient input source=] |source| for {{XRSession}} |session| begins its [=transient action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| for the time the action occurred.
  1. [=Queue a task=] to perform the following steps:
    1. Fire any <code>"pointerdown"</code> events produced by the [=XR input source=]'s action, if necessary.
    1. [=add input source|Add the XR input source=] to the [=list of active XR input sources=].
    1. If the [=transient action=] is a [=primary action=], [=fire an input source event=] with name {{selectstart!!event}}, frame |frame|, and source |source|.

</div>

<div class="algorithm" data-algorithm="on-transient-input-end">

When a [=transient input source=] |source| for {{XRSession}} |session| ends its [=transient action=] the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| for the time the action occurred.
  1. [=Queue a task=] to perform the following steps:
    1. If the [=transient action=] is a [=primary action=], [=fire an input source event=] with name {{select!!event}}, frame |frame|, and source |source|.
    1. Fire any <code>"click"</code> events produced by the [=XR input source=]'s action, if necessary.
    1. If the [=transient action=] is a [=primary action=], [=fire an input source event=] with name {{selectend!!event}}, frame |frame|, and source |source|.
    1. [=remove input source|Remove the XR input source=] from the [=list of active XR input sources=].
    1. Fire any <code>"pointerup"</code> events produced by the [=XR input source=]'s action, if necessary.

</div>

<div class="algorithm" data-algorithm="on-transient-input-cancelled">

When a [=transient input source=] |source| for {{XRSession}} |session| has its [=transient action=] cancelled the UA MUST run the following steps:

  1. Let |frame| be a new {{XRFrame}} with {{XRFrame/session}} |session| for the time the action occurred.
  1. [=Queue a task=] to perform the following steps:
    1. If the [=transient action=] is a [=primary action=], [=fire an input source event=] with name {{selectend!!event}}, frame |frame|, and source |source|.
    1. [=remove input source|Remove the XR input source=] from the [=list of active XR input sources=].
    1. Fire any <code>"pointerup"</code> events produced by the [=XR input source=]'s action, if necessary.

</div>

XRInputSourceArray {#xrinputsourcearray-interface}
------------------

An {{XRInputSourceArray}} represents a [=/list=] of {{XRInputSource}}s. It is used in favor of a [=/frozen array type=] when the contents of the [=/list=] are expected to change over time, such as with the {{XRSession}} {{XRSession/inputSources}} attribute.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRInputSourceArray {
  iterable&lt;XRInputSource&gt;;
  readonly attribute unsigned long length;
  getter XRInputSource(unsigned long index);
};
</pre>

The <dfn attribute for="XRInputSourceArray">length</dfn> attribute of {{XRInputSourceArray}} indicates how many {{XRInputSource}}s are contained within the {{XRInputSourceArray}}.

The <dfn export for="XRInputSourceArray">[=/indexed property getter=]</dfn> of {{XRInputSourceArray}} retrieves the {{XRInputSource}} at the provided index.

Layers {#layers}
======

Note: While this specification only defines the {{XRWebGLLayer}} layer, future extensions to the spec are expected to add additional layer types and the image sources that they draw from.

XRWebGLLayer {#xrwebgllayer-interface}
------------

An {{XRWebGLLayer}} is a layer which provides a WebGL framebuffer to render into, enabling hardware accelerated rendering of 3D graphics to be presented on the [=XRSession/XR device=].

<pre class="idl">
typedef (WebGLRenderingContext or
         WebGL2RenderingContext) XRWebGLRenderingContext;

dictionary XRWebGLLayerInit {
  boolean antialias = true;
  boolean depth = true;
  boolean stencil = false;
  boolean alpha = true;
  boolean ignoreDepthValues = false;
  double framebufferScaleFactor = 1.0;
};

[SecureContext, Exposed=Window]
interface XRWebGLLayer {
  constructor(XRSession session,
             XRWebGLRenderingContext context,
             optional XRWebGLLayerInit layerInit = {});
  // Attributes
  readonly attribute boolean antialias;
  readonly attribute boolean ignoreDepthValues;

  [SameObject] readonly attribute WebGLFramebuffer? framebuffer;
  readonly attribute unsigned long framebufferWidth;
  readonly attribute unsigned long framebufferHeight;

  // Methods
  XRViewport? getViewport(XRView view);

  // Static Methods
  static double getNativeFramebufferScaleFactor(XRSession session);
};
</pre>

Each {{XRWebGLLayer}} has a <dfn for="XRWebGLLayer">context</dfn> object, initially <code>null</code>, which is an instance of either a {{WebGLRenderingContext}} or a {{WebGL2RenderingContext}}.

Each {{XRWebGLLayer}} has an associated <dfn for="XRWebGLLayer">session</dfn>, which is the {{XRSession}} it was created with.

<div class="algorithm" data-algorithm="construct-webgl-layer">

The <dfn constructor for="XRWebGLLayer">XRWebGLLayer(|session|, |context|, |layerInit|)</dfn> constructor MUST perform the following steps when invoked:

  1. Let |layer| be a new {{XRWebGLLayer}}
  1. If |session|'s [=ended=] value is <code>true</code>, throw an {{InvalidStateError}} and abort these steps.
  1. If |context| is lost, throw an {{InvalidStateError}} and abort these steps.
  1. If |session| is an [=immersive session=] and |context|'s [=XR compatible=] boolean is <code>false</code>, throw an {{InvalidStateError}} and abort these steps.
  1. Initialize |layer|'s [=XRWebGLLayer/context=] to |context|.
  1. Initialize |layer|'s [=XRWebGLLayer/session=] to |session|.
  1. Initialize |layer|'s {{XRWebGLLayer/ignoreDepthValues}} as follows:
    <dl class="switch">
      <dt> If |layerInit|'s {{XRWebGLLayerInit/ignoreDepthValues}} value is <code>false</code> and the [=XR Compositor=] will make use of depth values
      <dd> Initialize |layer|'s {{XRWebGLLayer/ignoreDepthValues}} to <code>false</code>
      <dt> Otherwise
      <dd> Initialize |layer|'s {{XRWebGLLayer/ignoreDepthValues}} to <code>true</code>
    </dl>
  1. Initialize |layer|'s [=XRWebGLLayer/composition disabled=] boolean as follows:
    <dl class="switch">
      <dt> If |session| is an [=inline session=]
      <dd> Initialize |layer|'s [=XRWebGLLayer/composition disabled=] to <code>true</code>
      <dt> Otherwise
      <dd> Initialize |layer|'s [=XRWebGLLayer/composition disabled=] boolean to <code>false</code>
    </dl>
  1. <dl class="switch">
      <dt> If |layer|'s [=XRWebGLLayer/composition disabled=] boolean is <code>false</code>:
      <dd>
        1. Initialize |layer|'s {{XRWebGLLayer/antialias}} to |layerInit|'s {{XRWebGLLayerInit/antialias}} value.
        1. Initialize |layer|'s {{XRWebGLLayer/framebuffer}} to a new [=opaque framebuffer=] created with |context| and |layerInit|'s {{XRWebGLLayerInit/depth}}, {{XRWebGLLayerInit/stencil}}, and {{XRWebGLLayerInit/alpha}} values.
        1. Allocate and initialize resources compatible with |session|'s [=XRSession/XR device=], including GPU accessible memory buffers, as required to support the compositing of |layer|.
        1. If |layer|’s resources were unable to be created for any reason, throw an {{OperationError}} and abort these steps.
      <dt> Otherwise
      <dd>
        1. Initialize |layer|'s {{XRWebGLLayer/antialias}} to |layer|'s {{XRWebGLLayer/context}}'s [=actual context parameters=] {{WebGLContextAttributes|antialias}} value.
        1. Initialize |layer|'s {{XRWebGLLayer/framebuffer}} to <code>null</code>.
    </dl>
  1. Return |layer|.

</div>

Note: If an {{XRWebGLLayer}}'s [=XRWebGLLayer/composition disabled=] boolean is set to <code>true</code> all values on the {{XRWebGLLayerInit}} object are ignored, since the {{WebGLRenderingContext}}'s default framebuffer was already allocated using the context's [=actual context parameters=] and cannot be overridden.

The <dfn attribute for="XRWebGLLayer">context</dfn> attribute is the {{WebGLRenderingContext}} the {{XRWebGLLayer}} was created with.

Each {{XRWebGLLayer}} has a <dfn for="XRWebGLLayer">composition disabled</dfn> boolean which is initially set to <code>false</code>. If set to <code>true</code> it indicates that the {{XRWebGLLayer}} MUST NOT allocate its own {{WebGLFramebuffer}}, and all properties of the {{XRWebGLLayer}} that reflect {{XRWebGLLayer/framebuffer}} properties MUST instead reflect the properties of the [=XRWebGLLayer/context=]'s default framebuffer.

The <dfn attribute for="XRWebGLLayer">framebuffer</dfn> attribute of an {{XRWebGLLayer}} is an instance of a {{WebGLFramebuffer}} which has been marked as [=opaque framebuffer|opaque=] if [=XRWebGLLayer/composition disabled=] is <code>false</code>, and <code>null</code> otherwise. The {{framebuffer}} size cannot be adjusted by the developer after the {{XRWebGLLayer}} has been created.

An <dfn>opaque framebuffer</dfn> functions identically to a standard {{WebGLFramebuffer}} with the following changes that make it behave more like the [=default framebuffer=]:

 - An [=opaque framebuffer=] MAY support antialiasing, even in WebGL 1.0.
 - An [=opaque framebuffer=]'s attachments cannot be inspected or changed. Calling {{framebufferTexture2D}}, {{framebufferRenderbuffer}}, {{deleteFramebuffer}}, or {{getFramebufferAttachmentParameter}} with an [=opaque framebuffer=] MUST generate an {{INVALID_OPERATION}} error.
 - An [=opaque framebuffer=] is considered incomplete outside of a {{XRSession/requestAnimationFrame()}} callback. When not in a {{XRSession/requestAnimationFrame()}} callback calls to {{checkFramebufferStatus}} MUST generate a {{FRAMEBUFFER_UNSUPPORTED}} error and attempts to clear, draw to, or read from the [=opaque framebuffer=] MUST generate an {{INVALID_FRAMEBUFFER_OPERATION}} error.
 - An [=opaque framebuffer=] initialized with {{XRWebGLLayerInit/depth}} <code>false</code> will not have an attached depth buffer.
 - An [=opaque framebuffer=] initialized with {{XRWebGLLayerInit/stencil}} <code>false</code> will not have an attached stencil buffer.
 - An [=opaque framebuffer=]'s color buffer will have an alpha channel if and only if {{XRWebGLLayerInit/alpha}} is <code>true</code>.
 - The [=XR Compositor=] will assume the [=opaque framebuffer=] contains colors with premultiplied alpha. This is true regardless of the {{WebGLContextAttributes|premultipliedAlpha}} value set in the {{XRWebGLLayer/context}}'s [=actual context parameters=].

Note: User agents are not required to respect <code>true</code> values of {{XRWebGLLayerInit/depth}} and {{XRWebGLLayerInit/stencil}}, which is similar to WebGL's behavior when [=create a drawing buffer|creating a drawing buffer=]

The buffers attached to an [=opaque framebuffer=] MUST be cleared to the values in the table below when first created, or prior to the processing of each [=XR animation frame=]. This is identical to the behavior of the WebGL context's [=default framebuffer=].

<table class="tg">
  <thead>
    <tr>
      <th>Buffer</th>
      <th>Clear Value</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Color</td>
      <td>(0, 0, 0, 0)</td>
    </tr>
    <tr>
      <td>Depth</td>
      <td>1.0</td>
    </tr>
    <tr>
      <td>Stencil</td>
      <td>0</td>
    </tr>
  </tbody>
</table>

Note: Implementations may optimize away the required implicit clear operation of the [=opaque framebuffer=] as long as a guarantee can be made that the developer cannot gain access to buffer contents from another process. For instance, if the developer performs an explicit clear then the implicit clear is not needed.

Each {{XRWebGLLayer}} has a <dfn for="XRWebGLLayer">target framebuffer</dfn>, which is the {{XRWebGLLayer/framebuffer}} if [=XRWebGLLayer/composition disabled=] is <code>false</code>, and the [=XRWebGLLayer/context=]'s default framebuffer otherwise.

The <dfn attribute for="XRWebGLLayer">framebufferWidth</dfn> and <dfn attribute for="XRWebGLLayer">framebufferHeight</dfn> attributes return the width and height of the [=XRWebGLLayer/target framebuffer=]'s attachments, respectively.

The <dfn attribute for="XRWebGLLayer">antialias</dfn> attribute is <code>true</code> if the [=XRWebGLLayer/target framebuffer=] supports antialiasing using a technique of the UAs choosing, and <code>false</code> if no antialiasing will be performed.

The <dfn attribute for="XRWebGLLayer">ignoreDepthValues</dfn> attribute, if <code>true</code>, indicates the [=XR Compositor=] MUST NOT make use of values in the depth buffer attachment when rendering. When the attribute is <code>false</code> it indicates that the content of the depth buffer attachment will be used by the [=XR Compositor=] and is expected to be representative of the scene rendered into the layer.

Depth values stored in the buffer are expected to be between <code>0.0</code> and <code>1.0</code>, with <code>0.0</code> representing the distance of {{XRRenderState/depthNear}} and <code>1.0</code> representing the distance of {{XRRenderState/depthFar}}, with intermediate values interpolated linearly. This is the default behavior of WebGL. (See documentation for the <a href="https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glDepthRangef.xml">depthRange function</a> for additional details.))

Note: Making the scene's depth buffer available to the compositor allows some platforms to provide quality and comfort improvements such as improved reprojection.

Each {{XRWebGLLayer}} MUST have a <dfn>list of viewports</dfn> which is a [=/list=] containing one [=WebGL viewport=] for each {{XRView}} the {{XRSession}} currently exposes. The viewports MUST NOT be overlapping. If [=XRWebGLLayer/composition disabled=] is <code>true</code>, the [=list of viewports=] MUST contain a single [=WebGL viewport=] that covers the [=XRWebGLLayer/context=]'s entire default framebuffer.

{{getViewport()}} queries the {{XRViewport}} the given {{XRView}} should use when rendering to the layer.

<div class="algorithm" data-algorithm="get-viewport">

The <dfn method for="XRWebGLLayer">getViewport(|view|)</dfn> method, when invoked on an {{XRWebGLLayer}} |layer|, MUST run the following steps:

  1. Let |frame| be |view|'s [=XRView/frame=].
  1. If |frame|'s {{XRFrame/session}} is not equal to |layer|'s [=XRWebGLLayer/session=], throw an {{InvalidStateError}} and abort these steps.
  1. If |frame|'s [=XRFrame/active=] boolean is <code>false</code>, throw an {{InvalidStateError}} and abort these steps.
  1. Let |glViewport| be the [=WebGL viewport=] from the [=list of viewports=] associated with |view|.
  1. Let |viewport| be a new {{XRViewport}} instance.
  1. Initialize |viewport|'s {{XRViewport/x}} to |glViewport|'s <code>x</code> component.
  1. Initialize |viewport|'s {{XRViewport/y}} to |glViewport|'s <code>y</code> component.
  1. Initialize |viewport|'s {{XRViewport/width}} to |glViewport|'s <code>width</code>.
  1. Initialize |viewport|'s {{XRViewport/height}} to |glViewport|'s <code>height</code>.
  1. Return |viewport|.

</div>

Each {{XRSession}} MUST identify a <dfn>native WebGL framebuffer resolution</dfn>, which is the pixel resolution of a WebGL framebuffer required to match the physical pixel resolution of the [=XRSession/XR device=].

<div class="algorithm" data-algorithm="native-webgl-framebuffer-resolution">

The [=native WebGL framebuffer resolution=] is determined by running the following steps:

  1. Let |session| be the target {{XRSession}}.
  1. If |session|'s [=XRSession/mode=] value is not <code>"inline"</code>, set the [=native WebGL framebuffer resolution=] to the resolution required to have a 1:1 ratio between the pixels of a framebuffer large enough to contain all of the session's {{XRView}}s and the physical screen pixels in the area of the display under the highest magnification and abort these steps. If no method exists to determine the native resolution as described, the [=recommended WebGL framebuffer resolution=] MAY be used.
  1. If |session|'s [=XRSession/mode=] value is <code>"inline"</code>, set the [=native WebGL framebuffer resolution=] to the size of the |session|'s {{XRSession/renderState}}'s [=XRRenderState/output canvas=] in physical display pixels and reevaluate these steps every time the size of the canvas changes or the [=XRRenderState/output canvas=] is changed.

</div>

Additionally, the {{XRSession}} MUST identify a <dfn>recommended WebGL framebuffer resolution</dfn>, which represents a best estimate of the WebGL framebuffer resolution large enough to contain all of the session's {{XRView}}s that provides an average application a good balance between performance and quality. It MAY be smaller than, larger than, or equal to the [=native WebGL framebuffer resolution=].

Note: The user agent is free to use and method of its choosing to estimate the [=recommended WebGL framebuffer resolution=]. If there are platform-specific methods for querying a recommended size it is recommended that they be used, but not required.

<div class="algorithm" data-algorithm="get-native-framebuffer-scale-factor">

The <dfn method for="XRWebGLLayer">getNativeFramebufferScaleFactor(|session|)</dfn> method, when invoked, MUST run the following steps:

  1. Let |session| be the target {{XRSession}}.
  1. If |session|'s [=ended=] value is <code>true</code>, return <code>0.0</code> and abort these steps.
  1. Return the value that the |session|'s [=recommended WebGL framebuffer resolution=] must be multiplied by to yield the |session|'s [=native WebGL framebuffer resolution=].

</div>

WebGL Context Compatibility {#contextcompatibility}
---------------------------

In order for a WebGL context to be used as a source for immersive XR imagery it must be created on a <dfn>compatible graphics adapter</dfn> for the [=XR/immersive XR device=]. What is considered a [=compatible graphics adapter=] is platform dependent, but is understood to mean that the graphics adapter can supply imagery to the [=XR/immersive XR device=] without undue latency. If a WebGL context was not already created on the [=compatible graphics adapter=], it typically must be re-created on the adapter in question before it can be used with an {{XRWebGLLayer}}.

Note: On an XR platform with a single GPU, it can safely be assumed that the GPU is compatible with the [=XR/immersive XR device=]s advertised by the platform, and thus any hardware accelerated WebGL contexts are compatible as well. On PCs with both an integrated and discrete GPU the discrete GPU is often considered the [=compatible graphics adapter=] since it generally a higher performance chip. On desktop PCs with multiple graphics adapters installed, the one with the [=XR/immersive XR device=] physically connected to it is likely to be considered the [=compatible graphics adapter=].

Note: {{XRSessionMode/"inline"}} sessions render using the same graphics adapter as canvases, and thus do not need {{WebGLContextAttributes/xrCompatible}} contexts.

<pre class="idl">
partial dictionary WebGLContextAttributes {
    boolean xrCompatible = false;
};

partial interface mixin WebGLRenderingContextBase {
    [NewObject] Promise&lt;void&gt; makeXRCompatible();
};
</pre>

When a user agent implements this specification it MUST set a <dfn>XR compatible</dfn> boolean, initially set to <code>false</code>, on every {{WebGLRenderingContextBase}}. Once the [=XR compatible=] boolean is set to <code>true</code>, the context can be used with layers for any {{XRSession}} requested from the current [=XR/immersive XR device=].

The [=XR compatible=] boolean can be set either at context creation time or after context creation, potentially incurring a context loss. To set the [=XR compatible=] boolean at context creation time, the {{xrCompatible}} context creation attribute must be set to <code>true</code> when requesting a WebGL context.

<div class="algorithm" data-algorithm="create-with-compatible-xr-device">

When the {{HTMLCanvasElement}}'s {{HTMLCanvasElement/getContext()}} method is invoked with a {{WebGLContextAttributes}} dictionary with {{xrCompatible}} set to <code>true</code>, run the following steps:

  1. [=ensures an immersive XR device is selected|Ensure an immersive XR device is selected=].
  1. If the [=XR/immersive XR device=] is <code>null</code>:
    1. [=Create the WebGL context=] as usual.
    1. Let |context| be the newly created WebGL context.
    1. Set |context|'s [=XR compatible=] boolean to false.
  1. Otherwise:
    1. [=Create the WebGL context=] as usual, ensuring it is created on a [=compatible graphics adapter=] for the [=XR/immersive XR device=].
    1. Let |context| be the newly created WebGL context.
    1. Set |context|'s [=XR compatible=] boolean to true.
  1. Return |context|.

</div>

<div class="example">
The following code creates a WebGL context that is compatible with an [=XR/immersive XR device=] and then uses it to create an {{XRWebGLLayer}}.

<pre highlight="js">
function onXRSessionStarted(xrSession) {
  let glCanvas = document.createElement("canvas");
  let gl = glCanvas.getContext("webgl", { xrCompatible: true });

  loadWebGLResources();

  xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl) });
}
</pre>
</div>

To set the [=XR compatible=] boolean after the context has been created, the {{makeXRCompatible()}} method is used.

<div class="algorithm" data-algorithm="make-xr-compatible">
The <dfn method for="WebGLRenderingContextBase">makeXRCompatible()</dfn> method ensures the {{WebGLRenderingContextBase}} is running on a [=compatible graphics adapter=] for the [=XR/immersive XR device=].

When this method is invoked, the user agent MUST run the following steps:

  1. Let |promise| be [=a new Promise=].
  1. Let |context| be the target {{WebGLRenderingContextBase}} object.
  1. [=ensures an immersive XR device is selected|Ensure an immersive XR device is selected=].
  1. Set |context|'s [=XR compatible=] boolean as follows:
    <dl class="switch">
      <dt> If |context|'s [=WebGL context lost flag=] is set
      <dd> Set |context|'s [=XR compatible=] boolean to <code>false</code> and [=reject=] |promise| with an {{InvalidStateError}}.
      <dt> If the [=XR/immersive XR device=] is <code>null</code>
      <dd> Set |context|'s [=XR compatible=] boolean to <code>false</code> and [=reject=] |promise| with an {{InvalidStateError}}.
      <dt> If |context|'s [=XR compatible=] boolean is <code>true</code>
      <dd> [=/Resolve=] |promise|.
      <dt> If |context| was created on a [=compatible graphics adapter=] for the [=XR/immersive XR device=]
      <dd> Set |context|'s [=XR compatible=] boolean to <code>true</code> and [=/resolve=] |promise|.
      <dt> Otherwise
      <dd> [=Queue a task=] on the [=/WebGL task source=] to perform the following steps:
              1. Force |context| to be lost and [=handle the context loss=] as described by the WebGL specification.
              1. If the [=canceled flag=] of the "webglcontextlost" event fired in the previous step was not set, [=reject=] |promise| with an {{AbortError}} and abort these steps.
              1. [=Restore the context=] on a [=compatible graphics adapter=] for the [=XR/immersive XR device=].
              1. Set |context|'s [=XR compatible=] boolean to <code>true</code>.
              1. [=/Resolve=] |promise|.
    </dl>
  1. Return |promise|.

</div>

<div class="algorithm" data-algorithm="webgl-context-lost">

Additionally, when any WebGL [=handle the context loss|context is lost=] run the following steps prior to firing the "webglcontextlost" event:

  1. Set the context's [=XR compatible=] boolean to <code>false</code>.

</div>

<div class="example">
The following code creates an {{XRWebGLLayer}} from a pre-existing WebGL context.

<pre highlight="js">
let glCanvas = document.createElement("canvas");
let gl = glCanvas.getContext("webgl");

loadWebGLResources();

glCanvas.addEventListener("webglcontextlost", (event) => {
  // Indicates that the WebGL context can be restored.
  event.canceled = true;
});

glCanvas.addEventListener("webglcontextrestored", (event) => {
  // WebGL resources need to be re-created after a context loss.
  loadWebGLResources();
});

function onXRSessionStarted(xrSession) {
  // Make sure the canvas context we want to use is compatible with the device.
  // May trigger a context loss.
  return gl.makeXRCompatible().then(() => {
    return xrSession.updateRenderState({
      baseLayer: new XRWebGLLayer(xrSession, gl)
    });
  });
}
</pre>
</div>

Events {#events}
======

XRSessionEvent {#xrsessionevent-interface}
--------------

{{XRSessionEvent}}s are fired to indicate changes to the state of an {{XRSession}}.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRSessionEvent : Event {
  constructor(DOMString type, XRSessionEventInit eventInitDict);
  [SameObject] readonly attribute XRSession session;
};

dictionary XRSessionEventInit : EventInit {
  required XRSession session;
};
</pre>

The <dfn attribute for="XRSessionEvent">session</dfn> attribute indicates the {{XRSession}} that generated the event.

XRInputSourceEvent {#xrinputsourceevent-interface}
------------------

{{XRInputSourceEvent}}s are fired to indicate changes to the state of an {{XRInputSource}}.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRInputSourceEvent : Event {
  constructor(DOMString type, XRInputSourceEventInit eventInitDict);
  [SameObject] readonly attribute XRFrame frame;
  [SameObject] readonly attribute XRInputSource inputSource;
};

dictionary XRInputSourceEventInit : EventInit {
  required XRFrame frame;
  required XRInputSource inputSource;
};
</pre>

The <dfn attribute for="XRInputSourceEvent">inputSource</dfn> attribute indicates the {{XRInputSource}} that generated this event.

The <dfn attribute for="XRInputSourceEvent">frame</dfn> attribute is an {{XRFrame}} that corresponds with the time that the event took place. It may represent historical data. Any {{XRViewerPose}} queried from the {{XRInputSourceEvent/frame}} MUST have an empty {{XRViewerPose/views}} array.

<div class="algorithm" data-algorithm="fire-input-source-event">

When the user agent has to <dfn>fire an input source event</dfn> with name |name|, {{XRFrame}} |frame|, and {{XRInputSource}} |source| it MUST run the following steps:

  1. Create an {{XRInputSourceEvent}} |event| with {{Event/type}} |name|, {{XRInputSourceEvent/frame}} |frame|, and {{XRInputSourceEvent/inputSource}} |source|.
  1. Set |frame|'s [=active=] boolean to <code>true</code>.
  1. [=XRFrame/Apply frame updates=] for |frame|.
  1. [=Dispatch=] |event| on |frame|'s {{XRFrame/session}}
  1. Set |frame|'s [=active=] boolean to <code>false</code>.

</div>


XRInputSourcesChangeEvent {#xrinputsourceschangeevent-interface}
-------------------------

{{XRInputSourcesChangeEvent}}s are fired to indicate changes to the {{XRInputSource}}s that are available to an {{XRSession}}.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRInputSourcesChangeEvent : Event {
  constructor(DOMString type, XRInputSourcesChangeEventInit eventInitDict);
  [SameObject] readonly attribute XRSession session;
  [SameObject] readonly attribute FrozenArray&lt;XRInputSource&gt; added;
  [SameObject] readonly attribute FrozenArray&lt;XRInputSource&gt; removed;
};

dictionary XRInputSourcesChangeEventInit : EventInit {
  required XRSession session;
  required FrozenArray&lt;XRInputSource&gt; added;
  required FrozenArray&lt;XRInputSource&gt; removed;

};
</pre>

The <dfn attribute for="XRInputSourcesChangeEvent">session</dfn> attribute indicates the {{XRSession}} that generated the event.

The <dfn attribute for="XRInputSourcesChangeEvent">added</dfn> attribute is a [=/list=] of {{XRInputSource}}s that were added to the {{XRSession}} at the time of the event.

The <dfn attribute for="XRInputSourcesChangeEvent">removed</dfn> attribute is a [=/list=] of {{XRInputSource}}s that were removed from the {{XRSession}} at the time of the event.


XRReferenceSpaceEvent {#xrreferencespaceevent-interface}
---------------------

{{XRReferenceSpaceEvent}}s are fired to indicate changes to the state of an {{XRReferenceSpace}}.

<pre class="idl">
[SecureContext, Exposed=Window]
interface XRReferenceSpaceEvent : Event {
  constructor(DOMString type, XRReferenceSpaceEventInit eventInitDict);
  [SameObject] readonly attribute XRReferenceSpace referenceSpace;
  [SameObject] readonly attribute XRRigidTransform? transform;
};

dictionary XRReferenceSpaceEventInit : EventInit {
  required XRReferenceSpace referenceSpace;
  XRRigidTransform transform;
};
</pre>

The <dfn attribute for="XRReferenceSpaceEvent">referenceSpace</dfn> attribute indicates the {{XRReferenceSpace}} that generated this event.

The <dfn attribute for="XRReferenceSpaceEvent">transform</dfn> attribute describes the post-event position and orientation of the {{XRReferenceSpaceEvent/referenceSpace}}'s [=native origin=] in the pre-event coordinate system.

Event Types {#event-types}
-----------

The user agent MUST provide the following new events. Registration for and firing of the events must follow the usual behavior of DOM4 Events.

The user agent MUST fire a <dfn event for="XR">devicechange</dfn> event on the {{XR}} object to indicate that the availability of [=XR/immersive XR device=]s has been changed unless the document's origin is not allowed to use the "xr-spatial-tracking" [[#feature-policy|feature policy]]. The event MUST be of type {{Event}}.

A user agent MUST dispatch a <dfn event for="XRSession">visibilitychange</dfn> event on an {{XRSession}} each time the [=XRSession/visibility state=] of the {{XRSession}} has changed. The event MUST be of type {{XRSessionEvent}}.

A user agent MUST dispatch an <dfn event for="XRSession">end</dfn> event on an {{XRSession}} when the session ends, either by the application or the user agent. The event MUST be of type {{XRSessionEvent}}.

A user agent MUST dispatch an <dfn event for="XRSession">inputsourceschange</dfn> event on an {{XRSession}} when the session's [=list of active XR input sources=] has changed. The event MUST be of type {{XRInputSourcesChangeEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">selectstart</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s begins its [=primary action=]. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">selectend</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s ends its [=primary action=] or when an {{XRInputSource}} that has begun a [=primary action=] is disconnected. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">select</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s has fully completed a [=primary action=]. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">squeezestart</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s begins its [=primary squeeze action=]. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">squeezeend</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s ends its [=primary squeeze action=] or when an {{XRInputSource}} that has begun a [=primary squeeze action=] is disconnected. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRSession">squeeze</dfn> event on an {{XRSession}} when one of its {{XRInputSource}}s has fully completed a [=primary squeeze action=]. The event MUST be of type {{XRInputSourceEvent}}.

A user agent MUST dispatch a <dfn event for="XRReferenceSpace">reset</dfn> event on an {{XRReferenceSpace}} when discontinuities of the [=native origin=] or [=effective origin=] occur, i.e. there are significant changes in the origin’s position or orientation relative to the user’s environment. (For example: After user recalibration of their XR device or if the XR device automatically shifts its origin after losing and regaining tracking.) A {{reset}} event MUST also be dispatched when the {{boundsGeometry}} changes for an {{XRBoundedReferenceSpace}}. A {{reset}} event MUST NOT be dispatched if the [=viewer=]'s pose experiences discontinuities but the {{XRReferenceSpace}}'s origin physical mapping remains stable, such as when the [=viewer=] momentarily loses and regains tracking within the same tracking area. A {{reset}} event also MUST NOT be dispatched as an {{unbounded}} reference space makes small adjustments to its [=native origin=] over time to maintain space stability near the user, if a significant discontinuity has not occurred. The event MUST be of type {{XRReferenceSpaceEvent}}, and MUST be dispatched prior to the execution of any [=XR animation frame=]s that make use of the new origin.

Note: This does mean that the session needs to hold on to strong references to any {{XRReferenceSpace}}s that have {{XRReferenceSpace/reset}} listeners.

Note: Jumps in [=viewer=] position can be handled by the application by observing the {{XRPose/emulatedPosition}} boolean. If a jump in [=viewer=] position coincides with {{XRPose/emulatedPosition}} switching from <code>true</code> to <code>false</code>, it indicates that the [=viewer=] has regained tracking and their new position represents a correction from the previously emulated values. For experiences without a "teleportation" mechanic, where the [=viewer=] can move through the virtual world without moving physically, this is generally the application's desired behavior. However, if an experience does provide a "teleportation" mechanic, it may be needlessly jarring to jump the [=viewer=]'s position back after tracking recovery. Instead, when such an application recovers tracking, it can simply resume the experience from the [=viewer=]'s current position in the virtual world by absorbing that sudden jump in position into its teleportation offset. To do so, the developer calls {{getOffsetReferenceSpace()}} to create a replacement reference space with its [=effective origin=] adjusted by the amount that the [=viewer=]'s position jumped since the previous frame.

Security, Privacy, and Comfort Considerations {#security}
=============================================

The WebXR Device API provides powerful new features which bring with them several unique privacy, security, and comfort risks that user agents must take steps to mitigate.

Sensitive Information {#sensitive-information-header}
---------------------

In the context of XR, <dfn>sensitive information</dfn> includes, but is not limited to, user-configurable data such as interpupillary distance (IPD) and sensor-based data such as {{XRPose}}s. All [=immersive sessions=] will expose some amount of sensitive data, due to the user's pose being necessary to render anything. However, in some cases, the same sensitive information will also be exposed via {{XRSessionMode/"inline"}} sessions.

### Active and focused document ### {#active-and-focused-document}
A document MUST be [=active and focused=] at the time that [=sensitive information=] is requested.

<div class="algorithm" data-algorithm="document-is-active-and-focused">

To determine if a given {{Document}} |document| is <dfn>active and focused</dfn> the user agent MUST run the following steps:

  1. If the [=currently focused area=] does not belong to |document|, return <code>false</code>
  1. If |document| is not of the [=same origin-domain=] as the [=active document=], return <code>false</code>
  1. Return <code>true</code>

</div>

### Trustworthy documents and origins ### {#trustworthy-documents}
In order to expose any [=sensitive information=] the requesting document MUST be considered [=trustworthy=].

<div class="algorithm" data-algorithm="document-is-trustworthy">

To determine if a given {{Document}} |document| is <dfn>trustworthy</dfn> the user agent MUST run the following steps:

  1. If |document| is not a [=responsible=] document, return <code>false</code>
  1. If |document| is not [=active and focused=], return <code>false</code>
  1. Return <code>true</code>

</div>

User intention {#user-intention}
--------------

It is often necessary to be sure of <dfn>user intent</dfn> before exposing sensitive information or allowing actions with a significant effect on the user's experience. This intent may be communicated or observed in a number of ways.

### User activation ### {#user-activation}
Events which are [=triggered by user activation=] MAY serve as an indication of [=user intent=] in some scenarios.

### Launching a web application ### {#application-launch}
In some environments a page may be presented as an application, installed with the express intent of running immersive content. In that case <dfn>launching a web application</dfn> MAY also serve as an indication of [=user intent=].

### Implicit and Explicit consent ### {#user-consent}
A user agent MAY use <dfn>implicit consent</dfn> based, for example, on the install status of a web application or frequency and recency of visits. Given the sensitivity of XR data, caution is strongly advised when relying on implicit signals. 

It is often useful to get <dfn>explicit consent</dfn> from the user before exposing [=sensitive information=]. When gathering explicit user consent, user agents present an explanation of what is being requested and provide users the option to decline. Requests for user consent can be presented in many visual forms based on the features being protected and user agent choice.

### Duration of consent ### {#consent-duration}
It is recommended that once [=explicit consent=] is granted for a specific [=/origin=] that this consent persist until the [=/browsing context=] has ended. User agents may choose to lengthen or shorten this consent duration based upon implicit or explicit signals of [=user intent=], but implementations are advised to exercise caution when deviating from this recommendation, particularly when relying on implicit signals. For example, it may be appropriate for a web application installed with the express intent of running immersive content to persist the user's consent, but not for an installed web application where immersive content is a secondary feature.

Regardless of how long the user agent chooses to persist the user's consent, [=sensitive information=] MUST only be exposed by an {{XRSession}} which has not [=ended=].

Mid-session consent {#mid-session-consent}
-------------------

There are multiple non-XR APIs which cause user agents to request [=explicit consent=] to use a feature. If the user agent will request the user's consent while there is an [=active immersive session=], the user agent MUST [=shut down the session=] prior to displaying the consent request to the user. If the user's consent for the feature had been granted prior to the [=active immersive session=] being created the session does not need to be terminated. 

Note: This limitation is to ensure that there is behavioral parity between all user agents until consensus is reached about how user agents should manage mid-session [=explicit consent=]. It is not expected to be a long term requirement. 

Data adjustments {#data-adjustments-header}
----------------

In some cases, security and privacy threats can be mitigated through <dfn>data adjustment</dfn>s such as throttling, quantizing, rounding, limiting, or otherwise manipulating the data reported from the [=/XR device=]. This may sometimes be necessary to avoid fingerprinting, even in situations when [=user intent=] has been established.  However, [=data adjustment=] mitigations MUST only be used in situations which would not result in user discomfort.

### Throttling ### {#throttling-header}
<dfn>Throttling</dfn> is when [=sensitive information=] is reported at a lower frequency than otherwise possible. This mitigation has the potential to reduce a site's ability to infer user intent, infer location, or perform user profiling. However, when not used appropriately throttling runs a significant risk of causing user discomfort. In addition, under many circumstances it may be inadequate to provide a complete mitigation.

### Rounding, quantization, and fuzzing ### {#rounding-and-friends}
Rounding, quantization, and fuzzing are three categories of mitigations that modify the raw data that would otherwise be returned to the developer. <dfn>Rounding</dfn> decreases the precision of data by reducing the number of digits used to express it. <dfn>Quantization</dfn> constrains continuous data to instead report a discrete subset of values. Fuzzing is the introduction of slight, random errors into the the data. Collectively, these mitigations are useful to avoid fingerprinting, and are especially useful when doing so does not cause noticeable impact on user comfort.

### Limiting ### {#limiting-header}
<dfn>Limiting</dfn> is when data is reported only when it is within a specific range. For example, it is possible to comfortably limit reporting positional pose data when a user has moved beyond a specific distance away from an approved location. Care should be taken to ensure that the user experience is not negatively affected when employing this mitigation. It is often desirable to avoid a 'hard stop' at the end of a range as this may cause disruptive user experiences.

Protected functionality {#protected-functionality}
-----------------------

The [=sensitive information=] exposed by the API can be divided into categories that share threat profiles and necessary protections against those threats.

### Immersiveness ### {#protect-immersiveness}
Users must be in control of when immersive sessions are created because the creation causes invasive changes on a user's machine. For example, starting an [=immersive session=] will engage the [=/XR device=] sensors, take over access to the device's display, and begin presentating immersive content which may terminate another application's access to the XR hardware. It may also incur significant power or performance overhead on some systems or trigger the launching of a status tray or storefront.

<div class="algorithm" data-algorithm="immersive-session-allowed">

To determine if an <dfn>immersive session request is allowed</dfn> the user agent MUST run the following steps:

  1. If the request was not [=triggered by user activation=] or [=launching a web application=], return <code>false</code>
  1. If the requesting document is not considered [=trustworthy=], return <code>false</code>
  1. If [=user intent=] to begin an [=immersive session=] is not well understood, either via [=explicit consent=] or [=implicit consent=], return <code>false</code>
  1. Return <code>true</code>

</div>

Starting an {{XRSessionMode/"inline"}} session does not implicitly carry the same requirements, though additional requirements may be imposed depending on the session's [=requested features=].

<div class="algorithm" data-algorithm="inline-session-allowed">

To determine if an <dfn>inline session request is allowed</dfn> the user agent MUST run the following steps:

  1. If the session request contained any [=required features=] or [=optional features=] and the request was not [=triggered by user activation=] or [=launching a web application=], return <code>false</code>
  1. If the requesting document is not [=responsible=], return <code>false</code>
  1. Return <code>true</code>

</div>

### Poses ### {#protect-poses}
When based on sensor data, {{XRPose}} and {{XRViewerPose}} will expose [=sensitive information=] that may be misused in a number of ways, including input sniffing, gaze tracking, or fingerprinting.

<div class="algorithm" data-algorithm="poses-allowed">

To determine if <dfn>poses may be reported</dfn> to an {{XRSession}} |session|, the user agent MUST run the following steps:

  1. Let |document| be the document that owns |session|.
  1. If the request does not originate from |document|, return <code>false</code>.
  1. If |document| is not [=active and focused=], return <code>false</code>.
  1. If |session|'s {{XRSession/visibilityState}} in not {{XRVisibilityState/"visible"}}, return <code>false</code>.
  1. Determine if the pose data can be returned as follows:
    <dl class="switch">
      <dt> If the pose data is known by the user agent to not expose fingerprintable sensor data
      <dd> Return <code>true</code>.
      <dt> If [=data adjustments=] will be applied to the underlying sensor data to prevent fingerprinting or profiling
      <dd> Return <code>true</code>.
      <dt> If [=user intent=] is well understood, either via [=explicit consent=] or [=implicit consent=]
      <dd> Return <code>true</code>.
      <dt> Otherwise
      <dd> Return <code>false</code>.
    </dl>

</div>

Note: The method by which a user agent determines that poses do not expose fingerprintable data is left to the user agent's discretion.

The primary difference between {{XRViewerPose}} and {{XRPose}} is the inclusion of {{XRView}} information. When more than one view is present and the physical relationship between these views is configurable by the user, the relationship between these views is considered [=sensitive information=] as it can be used to fingerprint or profile the user.

If the relationship between {{XRView}}s could uniquely identify the [=/XR device=], then the user agent MUST anonymize the {{XRView}} data to prevent fingerprinting. The method of anonymization is at the discretion of the user agent.

Note: Furthermore, if the relationship between {{XRView}}s is affected by a user-configured interpupillary distance (IPD), then it is strongly recommended that the user agent require [=explicit consent=] during session creation, prior to reporting any {{XRView}} data.

### Reference spaces ### {#protect-reference-spaces}
Depending on the reference spaces used, several different types of [=sensitive information=] may be exposed to the application.

 - On devices which support [=6DoF=] tracking, {{XRReferenceSpaceType/"local"}} reference spaces may be used to perform gait analysis, allowing user profiling and fingerprinting.

 - On devices which support [=6DoF=] tracking, {{XRReferenceSpaceType/"local-floor"}} reference spaces may be used to perform gait analysis, allowing user profiling and fingerprinting. In addition, because the {{XRReferenceSpaceType/"local-floor"}} reference spaces provide an established floor level, it may be possible for a site to infer the user's height, allowing user profiling and fingerprinting.

 - {{XRReferenceSpaceType/"bounded-floor"}} reference spaces, when sufficiently constrained in size, do not enable developers to determine geographic location. However, because the floor level is established and users are able to walk around, it may be possible for a site to infer the user's height or perform gait analysis, allowing user profiling and fingerprinting. In addition, it may be possible perform fingerprinting using the bounds reported by a bounded reference space.

 - {{XRReferenceSpaceType/"unbounded"}} reference spaces reveal the largest amount of spatial data and may result in user profiling and fingerprinting. For example, this data may enable determining user's specific geographic location or to perform gait analysis.

As a result the various reference space types have restrictions placed on their creation to ensure the [=sensitive information=] expose is handled safely:

Most reference spaces require that [=user intent=] to use the reference space is well understood, either via [=explicit consent=] or [=implicit consent=]. See the [=feature requirements=] table for details.
 
Any group of {{XRReferenceSpaceType/"local"}}, {{XRReferenceSpaceType/"local-floor"}}, and {{XRReferenceSpaceType/"bounded-floor"}} reference spaces that are capable of being related to one another MUST share a common [=native origin=]; This restriction only applies when the creation of {{XRReferenceSpaceType/"unbounded"}} reference spaces has been restricted.

<div class="algorithm" data-algorithm="poses-limited">

To determine if <dfn>poses must be limited</dfn> between two spaces, |space| and |baseSpace|, the user agent MUST run the following steps:

  1. If either |space| or |baseSpace| are an {{XRBoundedReferenceSpace}} and the other space's [=native origin=]'s falls further outside the [=native bounds geometry=] than a reasonable distance determined by the user agent, return true.
  1. If either |space| or |baseSpace| are an {{XRReferenceSpace}} with a [=XRReferenceSpace/type=] of {{XRReferenceSpaceType/"local"}} or {{XRReferenceSpaceType/"local-floor"}} and the distance between the spaces' [=native origin=]'s is greater than a reasonable distance determined by the user agent, return <code>true</code>.
  1. Return false.

</div>

Note: Is is suggested that poses reported relative to a {{XRReferenceSpaceType/"local"}} or {{XRReferenceSpaceType/"local-floor"}} reference space be [=limiting|limited=] to a distance of 15 meters from the {{XRReferenceSpace}}'s [=native origin=].

Note: Is is suggested that poses reported relative to a {{XRBoundedReferenceSpace}} be [=limiting|limited=] to a distance of 1 meter outside the {{XRBoundedReferenceSpace}}'s [=native bounds geometry=].


Trusted Environment {#trustedenvironment-security}
-------------------

A <dfn>Trusted UI</dfn> is an interface presented by the User Agent that the user is able to interact with but the page cannot. The user agent MUST support showing [=trusted UI=].

A [=trusted UI=] MUST have the following properties:

    - It must not be spoofable
    - It indicates where the request/content displayed originates from
    - If it relies on a shared secret with the user, this shared secret cannot be observed by a mixed reality capture (e.g. it may not be a gesture that can be seen by the camera)
    - It is consistent between immersive experiences in the same UA

Broadly speaking, there are two options for user agents who wish to support [=trusted UI=]. One option is <dfn>trusted immersive UI</dfn>, which is a [=trusted UI=] which does not exit immersive mode. Implementing [=trusted immersive UI=] can be challenging because `XRWebGLLayer` buffers fill the XR Device display and the User Agent does not typically "reserve" pixels for its own use. User agents are not required to support [=trusted immersive UI=], they may instead temporarily pause/exit immersive mode and show non-immersive [=trusted UI=] to the user.

<div class="note">
Note: Examples of [=trusted UI=] include:
  - The default 2D mode browser shown when not in immersive mode
  - A prompt shown within immersive mode which can only be interacted with via a reserved hardware button to prevent spoofing
  - Pausing the immersive session and showing some form of native system environment in which a prompt can be shown

</div>

The ability to read input information (head pose, input pose, etc) poses a risk to the integrity of [=trusted UI=] as the page may use this information to snoop on the choices made by the user while interacting with the [=trusted UI=]. To prevent this risk the user agent MUST set the [=visibility state=] of all {{XRSession}}s to {{XRVisibilityState/"hidden"}} when the user is interacting with [=trusted UI=] ([=trusted immersive ui|immersive=] or non-immersive) such as URL bars or system dialogs. Additionally, to prevent a malicious page from being able to monitor input on other pages the user agent MUST set the {{XRSession}}'s [=visibility state=] to {{XRVisibilityState/"hidden"}} if the [=currently focused area=] does belong to the document which created the {{XRSession}}.


The user agent MUST use [=trusted UI=] to show permissions prompts.

If the virtual environment does not consistently track the user's head motion with low latency and at a high frame rate the user may become disoriented or physically ill. Since it is impossible to force pages to produce consistently performant and correct content the user agent MUST provide a tracked, trusted environment and an [=XR Compositor=] which runs asynchronously from page content. The compositor is responsible for compositing the trusted and untrusted content. If content is not performant, does not submit frames, or terminates unexpectedly the user agent should be able to continue presenting a responsive, [=trusted UI=].

Additionally, page content has the ability to make users uncomfortable in ways not related to performance. Badly applied tracking, strobing colors, and content intended to offend, frighten, or intimidate are examples of content which may cause the user to want to quickly exit the XR experience. Removing the XR device in these cases may not always be a fast or practical option. To accommodate this the user agent MUST provide users with an action, such as pressing a reserved hardware button or performing a gesture, that escapes out of WebXR content and displays the user agent's [=trusted UI=].

<section class="unstable">


Context Isolation {#contextisolation-security}
-----------------

The trusted UI must be drawn by an independent rendering context whose state is isolated from any rendering contexts used by the page. (For example, any WebGL rendering contexts.) This is to prevent the page from corrupting the state of the trusted UI's context, which may prevent it from properly rendering a tracked environment. It also prevents the possibility of the page being able to capture imagery from the trusted UI, which could lead to private information being leaked.

Also, to prevent CORS-related vulnerabilities each page will see a new instance of objects returned by the API, such as {{XRSession}}. Attributes such as the [=XRWebGLLayer/context=] set by one page must not be able to be read by another. Similarly, methods invoked on the API MUST NOT cause an observable state change on other pages. For example: No method will be exposed that enables a system-level orientation reset, as this could be called repeatedly by a malicious page to prevent other pages from tracking properly. The user agent MUST, however, respect system-level orientation resets triggered by a user gesture or system menu.

Fingerprinting {#fingerprinting-security}
--------------

Given that the API describes hardware available to the user and its capabilities it will inevitably provide additional surface area for fingerprinting. While it's impossible to completely avoid this, user agents should take steps to mitigate the issue. This spec limits reporting of available hardware to only a single device at a time, which prevents using the rare cases of multiple headsets being connected as a fingerprinting signal. Also, the devices that are reported have no string identifiers and expose very little information about the devices capabilities until an XRSession is created, which requires additional protections when [=sensitive information=] will be exposed.
</section>

Integrations {#integrations}
============

Feature Policy {#feature-policy}
--------------

This specification defines a [=policy-controlled feature=] that controls whether any {{XRSession}} that requires the use of spatial tracking may be returned by {{XR/requestSession()}}, and whether support for session modes that require spatial tracking may be indicated by either {{XR/isSessionSupported()}} or {{devicechange}} events on the {{Navigator/xr|navigator.xr}} object.

The feature identifier for this feature is <code>"xr-spatial-tracking"</code>.

The [=default allowlist=] for this feature is <code>["self"]</code>.

Note: If the document's origin is not allowed to use the <code>"xr-spatial-tracking"</code> feature policy any [=immersive sessions=] will be blocked, because all [=immersive sessions=] require some use of spatial tracking. [=Inline sessions=] will still be allowed, but restricted to only using the {{XRReferenceSpaceType/"viewer"}} {{XRReferenceSpace}}.

Acknowledgements {#ack}
================

The following individuals have contributed to the design of the WebXR Device API specification:

  * <a href="mailto:cvan@mozilla.com">Chris Van Wiemeersch</a> (<a href="https://mozilla.org/">Mozilla</a>)
  * <a href="mailto:kgilbert@mozilla.com">Kearwood Gilbert</a> (<a href="https://mozilla.org/">Mozilla</a>)
  * <a href="mailto:rafael.cintron@microsoft.com">Rafael Cintron</a> (<a href="https://microsoft.com/">Microsoft</a>)
  * <a href="mailto:sebastian.sylvan@gmail.com">Sebastian Sylvan</a> (Formerly <a href="https://microsoft.com/">Microsoft</a>)

And a special thanks to <a href="mailto:vladv@unity3d.com">Vladimir Vukicevic</a> (<a href="https://unity3d.com/">Unity</a>) for kick-starting this whole adventure!

</section>
