• Stars
    star
    1,890
  • Rank 23,591 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🤳 VR/AR with react-three-fiber

@react-three/xr

Version Downloads Discord Shield

React components and hooks for creating VR/AR applications with @react-three/fiber

npm install @react-three/xr

Examples

These demos are real, you can click them! They contain the full code, too.

Getting started

The following adds a button to start your session and controllers inside an XR manager to prepare your scene for WebXR rendering and interaction.

import { VRButton, ARButton, XR, Controllers, Hands } from '@react-three/xr'
import { Canvas } from '@react-three/fiber'

function App() {
  return (
    <>
      <VRButton />
      <Canvas>
        <XR>
          <Controllers />
          <Hands />
          <mesh>
            <boxGeometry />
            <meshBasicMaterial color="blue" />
          </mesh>
        </XR>
      </Canvas>
    </>
  )
}

XRButton

<XRButton /> is an HTML <button /> that can be used to init and display info about your WebXR session. This is aliased by ARButton and VRButton with sensible session defaults.

<XRButton
  /* The type of `XRSession` to create */
  mode={'AR' | 'VR' | 'inline'}
  /**
   * `XRSession` configuration options
   * @see https://immersive-web.github.io/webxr/#feature-dependencies
   */
  sessionInit={{ optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking', 'layers'] }}
  /** Whether this button should only enter an `XRSession`. Default is `false` */
  enterOnly={false}
  /** Whether this button should only exit an `XRSession`. Default is `false` */
  exitOnly={false}
  /** This callback gets fired if XR initialization fails. */
  onError={(error) => ...}
>
  {/* Can accept regular DOM children and has an optional callback with the XR button status (unsupported, exited, entered) */}
  {(status) => `WebXR ${status}`}
</XRButton>

XR

<XR /> is a WebXR manager that configures your scene for XR rendering and interaction. This lives within a R3F <Canvas />.

<Canvas>
  <XR
    /**
     * Enables foveated rendering. Default is `0`
     * 0 = no foveation, full resolution
     * 1 = maximum foveation, the edges render at lower resolution
     */
    foveation={0}
    /**
     * The target framerate for the XRSystem. Smaller rates give more CPU headroom at the cost of responsiveness.
     * Recommended range is `72`-`120`. Default is unset and left to the device.
     * @note If your experience cannot effectively reach the target framerate, it will be subject to frame reprojection
     * which will halve the effective framerate. Choose a conservative estimate that balances responsiveness and
     * headroom based on your experience.
     * @see https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Rendering#refresh_rate_and_frame_rate
    */
    frameRate={72 | 90 | 120}
    /** Type of WebXR reference space to use. Default is `local-floor` */
    referenceSpace="local-floor"
    /** Called as an XRSession is requested */
    onSessionStart={(event: XREvent<XRManagerEvent>) => ...}
    /** Called after an XRSession is terminated */
    onSessionEnd={(event: XREvent<XRManagerEvent>) => ...}
    /** Called when an XRSession is hidden or unfocused. */
    onVisibilityChange={(event: XREvent<XRSessionEvent>) => ...}
    /** Called when available inputsources change */
    onInputSourcesChange={(event: XREvent<XRSessionEvent>) => ...}
  >
    {/* All your regular react-three-fiber elements go here */}
  </XR>
</Canvas>

useXR

This hook gives you access to the current XRState configured by <XR />.

const {
  // An array of connected `XRController`
  controllers,
  // Whether the XR device is presenting in an XR session
  isPresenting,
  // Whether hand tracking inputs are active
  isHandTracking,
  // A THREE.Group representing the XR viewer or player
  player,
  // The active `XRSession`
  session,
  // `XRSession` foveation. This can be configured as `foveation` on <XR>. Default is `0`
  foveation,
  // `XRSession` reference-space type. This can be configured as `referenceSpace` on <XR>. Default is `local-floor`
  referenceSpace
} = useXR()

To subscribe to a specific key, useXR accepts a Zustand selector:

const player = useXR((state) => state.player)

Controllers

Controllers can be added with <Controllers /> for motion-controllers and/or <Hands /> for hand-tracking. These will activate whenever their respective input mode is enabled on-device and provide live models for a left and right XRController.

<Controllers
  /** Optional material props to pass to controllers' ray indicators */
  rayMaterial={{ color: 'blue' }}
  /** Whether to hide controllers' rays on blur. Default is `false` */
  hideRaysOnBlur={false}
/>
<Hands
  // Optional custom models per hand. Default is the Oculus hand model
  modelLeft="/model-left.glb"
  modelRight="/model-right.glb"
/>

useController

useController references an XRController by handedness, exposing position and orientation info.

const leftController = useController('left')
const rightController = useController('right')
const gazeController = useController('none')

XRController

XRController is an Object3D that represents an XRInputSource with the following properties:

index: number
controller: THREE.XRTargetRaySpace
grip: THREE.XRGripSpace
hand: THREE.XRHandSpace
inputSource: XRInputSource

Interactions

To interact with objects using controllers you can use <Interactive /> component or useInteraction hook. They allow adding controller event handlers to your objects.

Interactive

<Interactive /> wraps your objects and accepts XR controller event handlers as props. Supports select, hover, blur and squeeze events (see XR inputsources).

<Interactive
  /* Called when hovered by a controller */
  onHover={(event: XRInteractionEvent) => ...}
  /* Called when unhovered by a controller */
  onBlur={(event: XRInteractionEvent) => ...}
  /* Called on button press when selected by a controller */
  onSelectStart={(event: XRInteractionEvent) => ...}
  /* Called on button release when selected by a controller */
  onSelectEnd={(event: XRInteractionEvent) => ...}
  /* Called on button release when another interactive is selected by a controller */
  onSelectMissed={(event: XRInteractionEvent) => ...}
  /* Called when selected by a controller */
  onSelect={(event: XRInteractionEvent) => ...}
  /* Called on button press when squeezed by a controller */
  onSqueezeStart={(event: XRInteractionEvent) => ...}
  /* Called on button release when squeezed by a controller */
  onSqueezeEnd={(event: XRInteractionEvent) => ...}
  /* Called on button release when another interactive is squeezed by a controller */
  onSqueezeMissed={(event: XRInteractionEvent) => ...}
  /* Called when squeezed by a controller */
  onSqueeze={(event: XRInteractionEvent) => ...}
  /* Called when a controller moves over the object, equivalent to pointermove */
  onMove={(event: XRInteractionEvent) => ...}
>
  <Box />
</Interactive>

RayGrab

<RayGrab /> is a specialized <Interactive /> that can be grabbed and moved by controllers.

<RayGrab>
  <Box />
</RayGrab>

useInteraction

useInteraction subscribes an existing element to controller events.

The following interaction events are supported: onHover, onBlur, onSelect, onSelectEnd, onSelectStart, onSelectMissed, onSqueeze, onSqueezeEnd, onSqueezeStart, onSqueezeMissed, onMove.

const boxRef = useRef()
useInteraction(boxRef, 'onSelect', (event: XRInteractionEvent) => ...)

<Box ref={boxRef} />

useHitTest

Use this hook to perform a hit test for an AR environment. Also see XRHitTestResult.

useHitTest((hitMatrix: Matrix4, hit: XRHitTestResult) => {
  // use hitMatrix to position any object on the real life surface
  hitMatrix.decompose(mesh.position, mesh.quaternion, mesh.scale)
})

useXREvent

To handle controller events that are not bound to any object in the scene you can use useXREvent hook. This is a low-level abstraction that subscribes directly into the native XRInputSource (see XRInputSourceEvent).

useXREvent('squeeze', (event: XRControllerEvent) => ...)

It supports an optional third parameter with options for filtering by handedness.

useXREvent('squeeze', (event: XRControllerEvent) => ..., { handedness: 'left' | 'right' | 'none' })

Custom XRButton

While you can customize XRButton, there's a way to shave off react-dom and customize it even more. For this there's a couple of low-level utilities of a headless xr button: startSession, stopSession and toggleSession.

import { toggleSession } from '@react-three/xr'

const handleClick = async () => {
  const session = await toggleSession('immersive-vr')
  if (session) {
    button.innerText = 'Exit VR'
  } else {
    button.innerText = 'Enter VR'
  }
}

const button = document.createElement('button')
button.innerText = 'Enter VR'
button.addEventListener('click', handleClick)
document.appendChild(button)

Built with react-xr

  • Avatar Poser github link

More Repositories

1

zustand

🐻 Bear necessities for state management in React
TypeScript
40,808
star
2

react-spring

✌️ A spring physics based React animation library
TypeScript
27,160
star
3

react-three-fiber

🇨🇭 A React renderer for Three.js
TypeScript
25,320
star
4

jotai

👻 Primitive and flexible state management for React
TypeScript
16,893
star
5

use-gesture

👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
TypeScript
8,537
star
6

valtio

💊 Valtio makes proxy-state simple for React and Vanilla
TypeScript
8,257
star
7

drei

🥉 useful helpers for react-three-fiber
JavaScript
7,122
star
8

leva

🌋 React-first components GUI
TypeScript
4,528
star
9

gltfjsx

🎮 Turns GLTFs into JSX components
JavaScript
3,949
star
10

use-cannon

👋💣 physics based hooks for @react-three/fiber
TypeScript
2,654
star
11

react-three-next

React Three Fiber, Threejs, Nextjs starter
JavaScript
2,140
star
12

postprocessing

A post processing library for three.js.
JavaScript
2,100
star
13

racing-game

🏎 Open source racing game developed by everyone willing
TypeScript
2,094
star
14

react-three-flex

💪📦 Flexbox for react-three-fiber
TypeScript
1,606
star
15

suspend-react

🚥 Async/await for React components
TypeScript
1,308
star
16

react-postprocessing

📬 postprocessing for react-three-fiber
JavaScript
1,009
star
17

detect-gpu

Classifies GPUs based on their 3D rendering benchmark score allowing the developer to provide sensible default settings for graphically intensive applications.
TypeScript
979
star
18

lamina

🍰 An extensible, layer based shader material for ThreeJS
TypeScript
976
star
19

its-fine

🐶🔥 A collection of escape hatches for React.
TypeScript
891
star
20

react-use-measure

🙌 Utility to measure view bounds
TypeScript
799
star
21

react-nil

⃝ A react null renderer
TypeScript
772
star
22

react-three-rapier

🤺 Rapier physics in React
TypeScript
765
star
23

maath

🪶 Math helpers for the rest of us
TypeScript
755
star
24

threejs-journey

⚛️ Bruno Simons journey demos in React
TypeScript
685
star
25

three-stdlib

📚 Stand-alone library of threejs examples designed to run without transpilation in node & browser
JavaScript
624
star
26

react-three-editor

🔌 A one of a kind scene editor that writes changes back into your code
TypeScript
602
star
27

react-three-a11y

♿️ Accessibility tools for React Three Fiber
TypeScript
507
star
28

react-zdog

⚡️🐶 React bindings for zdog
JavaScript
441
star
29

use-asset

📦 A promise caching strategy for React Suspense
TypeScript
414
star
30

react-three-offscreen

📺 Offscreen worker canvas for react-three-fiber
TypeScript
397
star
31

drei-vanilla

🍦 drei-inspired helpers for threejs
TypeScript
364
star
32

ecctrl

🕹️ A floating rigibody character controller
TypeScript
349
star
33

tunnel-rat

🐀 Non gratum anus rodentum
TypeScript
287
star
34

react-three-lgl

🔆 A React abstraction for the LGL Raycaster
TypeScript
260
star
35

market

📦 Download CC0 assets ready to use in your next 3D Project
JavaScript
249
star
36

react-three-csg

🚧 Constructive solid geometry for React
TypeScript
242
star
37

gltf-react-three

Convert GLTF files to React Three Fiber Components
JavaScript
230
star
38

component-material

🧩 Compose modular materials in React
TypeScript
161
star
39

env

💄 An app to create, edit, and preview HDR environment maps in the browser
TypeScript
143
star
40

use-p2

👋💣 2d physics hooks for @react-three/fiber
TypeScript
141
star
41

react-ogl

🦴 A barebones react renderer for ogl.
TypeScript
139
star
42

react-spring-examples

JavaScript
138
star
43

react-three-gpu-pathtracer

⚡️ A React abstraction for the popular three-gpu-pathtracer
TypeScript
125
star
44

react-three-lightmap

In-browser lightmap/AO baker for react-three-fiber and ThreeJS
TypeScript
123
star
45

cannon-es-debugger

Wireframe debugger for use with cannon-es https://github.com/react-spring/cannon-es
HTML
103
star
46

rafz

💍 One loop to frame them all.
TypeScript
96
star
47

website

Poimandres developer collective website
JavaScript
87
star
48

swc-jotai

Rust
85
star
49

assets

📦 Importable base64 encoded CC0 assets
Makefile
84
star
50

react-three-scissor

✂ Multiple scenes, one canvas! WebGL Scissoring implementation for React Three Fiber.
TypeScript
81
star
51

eslint-plugin-valtio

An eslint plugin for better valtio experience
JavaScript
69
star
52

react-spring.io

✌️ A spring physics based React animation library
TypeScript
56
star
53

react-three-babel

🛍 A Babel plugin that automatically builds the extend catalogue of known native Three.js elements
TypeScript
53
star
54

r3f-website

Website for React Three Fiber
JavaScript
26
star
55

market-assets

JavaScript
19
star
56

react-three-8thwall

JavaScript
17
star
57

drei-assets

JavaScript
16
star
58

discord

🤖 Poimandres Discord Bot
TypeScript
10
star
59

react-three-jolt

⚡ Jolt physics in React
CSS
10
star
60

branding

TypeScript
7
star
61

market-assets-do

JavaScript
5
star
62

envinfo

Easily collect useful information for bug reports
JavaScript
4
star
63

leva-wg

1
star