zehfernandes / drei

πŸ₯‰ useful helpers for react-three-fiber

Home Page:https://drei.pmnd.rs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

logo

Version Downloads Discord Shield

A growing collection of useful helpers and fully functional, ready-made abstractions for react-three-fiber. If you make a component that is generic enough to be useful to others, think about making it available here through a PR!

npm install @react-three/drei

πŸ‘‰ this package is using the stand-alone three-stdlib instead of three/examples/jsm. πŸ‘ˆ

Basic usage:

import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei'

React-native:

import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei/native'

The native route of the library does not export Html or Loader. The default export of the library is web which does export Html and Loader.

Index

Cameras

PerspectiveCamera

A responsive THREE.PerspectiveCamera that can set itself as the default.

<PerspectiveCamera makeDefault {...props} />
<mesh />

You can also give it children, which will now occupy the same position as the camera and follow along as it moves.

<PerspectiveCamera makeDefault {...props}>
  <mesh />
</PerspectiveCamera>

You can also drive it manually, it won't be responsive and you have to calculate aspect ration yourself.

<PerspectiveCamera manual aspect={...} onUpdate={(c) => c.updateProjectionMatrix()}>

OrthographicCamera

A responsive THREE.OrthographicCamera that can set itself as the default.

<OrthographicCamera makeDefault {...props}>
  <mesh />
</OrthographicCamera>

CubeCamera

A THREE.CubeCamera that returns its texture as a render-prop. It makes children invisible while rendering to the internal buffer so that they are not included in the reflection.

Using the frames prop you can control if this camera renders indefinitively or statically (a given number of times). If you have two static objects in the scene, make it frames={2} for instance, so that both objects get to "see" one another in the reflections, which takes multiple renders. If you have moving objects, unset the prop and use a smaller resolution instead.

<CubeCamera resolution={256} frames={Infinity} fog={customFog} near={1} far={1000}>
  {(texture) => (
    <mesh>
      <sphereGeometry />
      <meshStandardMaterial envMap={texture} />
    </mesh>
  )}
</CubeCamera>

Controls

If available controls have damping enabled by default, they manage their own updates, remove themselves on unmount, are compatible with the invalidateFrameloop canvas-flag. They inherit all props from their underlying THREE controls.

Some controls allow you to set makeDefault, similar to, for instance, PerspectiveCamera. This will set react-three-fiber's controls field in the root store. This can make it easier in situations where you want controls to be known and other parts of the app could respond to it. Some drei controls already take it into account, like CameraShake, Gizmo and TransformControls.

Drei currently exports OrbitControls , MapControls , TrackballControls, ArcballControls, FlyControls, DeviceOrientationControls, PointerLockControls , FirstPersonControls

All controls react to the default camera. If you have a <PerspectiveCamera makeDefault /> in your scene, they will control it. If you need to inject an imperative camera or one that isn't the default, use the camera prop: <OrbitControls camera={MyCamera} />.

PointerLockControls additionally supports a selector prop, which enables the binding of click event handlers for control activation to other elements than document (e.g. a 'Click here to play' button). All elements matching the selector prop will activate the controls. It will also center raycast events by default, so regular onPointerOver/etc events on meshes will continue to work.

TransformControls

Tranform controls

An abstraction around THREE.TransformControls.

You can wrap objects which then receive a transform gizmo.

<TransformControls mode="translate">
  <mesh />
</TransformControls>

You could also reference the object which might make it easier to exchange the target. Now the object does not have to be part of the same sub-graph. References can be plain objects or React.MutableRefObjects.

<TransformControls object={mesh} mode="translate">
<mesh ref={mesh} />

If you are using other controls (Orbit, Trackball, etc), you will notice how they interfere, dragging one will affect the other. Default-controls will temporarily be disabled automatically when the user is pulling on the transform gizmo.

<TransformControls mode="translate" />
<OrbitControls makeDefault />

ScrollControls

Horizontal tiles M1 scroll useIntersect Infinite scroll Vertical scroll GLTF and useScroll

Scroll controls create a HTML scroll container in front of the canvas. Everything you drop into the <Scroll> component will be affected.

You can listen and react to scroll with the useScroll hook which gives you useful data like the current scroll offset, delta and functions for range finding: range, curve and visible. The latter functions are especially useful if you want to react to the scroll offset, for instance if you wanted to fade things in and out if they are in or out of view.

<ScrollControls
  pages={3} // Each page takes 100% of the height of the canvas
  distance={1} // A factor that increases scroll bar travel (default: 1)
  damping={4} // Friction, higher is faster (default: 4)
  horizontal={false} // Can also scroll horizontally (default: false)
  infinite={false} // Can also scroll infinitely (default: false)
>
  {/* You can have components in here, they are not scrolled, but they can still
      react to scroll by using useScroll! */}
  <Scroll>
    <Foo position={[0, 0, 0]} />
    <Foo position={[0, viewport.height, 0]} />
    <Foo position={[0, viewport.height * 1, 0]} />
  </Scroll>
  <Scroll html>
    <h1>html in here (optional)</h1>
    <h1 style={{ top: '100vh' }}>second page</h1>
    <h1 style={{ top: '200vh' }}>third page</h1>
  </Scroll>
</ScrollControls>

function Foo(props) {
  const ref = useRef()
  const data = useScroll()
  useFrame(() => {
    // data.offset = current scroll position, between 0 and 1, dampened
    // data.delta = current delta, between 0 and 1, dampened

    // Will be 0 when the scrollbar is at the starting position,
    // then increase to 1 until 1 / 3 of the scroll distance is reached
    const a = data.range(0, 1 / 3)
    // Will start increasing when 1 / 3 of the scroll distance is reached,
    // and reach 1 when it reaches 2 / 3rds.
    const b = data.range(1 / 3, 1 / 3)
        // Same as above but with a margin of 0.1 on both ends
    const c = data.range(1 / 3, 1 / 3, 0.1)
    // Will move between 0-1-0 for the selected range
    const d = data.curve(1 / 3, 1 / 3)
    // Same as above, but with a margin of 0.1 on both ends
    const d = data.curve(1 / 3, 1 / 3, 0.1)
    // Returns true if the offset is in range and false if it isn't
    const e = data.visible(2 / 3, 1 / 3)
    // The visible function can also receive a margin
    const f = data.visible(2 / 3, 1 / 3, 0.1)
  })
  return <mesh ref={ref} {...props} />

PresentationControls

Journey stage 1 Watch

Semi-OrbitControls with spring-physics, polar zoom and snap-back, for presentational purposes. These controls do not turn the camera but will spin their contents. They will not suddenly come to rest when they reach limits like OrbitControls do, but rather smoothly anticipate stopping position.

<PresentationControls
  global={false} // Spin globally or by dragging the model
  cursor={true} // Whether to toggle cursor style on drag
  snap={false} // Snap-back to center (can also be a spring config)
  speed={1} // Speed factor
  zoom={1} // Zoom factor when half the polar-max is reached
  rotation={[0, 0, 0]} // Default rotation
  polar={[0, Math.PI / 2]} // Vertical limits
  azimuth={[-Infinity, Infinity]} // Horizontal limits
  config = { mass: 1, tension: 170, friction: 26 } // Spring config
>
  <mesh />
</PresentationControls>

Shapes

Buffer-geometry short-cuts for Plane, Box, Sphere, Circle, Cone, Cylinder, Tube, Torus, TorusKnot, Ring, Tetrahedron, Polyhedron, Icosahedron, Octahedron, Dodecahedron, Extrude, Lathe.

<Plane args={[2, 2]} />
<Sphere>
  <meshBasicMaterial attach="material" color="hotpink" />
</Sphere>

RoundedBox

A box buffer geometry with rounded corners, done with extrusion.

<RoundedBox args={[1, 1, 1]} radius={0.05} smoothness={4} {...meshProps}>
  <meshPhongMaterial attach="material" color="#f3f3f3" wireframe />
</RoundedBox>

ScreenQuad

<ScreenQuad>
  <myMaterial />
</ScreenQuad>

A triangle that fills the screen, ideal for full-screen fragment shader work (raymarching, postprocessing). πŸ‘‰ Why a triangle? πŸ‘‰ Use as a post processing mesh

Abstractions

Image

Horizontal tiles useIntersect Infinite scroll Vertical scroll

A shader-based image component with auto-cover (similar to css/background: cover).

function Foo() {
  const ref = useRef()
  useFrame(() => {
    ref.current.material.zoom = ... // 1 and higher
    ref.current.material.grayscale = ... // between 0 and 1
    ref.current.material.color.set(...) // mix-in color
  })
  return <Image ref={ref} url="/file.jpg" />

Text

Demo

Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text. All of troikas props are valid!

<Text color="black" anchorX="center" anchorY="middle">
  hello world!
</Text>

Text will suspend while loading the font data, but in order to completely avoid FOUC you can pass the characters it needs to render.

<Text font={fontUrl} characters="abcdefghijklmnopqrstuvwxyz0123456789!">
  hello world!
</Text>

Line

Renders a THREE.Line2.

<Line
  points={[[0, 0, 0], ...]}       // Array of points
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

QuadraticBezierLine

Demo

Renders a THREE.Line2 using THREE.QuadraticBezierCurve3 for interpolation.

<QuadraticBezierLine
  start={[0, 0, 0]}               // Starting point, can be an array or a vec3
  end={[10, 0, 10]}               // Ending point, can be an array or a vec3
  mid={[5, 0, 5]}                 // Optional control point, can be an array or a vec3
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

You can also update the line runtime.

const ref = useRef()
useFrame((state) => {
  ref.current.setPoints(
    [0, 0, 0],
    [10, 0, 0],
    // [5, 0, 0] // Optional: mid-point
  )
}, [])
return <QuadraticBezierLine ref={ref} />
}

CubicBezierLine

Renders a THREE.Line2 using THREE.CubicBezierCurve3 for interpolation.

<CubicBezierLine
  start={[0, 0, 0]}               // Starting point
  end={[10, 0, 10]}               // Ending point
  midA={[5, 0, 0]}                // First control point
  midB={[0, 0, 5]}                // Second control point
  color="black"                   // Default
  lineWidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>

PositionalAudio

Demo

A wrapper around THREE.PositionalAudio. Add this to groups or meshes to tie them to a sound that plays when the camera comes near.

<PositionalAudio
  url="/sound.mp3"
  distance={1}
  loop
  {...props} // All THREE.PositionalAudio props are valid
/>

Billboard

Adds a <group /> that always faces the camera.

<Billboard
  follow={true}
  lockX={false}
  lockY={false}
  lockZ={false} // Lock the rotation on the z axis (default=false)
>
  <Text fontSize={1}>I'm a billboard</Text>
</Billboard>

GizmoHelper

Used by widgets that visualize and control camera position.

Two example gizmos are included: GizmoViewport and GizmoViewcube, and useGizmoContext makes it easy to create your own.

Make sure to set the makeDefault prop on your controls, in that case you do not have to define the onTarget and onUpdate props.

<GizmoHelper
  alignment="bottom-right" // widget alignment within scene
  margin={[80, 80]} // widget margins (X, Y)
  onUpdate={/* called during camera animation  */}
  onTarget={/* return current camera target (e.g. from orbit controls) to center animation */}
  renderPriority={/* use renderPriority to prevent the helper from disappearing if there is another useFrame(..., 1)*/}
>
  <GizmoViewport axisColors={['red', 'green', 'blue']} labelColor="black" />
  {/* alternative: <GizmoViewcube /> */}
</GizmoHelper>

Effects

Abstraction around threes own EffectComposer.

<Effects multisamping={8} renderIndex={1} disableGamma={false} disableRenderPass={false}>
  <lUTPass attachArray="passes" lut={texture3D} />
</Effects>

GradientTexture

Demo

A declarative THREE.Texture which attaches to "map" by default. You can use this to create gradient backgrounds.

<mesh>
  <planeGeometry />
  <meshBasicMaterial>
    <GradientTexture
      stops={[0, 1]} // As many stops as you want
      colors={['aquamarine', 'hotpink']} // Colors need to match the number of stops
      size={1024} // Size is optional, default = 1024
    />
  </meshBasicMaterial>
</mesh>

Edges

Demo

Abstracts THREE.EdgesGeometry. It pulls the geometry automatically from its parent, optionally you can ungroup it and give it a geometry prop. You can give it children, for instance a custom material.

<mesh>
  <boxGeometry />
  <meshBasicMaterial />
  <Edges
    scale={1.1}
    threshold={15} // Display edges only when the angle between two faces exceeds this value (default=15 degrees)
    color="white"
  />
</mesh>

useAnimations

Demo

A hook that abstracts AnimationMixer.

const { nodes, materials, animations } = useGLTF(url)
const { ref, mixer, names, actions, clips } = useAnimations(animations)
useEffect(() => {
  actions?.jump.play()
})
return (
  <mesh ref={ref} />

The hook can also take a pre-existing root (which can be a plain object3d or a reference to one):

const { scene, animations } = useGLTF(url)
const { actions } = useAnimations(animations, scene)
return <primitive object={scene} />

Shaders

MeshReflectorMaterial

Demo Demo

Easily add reflections and/or blur to any mesh. It takes surface roughness into account for a more realistic effect. This material extends from THREE.MeshStandardMaterial and accepts all its props.

<mesh>
  <planeGeometry />
  <MeshReflectorMaterial
    blur={[0, 0]} // Blur ground reflections (width, heigt), 0 skips blur
    mixBlur={0} // How much blur mixes with surface roughness (default = 1)
    mixStrength={1} // Strength of the reflections
    mixContrast={1} // Contrast of the reflections
    resolution={256} // Off-buffer resolution, lower=faster, higher=better quality, slower
    mirror={0} // Mirror environment, 0 = texture colors, 1 = pick up env colors
    depthScale={0} // Scale the depth factor (0 = no depth, default = 0)
    minDepthThreshold={0.9} // Lower edge for the depthTexture interpolation (default = 0)
    maxDepthThreshold={1} // Upper edge for the depthTexture interpolation (default = 0)
    depthToBlurRatioBias={0.25} // Adds a bias factor to the depthTexture before calculating the blur amount [blurFactor = blurTexture * (depthTexture + bias)]. It accepts values between 0 and 1, default is 0.25. An amount > 0 of bias makes sure that the blurTexture is not too sharp because of the multiplication with the depthTexture
    distortion={1} // Amount of distortion based on the distortionMap texture
    distortionMap={distortionTexture} // The red channel of this texture is used as the distortion map. Default is null
    debug={0} /* Depending on the assigned value, one of the following channels is shown:
      0 = no debug
      1 = depth channel
      2 = base channel
      3 = distortion channel
      4 = lod channel (based on the roughness)
    */
   reflectorOffset={0.2} // Offsets the virtual camera that projects the reflection. Useful when the reflective surface is some distance from the object's origin (default = 0)
  >
</mesh>

MeshWobbleMaterial

This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.

<mesh>
  <boxBufferGeometry attach="geometry" />
  <MeshWobbleMaterial attach="material" factor={1} speed={10} />
</mesh>

MeshDistortMaterial

Demo

This material makes your geometry distort following simplex noise.

<mesh>
  <boxBufferGeometry attach="geometry" />
  <MeshDistortMaterial attach="material" distort={1} speed={10} />
</mesh>

PointMaterial

Antialiased round dots. It takes the same props as regular THREE.PointsMaterial

<points>
  <PointMaterial scale={20} />
</points>

softShadows

Demo

Injects percent closer soft shadows (pcss) into threes shader chunk.

softShadows({
  frustum: 3.75,
  size: 0.005,
  near: 9.5,
  samples: 17,
  rings: 11, // Rings (default: 11) must be a int
})

shaderMaterial

Demo

Creates a THREE.ShaderMaterial for you with easier handling of uniforms, which are also automatically declared as setter/getters on the object.

import { extend } from 'react-three-fiber'
import glsl from 'babel-plugin-glsl/macro'

const ColorShiftMaterial = shaderMaterial(
  { time: 0, color: new THREE.Color(0.2, 0.0, 0.1) },
  // vertex shader
  glsl`
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  // fragment shader
  glsl`
    uniform float time;
    uniform vec3 color;
    varying vec2 vUv;
    void main() {
      gl_FragColor.rgba = vec4(0.5 + 0.3 * sin(vUv.yxx + time) + color, 1.0);
    }
  `
)

extend({ ColorShiftMaterial })

// in your component
<mesh>
  <colorShiftMaterial attach="material" color="hotpink" time={1} />
</mesh>

Modifiers

CurveModifier

Given a curve will replace the children of this component with a mesh that move along said curve calling the property moveAlongCurve on the passed ref. Uses three's Curve Modifier

const curveRef = useRef()

const curve = React.useMemo(() => new THREE.CatmullRomCurve3([...handlePos], true, 'centripetal'), [handlePos])

return (
  <CurveModifier ref={curveRef} curve={curve}>
    <mesh>
      <boxBufferGeometry args={[10, 10]} />
    </mesh>
  </CurveModifier>
)

Misc

useContextBridge

Allows you to forward contexts provided above the <Canvas /> to be consumed from within the <Canvas /> normally

function SceneWrapper() {
  // bridge any number of contexts
  // Note: These contexts must be provided by something above this SceneWrapper component
  //       You cannot render the providers for these contexts inside this component
  const ContextBridge = useContextBridge(ThemeContext, GreetingContext)
  return (
    <Canvas>
      <ContextBridge>
        <Scene />
      </ContextBridge>
    </Canvas>
  )
}

function Scene() {
  // we can now consume a context within the Canvas
  const theme = React.useContext(ThemeContext)
  const greeting = React.useContext(GreetingContext)
  return (
    //...
  )
}

Html

Demo Demo Demo

Allows you to tie HTML content to any object of your scene. It will be projected to the objects whereabouts automatically.

<Html
  as='div' // Wrapping element (default: 'div')
  wrapperClass // The className of the wrapping element (default: undefined)
  prepend // Project content behind the canvas (default: false)
  center // Adds a -50%/-50% css transform (default: false) [ignored in transform mode]
  fullscreen // Aligns to the upper-left corner, fills the screen (default:false) [ignored in transform mode]
  distanceFactor={10} // If set (default: undefined), children will be scaled by this factor, and also by distance to a PerspectiveCamera / zoom by a OrthographicCamera.
  zIndexRange={[100, 0]} // Z-order range (default=[16777271, 0])
  portal={domnodeRef} // Reference to target container (default=undefined)
  transform // If true, applies matrix3d transformations (default=false)
  sprite // Renders as sprite, but only in transform mode (default=false)
  calculatePosition={(el: Object3D, camera: Camera, size: { width: number; height: number }) => number[]} // Override default positioning function. (default=undefined) [ignored in transform mode]
  occlude={[ref]} // Can be true or a Ref<Object3D>[], true occludes the entire scene (default: undefined)
  onOcclude={(visible) => null} // Callback when the visibility changes (default: undefined)
  {...groupProps} // All THREE.Group props are valid
  {...divProps} // All HTMLDivElement props are valid
>
  <h1>hello</h1>
  <p>world</p>
</Html>

Html can hide behind geometry using the occlude prop.

// Raytrace the entire scene
<Html occlude />
// Raytrace only specific elements
<Html occlude={[ref1, ref2]} />

When the Html object hides it sets the opacity prop on the innermost div. If you want to animate or control the transition yourself then you can use onOcclude.

const [hidden, set] = useState()

<Html
  occlude
  onOcclude={set}
  style={{
    transition: 'all 0.5s',
    opacity: hidden ? 0 : 1,
    transform: `scale(${hidden ? 0.5 : 1})`
  }} />

CycleRaycast

Demo

This component allows you to cycle through all objects underneath the cursor with optional visual feedback. This can be useful for non-trivial selection, CAD data, housing, everything that has layers. It does this by changing the raycasters filter function and then refreshing the raycaster.

For this to work properly your event handler have to call event.stopPropagation(), for instance in onPointerOver or onClick, only one element can be selective for cycling to make sense.

<CycleRaycast
  preventDefault={true} // Call event.preventDefault() (default: true)
  scroll={true} // Wheel events (default: true)
  keyCode={9} // Keyboard events (default: 9 [Tab])
  onChanged={(objects, cycle) => console.log(objects, cycle)} // Optional onChanged event
/>

Select

Demo

This component allows you to select/unselect objects by clicking on them. It keeps track of the currently selected objects and can select multiple objects (with the shift key). Nested components can request the current selection (which is always an array) with the useSelect hook. With the box prop it will let you shift-box-select objects by holding and draging the cursor over multiple objects. Optionally you can filter the selected items as well as define in which shape they are stored by defining the filter prop.

<Select box multiple onChange={console.log} filter={items => items}>
  <Foo />
  <Bar />
</Select>

function Foo() {
  const selected = useSelect()

Stats

Adds stats to document.body. It takes over the render-loop!

<Stats showPanel={0} className="stats" {...props} />

You can choose to mount Stats to a different DOM Element - for example, for custom styling:

const node = useRef(document.createElement('div'))

useEffect(() => {
  node.current.id = 'test'
  document.body.appendChild(node.current)

  return () => document.body.removeChild(node.current)
}, [])

return <Stats parent={parent} />

useDepthBuffer

Renders the scene into a depth-buffer. Often effects depend on it and this allows you to render a single buffer and share it, which minimizes the performance impact. It returns the buffer's depthTexture.

Since this is a rather expensive effect you can limit the amount of frames it renders when your objects are static. For instance making it render only once by setting frames: 1.

const depthBuffer = useDepthBuffer({
  size: 256, // Size of the FBO, 256 by default
  frames: Infinity, // How many frames it renders, Infinity by default
})
return <SomethingThatNeedsADepthBuffer depthBuffer={depthBuffer} />

useFBO

Creates a THREE.WebGLRenderTarget or THREE.WebGLMultisampleRenderTarget.

const target = useFBO({
  multisample: true,
  stencilBuffer: false,
})

The rendertarget is automatically disposed when unmounted.

useCamera

Demo

A hook for the rare case when you are using non-default cameras for heads-up-displays or portals, and you need events/raytracing to function properly (raycasting uses the default camera otherwise).

<mesh raycast={useCamera(customCamera)} />

useHelper

A hook for a quick way to add helpers to existing nodes in the scene. It handles removal of the helper on unmount and auto-updates it by default.

const mesh = useRef()
useHelper(mesh, BoxHelper, 'cyan')
useHelper(condition && mesh, BoxHelper, 'red') // you can passe false instead of the object ref to hide the helper

<mesh ref={mesh} ... />

useDetectGPU

This hook uses DetectGPU by @TimvanScherpenzeel, wrapped into suspense, to determine what tier should be assigned to the user's GPU.

πŸ‘‰ This hook CAN be used outside the react-three-fiber Canvas.

function App() {
  const GPUTier = useDetectGPU()
  // show a fallback for mobile or lowest tier GPUs
  return (
    {(GPUTier.tier === "0" || GPUTier.isMobile) ? <Fallback /> : <Canvas>...</Canvas>

<Suspense fallback={null}>
  <App />

useAspect

This hook calculates aspect ratios (for now only what in css would be image-size: cover is supported). You can use it to make an image fill the screen. It is responsive and adapts to viewport resize. Just give the hook the image bounds in pixels. It returns an array: [width, height, 1].

const scale = useAspect(
  1024,                     // Pixel-width
  512,                      // Pixel-height
  1                         // Optional scaling factor
)
return (
  <mesh scale={scale}>
    <planeBufferGeometry />
    <meshBasicMaterial map={imageTexture} />

useCursor

A small hook that sets the css body cursor according to the hover state of a mesh, so that you can give the use visual feedback when the mouse enters a shape. Arguments 1 and 2 determine the style, the defaults are: onPointerOver = 'pointer', onPointerOut = 'auto'.

const [hovered, set] = useState()
useCursor(hovered, /*'pointer', 'auto'*/)
return (
  <mesh onPointerOver={() => set(true)} onPointerOut={() => set(false)}>

useIntersect

Demo

A very cheap frustum check that gives you a reference you can observe in order to know if the object has entered the view or is outside of it. This relies on THREE.Object3D.onBeforeRender so it only works on objects that are effectively rendered, like meshes, lines, sprites. It won't work on groups, object3d's, bones, etc.

const ref = useIntersect((visible) => console.log('object is visible', visible))
return <mesh ref={ref} />

useBoxProjectedEnv

Demo

The cheapest possible way of getting reflections in threejs. This will box-project the current environment map onto a plane. It returns an object that you need to spread over its material. The spread object contains a ref, onBeforeCompile and customProgramCacheKey. If you combine it with drei/CubeCamera you can "film" a single frame of the environment and feed it to the material, thereby getting realistic reflections at no cost. Align it with the position and scale properties.

const projection = useBoxProjectedEnv(
  [0, 0, 0], // Position
  [1, 1, 1] // Scale
)

<CubeCamera frames={1}>
  {(texture) => (
    <mesh>
      <planeGeometry />
      <meshStandardMaterial envMap={texture} {...projection} />
    </mesh>
  )}
</CubeCamera>

Loading

Loader

Demo

A quick and easy loading overlay component that you can drop on top of your canvas. It's intended to "hide" the whole app, so if you have multiple suspense wrappers in your application, you should use multiple loaders. It will show an animated loadingbar and a percentage.

<Canvas>
  <Suspense fallback={null}>
    <AsyncModels />
  </Suspense>
</Canvas>
<Loader />

You can override styles, too.

<Loader
  containerStyles={...container} // Flex layout styles
  innerStyles={...inner} // Inner container styles
  barStyles={...bar} // Loading-bar styles
  dataStyles={...data} // Text styles
  dataInterpolation={(p) => `Loading ${p.toFixed(2)}%`} // Text
  initialState={(active) => active} // Initial black out state
>

useProgress

A convenience hook that wraps THREE.DefaultLoadingManager's progress status.

function Loader() {
  const { active, progress, errors, item, loaded, total } = useProgress()
  return <Html center>{progress} % loaded</Html>
}

return (
  <Suspense fallback={<Loader />}>
    <AsyncModels />
  </Suspense>
)

If you don't want your progress component to re-render on all changes you can be specific as to what you need, for instance if the component is supposed to collect errors only. Look into zustand for more info about selectors.

const errors = useProgress((state) => state.errors)

πŸ‘‰ Note that your loading component does not have to be a suspense fallback. You can use it anywhere, even in your dom tree, for instance for overlays.

useGLTF

A convenience hook that uses useLoader and GLTFLoader, it defaults to CDN loaded draco binaries (https://www.gstatic.com/draco/v1/decoders/) which are only loaded for compressed models.

useGLTF(url)

useGLTF(url, '/draco-gltf')

useGLTF.preload(url)

useFBX

A convenience hook that uses useLoader and FBXLoader:

useFBX(url)

function SuzanneFBX() {
  let fbx = useFBX('suzanne/suzanne.fbx')
  return <primitive object={fbx} dispose={null} />
}

useTexture

A convenience hook that uses useLoader and TextureLoader

const texture = useTexture(url)
const [texture1, texture2] = useTexture([texture1, texture2])

You can also use key: url objects:

const props = useTexture({
  metalnessMap: url1,
  map: url2,
})
return <meshStandardMaterial {...props} />

useKTX2

A convenience hook that uses useLoader and KTX2Loader

const texture = useKTX2(url)
const [texture1, texture2] = useKTX2([texture1, texture2])

return <meshStandardMaterial map={texture} />

useCubeTexture

A convenience hook that uses useLoader and CubeTextureLoader

const envMap = useCubeTexture(['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'], { path: 'cube/' })

Performance

Instances

Demo Demo

A wrapper around THREE.InstancedMesh. This allows you to define hundreds of thousands of objects in a single draw call, but declaratively!

<Instances
  limit={1000} // Optional: max amount of items (for calculating buffer size)
  range={1000} // Optional: draw-range
>
  <boxGeometry />
  <meshStandardMaterial />
  <Instance
    color="red"
    scale={2}
    position={[1, 2, 3]}
    rotation={[Math.PI / 3, 0, 0]}
    onClick={onClick} ... />
  // As many as you want, make them conditional, mount/unmount them, lazy load them, etc ...
</Instances>

You can nest Instances and use relative coordinates!

<group position={[1, 2, 3]} rotation={[Math.PI / 2, 0, 0]}>
  <Instance />
</group>

Instances can also receive non-instanced objects, for instance annotations!

<Instance>
  <Html>hello from the dom</Html>
</Instance>

You can define events on them!

<Instance onClick={...} onPointerOver={...} />

πŸ‘‰ Note: While creating instances declaratively keeps all the power of components with reduced draw calls, it comes at the cost of CPU overhead. For cases like foliage where you want no CPU overhead with thousands of intances you should use THREE.InstancedMesh such as in this example.

Merged

Demo

This creates instances for existing meshes and allows you to use them cheaply in the same scene graph. Each type will cost you exactly one draw call, no matter how many you use. meshes has to be a collection of pre-existing THREE.Mesh objects.

<Merged meshes={[box, sphere]}>
  {(Box, Sphere) => (
    <>
      <Box position={[-2, -2, 0]} color="red" />
      <Box position={[-3, -3, 0]} color="tomato" />
      <Sphere scale={0.7} position={[2, 1, 0]} color="green" />
      <Sphere scale={0.7} position={[3, 2, 0]} color="teal" />
    </>
  )}
</Merged>

You may also use object notation, which is good for loaded models.

function Model({ url }) {
  const { nodes } = useGLTF(url)
  return (
    <Merged meshes={nodes}>
      {({ Screw, Filter, Pipe }) => (
        <>
          <Screw />
          <Filter position={[1, 2, 3]} />
          <Pipe position={[4, 5, 6]} />
        </>
      )}
    </Merged>
  )
}

Points

A wrapper around THREE.Points. It has the same api and properties as Instances.

<Points
  limit={1000} // Optional: max amount of items (for calculating buffer size)
  range={1000} // Optional: draw-range
>
  <pointsMaterial vertexColors />
  <Point position={[1, 2, 3]} color="red" onClick={onClick} onPointerOver={onPointerOver} ... />
  // As many as you want, make them conditional, mount/unmount them, lazy load them, etc ...
</Points>

If you just want to use buffers for position, color and size, you can use the alternative API:

<Points positions={positionsBuffer} colors={colorsBuffer} sizes={sizesBuffer}>
  <pointsMaterial />
</Points>

Segments

A wrapper around THREE.LineSegments. This allows you to use thousands of segments under the same geometry.

Prop based:
<Segments limit={1000} lineWidth={1.0}>
  <Segment start={[0, 0, 0]} end={[0, 10, 0]} color="red" />
  <Segment start={[0, 0, 0]} end={[0, 10, 10]} color={[1, 0, 1]} />
</Segments>
Ref based (for fast updates):
const ref = useRef()

// E.g. to change segment position each frame.
useFrame(() => {
  ref.current.start.set(0,0,0)
  ref.current.end.set(10,10,0)
  ref.current.color.setRGB(0,0,0)
})
// ...
<Segments
  limit={1000}
  lineWidth={1.0}
>
  <Segment ref={ref} />
</Segments>

Detailed

Demo

A wrapper around THREE.LOD (Level of detail).

<Detailed distances={[0, 10, 20]} {...props}>
  <mesh geometry={highDetail} />
  <mesh geometry={mediumDetail} />
  <mesh geometry={lowDetail} />
</Detailed>

Preload

The WebGLRenderer will compile materials only when they hit the frustrum, which can cause jank. This component precompiles the scene using gl.compile which makes sure that your app is responsive from the get go.

By default gl.compile will only preload visible objects, if you supply the all prop, it will circumvent that. With the scene and camera props you could also use it in portals.

<Canvas>
  <Suspense fallback={null}>
    <Model />
    <Preload all />

BakeShadows

Sets gl.shadowMap.autoUpdate to false while mounted and requests a single gl.shadowMap.needsUpdate = true afterwards. This freezes all shadow maps the moment this component comes in, which makes shadows performant again (with the downside that they are now static). Mount this component in lock-step with your models, for instance by dropping it into the same suspense boundary of a model that loads.

<Canvas>
  <Suspense fallback={null}>
    <Model />
    <BakeShadows />

meshBounds

A very fast, but often good-enough bounds-only raycast for meshes. You can use this if performance has precedence over pointer precision.

<mesh raycast={meshBounds} />

AdaptiveDpr

Drop this component into your scene and it will cut the pixel-ratio on regress according to the canvas's performance min/max settings. This allows you to temporarily reduce visual quality in exchange for more performance, for instance when the camera moves (look into drei's controls regress flag). Optionally, you can set the canvas to a pixelated filter, which would be even faster.

<AdaptiveDpr pixelated />

AdaptiveEvents

Drop this component into your scene and it will switch off the raycaster while the system is in regress.

<AdaptiveEvents />

useBVH

A hook to speed up the default raycasting by using the BVH Implementation by @gkjohnnson.

const mesh = useRef()
useBVH(mesh)

<mesh ref={mesh} ... />

Staging

Center

Calculates a boundary box and centers its children accordingly. alignTop adjusts it so that it sits flush on y=0.

<Center alignTop>
  <mesh />
</Center>

Bounds

Demo

Calculates a boundary box and centers the camera accordingly. If you are using controls, make sure to pass them the makeDefault prop. fit fits the current view on first render. clip sets the cameras near/far planes.

<Bounds fit clip damping={6} margin={1.2}>
  <mesh />
</Bounds>

The Bounds component also acts as a context provider, use the useBounds hook to refresh the bounds, fit the camera, clip near/far planes or focus objects. refresh(object?: THREE.Object3D | THREE.Box3) will recalculate bounds, since this can be expensive only call it when you know the view has changed. clip sets the cameras near/far planes. fit zooms and centers the view.

function Foo() {
  const bounds = useBounds()
  useEffect(() => {
    // Calculate scene bounds
    bounds.refresh().clip().fit()
    // Or, focus a specific object or box3
    // bounds.refresh(ref.current).clip().fit()
    // bounds.refresh(new THREE.Box3()).clip().fit()

<Bounds>
  <Foo />

CameraShake

Demo Demo

A component for applying a configurable camera shake effect. Currently only supports rotational camera shake. Pass a ref to recieve the ShakeController API.

If you use shake in combination with controls make sure to set the makeDefault prop on your controls, in that case you do not have to pass them via the controls prop.

const config = {
  maxYaw: 0.1, // Max amount camera can yaw in either direction
  maxPitch: 0.1, // Max amount camera can pitch in either direction
  maxRoll: 0.1, // Max amount camera can roll in either direction
  yawFrequency: 0.1, // Frequency of the the yaw rotation
  pitchFrequency: 0.1, // Frequency of the pitch rotation
  rollFrequency: 0.1, // Frequency of the roll rotation
  intensity: 1, // initial intensity of the shake
  decay: false, // should the intensity decay over time
  decayRate: 0.65, // if decay = true this is the rate at which intensity will reduce at
  controls: undefined, // if using orbit controls, pass a ref here so we can update the rotation
}

;<CameraShake {...config} />
interface ShakeController {
  getIntensity: () => number
  setIntensity: (val: number) => void
}

Float

Demo

This component makes its contents float or hover.

<Float
  speed={1} // Animation speed, defaults to 1
  rotationIntensity={1} // XYZ rotation intensity, defaults to 1
  floatIntensity={1} // Up/down float intensity, defaults to 1
>
  <mesh />
</Float>

Stage

Creates a "stage" with proper studio lighting, content centered and planar, shadows and ground-contact shadows.

Make sure to set the makeDefault prop on your controls, in that case you do not need to provide controls via prop.

<Stage contactShadow shadows adjustCamera intensity={1} environment="city" preset="rembrandt" controls={controlsRef}>
  <mesh />
</Stage>

Backdrop

Demo

A curved plane, like a studio backdrop. This is for presentational purposes, to break up light and shadows more interestingly.

<Backdrop
  floor={0.25} // Stretches the floor segment, 0.25 by default
  segments={20} // Mesh-resolution, 20 by default
>
  <meshStandardMaterial color="#353540" />
</Backdrop>

Shadow

A cheap canvas-texture-based circular gradient.

<Shadow
  color="black"
  colorStop={0}
  opacity={0.5}
  fog={false} // Reacts to fog (default=false)
/>

ContactShadows

Demo

A contact shadow implementation, facing upwards (positive Y) by default. scale can be a positive number or a 2D array [x: number, y: number].

<ContactShadows opacity={1} scale={10} blur={1} far={10} resolution={256} />

Since this is a rather expensive effect you can limit the amount of frames it renders when your objects are static. For instance making it render only once:

<ContactShadows frames={1} />

SpotLight

Demo Demo

A Volumetric spotlight.

<SpotLight
  distance={5}
  angle={0.15}
  attenuation={5}
  anglePower={5} // Diffuse-cone anglePower (default: 5)
/>

Optionally you can provide a depth-buffer which converts the spotlight into a soft particle.

function Foo() {
  const depthBuffer = useDepthBuffer()
  return <SpotLight depthBuffer={depthBuffer} />

Environment

Demo

Sets up a global cubemap, which affects the default scene.environment, and optionally scene.background, unless a custom scene has been passed. A selection of presets from HDRI Haven are available for convenience. If you pass an array of files it will use THREE.CubeTextureLoader.

πŸ‘‰ Note: preset property is not meant to be used in production environments. Consider using files property together with local files or a CDN of your choice instead.

<Environment
  background={false}
  files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']}
  path="/"
  preset={null}
  scene={undefined} // adds the ability to pass a custom THREE.Scene
/>

If you provide a single string it will use THREE.RGBELoader.

<Environment files="file.hdr" />

If you provide children you can even render a custom environment. It will render the contents into an off-buffer and film a single frame with a cube camera (whose props you can configure: near=1, fear=1000, resolution=256).

<Environment background>
  <mesh scale={100}>
    <sphereGeometry args={[1, 64, 64]} />
    <meshBasicMaterial map={texture} side={THREE.BackSide} />
  </mesh>
</Environment>

Sky

Demo

Adds a sky to your scene.

<Sky distance={450000} sunPosition={[0, 1, 0]} inclination={0} azimuth={0.25} {...props} />

Stars

Adds a blinking shader-based starfield to your scene.

<Stars radius={100} depth={50} count={5000} factor={4} saturation={0} fade />

Cloud

Demo

Particle based cloud.

πŸ‘‰ Note: <Cloud /> component is not meant to be used in production environments as it relies on third-party CDN.

<Cloud
  opacity={0.5}
  speed={0.4} // Rotation speed
  width={10} // Width of the full cloud
  depth={1.5} // Z-dir depth
  segments={20} // Number of particles
/>

useMatcapTexture

Loads matcap textures from this repository: https://github.com/emmelleppi/matcaps

(It is a fork of this repository: https://github.com/nidorx/matcaps)

πŸ‘‰ Note: useMatcapTexture hook is not meant to be used in production environments as it relies on third-party CDN.

const [matcap, url] = useMatcapTexture(
 0, // index of the matcap texture https://github.com/emmelleppi/matcaps/blob/master/matcap-list.json
 1024 // size of the texture ( 64, 128, 256, 512, 1024 )
)

return (
 ...
 <meshMatcapMaterial matcap={matcap} />
 ...
)

πŸ‘‰ You can also use the exact name of the matcap texture, like so:

const [matcap] = useMatcapTexture('3E2335_D36A1B_8E4A2E_2842A5')

πŸ‘‰ Use the url to download the texture when you are ready for production!

useNormalTexture

Loads normal textures from this repository: https://github.com/emmelleppi/normal-maps

πŸ‘‰ Note: useNormalTexture hook is not meant to be used in production environments as it relies on third-party CDN.

const [normalMap, url] = useNormalTexture(
  1, // index of the normal texture - https://github.com/emmelleppi/normal-maps/blob/master/normals.json
  // second argument is texture attributes
  {
    offset: [0, 0],
    repeat: [normRepeat, normRepeat],
    anisotropy: 8
  }
)

return (
  ...
  <meshStandardMaterial normalMap={normalMap} />
  ...
)
ezoic increase your site revenue

About

πŸ₯‰ useful helpers for react-three-fiber

https://drei.pmnd.rs/

License:MIT License


Languages

Language:JavaScript 80.8%Language:TypeScript 19.2%Language:CSS 0.1%Language:HTML 0.0%Language:Shell 0.0%Language:GLSL 0.0%