• Stars
    star
    364
  • Rank 113,016 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 1 year ago
  • Updated about 2 months ago

Reviews

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

Repository Details

ðŸĶ drei-inspired helpers for threejs

logo

Version Downloads Discord Shield Open in GitHub Codespaces

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

Storybook demos storybook

Storybook code available under .storybook/stories

npm install @pmndrs/vanilla

Basic usage:

import { pcss, ... } from '@pmndrs/vanilla'

Index

Shaders

pcss

storybook

Demo Demo

type SoftShadowsProps = {
  /** Size of the light source (the larger the softer the light), default: 25 */
  size?: number
  /** Number of samples (more samples less noise but more expensive), default: 10 */
  samples?: number
  /** Depth focus, use it to shift the focal point (where the shadow is the sharpest), default: 0 (the beginning) */
  focus?: number
}

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

// Inject pcss into the shader chunk
const reset = pcss({ size: 25, samples: 10, focus: 0 })

The function returns a reset function that can be used to remove the pcss from the shader chunk.

// Remove pcss from the shader chunk, and reset the scene
reset(renderer, scene, camera)

Materials

shaderMaterial

storybook

Demo

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

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);
    }
  `
)

const mesh = new THREE.Mesh(geometry, new ColorShiftMaterial())
TypeScript usage

Uniform types can be inferred from the uniforms argument or passed as a generic type argument.

  type MyMaterialProps = {
    time: number,
    color: THREE.Color,
    map: THREE.Texture | null
  }

  const MyMaterial = shaderMaterial<MyMaterialProps>(
    {
      time: 0,
      color: new THREE.Color(0.2, 0.0, 0.1)
      map: null
    },
    vertexShader,
    fragmentShader
  )

  const material = new MyMaterial()
  material.time
        // ^? (property) time: number

MeshDiscardMaterial

A material that discards fragments. It can be used to render nothing efficiently, but still have a mesh in the scene graph that throws shadows and can be raycast.

const mesh = new THREE.Mesh(geometry, new MeshDiscardMaterial())

MeshTransmissionMaterial

storybook

Demo

An improved THREE.MeshPhysicalMaterial. It acts like a normal PhysicalMaterial in terms of transmission support, thickness, ior, roughness, etc., but has chromatic aberration, noise-based roughness blur, (primitive) anisotropicBlur support, and unlike the original it can "see" other transmissive or transparent objects which leads to improved visuals.

Although it should be faster than MPM keep in mind that it can still be expensive as it causes an additional render pass of the scene. Low samples and low resolution will make it faster. If you use roughness consider using a tiny resolution, for instance 32x32 pixels, it will still look good but perform much faster.

For performance and visual reasons the host mesh gets removed from the render-stack temporarily. If you have other objects that you don't want to see reflected in the material just add them to the parent mesh as children.

export type MeshTransmissionMaterialProps = {
  /* Transmission, default: 1 */
  _transmission?: number
  /* Thickness (refraction), default: 0 */
  thickness?: number
  /* Roughness (blur), default: 0 */
  roughness?: number
  /* Chromatic aberration, default: 0.03 */
  chromaticAberration?: number
  /* AnisotropicBlur, default: 0.1 */
  anisotropicBlur?: number
  /* Distortion, default: 0 */
  distortion?: number
  /* Distortion scale, default: 0.5 */
  distortionScale: number
  /* Temporal distortion (speed of movement), default: 0.0 */
  temporalDistortion: number
}
const material = new MeshTransmissionMaterial({
  _transmission: 1,
  thickness: 0,
  roughness: 0,
  chromaticAberration: 0.03,
  anisotropicBlur: 0.1,
  distortion: 0,
  distortionScale: 0.5,
  temporalDistortion: 0.0,
})

SpotLight

storybook

Demo Demo

A Volumetric spotlight.

const material = new SpotLightMaterial({
  opacity: 1, // volume shader opacity
  attenuation: 2.5, // how far the volume will travel
  anglePower: 12, // volume edge fade
  spotPosition: new Vector3(0, 0, 0), // spotlight's world position
  lightColor: new Color('white'), // volume color

  cameraNear: 0, // for depth
  cameraFar: 1, // for depth
  depth: null, // for depth , add depthTexture here
  resolution: new Vector2(0, 0), // for depth , set viewport/canvas resolution here
})

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

MeshReflectorMaterial

storybook

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.

 AccumulativeShadows

storybook

Demo

A planar, Y-up oriented shadow-catcher that can accumulate into soft shadows and has zero performance impact after all frames have accumulated. It can be temporal, it will accumulate over time, or instantaneous, which might be expensive depending on how many frames you render.

Refer to storybook code on how to use & what each variable does

Caustics

storybook

drei counterpart

Caustics are swirls of light that appear when light passes through transmissive surfaces. This component uses a raymarching technique to project caustics onto a catcher plane. It is based on github/N8python/caustics.

type CausticsProps =  {
  /** How many frames it will render, set it to Infinity for runtime, default: 1 */
  frames?: number
  /** Will display caustics only and skip the models, default: false */
  causticsOnly: boolean
  /** Will include back faces and enable the backsideIOR prop, default: false */
  backside: boolean
  /** The IOR refraction index, default: 1.1 */
  ior?: number
  /** The IOR refraction index for back faces (only available when backside is enabled), default: 1.1 */
  backsideIOR?: number
  /** The texel size, default: 0.3125 */
  worldRadius?: number
  /** Intensity of the projected caustics, default: 0.05 */
  intensity?: number
  /** Caustics color, default: THREE.Color('white') */
  color?: THREE.Color
  /** Buffer resolution, default: 2048 */
  resolution?: number
  /** Caustics camera position, it will point towards the contents bounds center, default: THREE.Vector3(5,5,5) */
  lightSource?: <THREE.Vector3>| <THREE.Object3D>
  /** Caustics camera far, when 0 its automatically computed in render loop, default: 0 .Use this if the auto computed value looks incorrect(Happens in very small models)*/
  far?: number
}

It will create a transparent plane that blends the caustics of the objects it receives into your scene. It will only render once and not take resources any longer!

Make sure to configure the props above as some can be micro fractional depending on the models (intensity, worldRadius, ior and backsideIOR especially).

The light source can either be defined by Vector3 or by an object3d. Use the latter if you want to control the light source, for instance in order to move or animate it. Runtime caustics with frames set to Infinity, a low resolution and no backside can be feasible.

let caustics = Caustics(renderer, {
  frames: Infinity,
  resolution: 1024,
  worldRadius: 0.3,
  ...
})

scene.add(caustics.group) // add caustics group to your scene

caustics.scene.add(yourMesh) // add the mesh you want caustics from into the 'caustics scene'

// call the update() method in your animate loop for runtime (frames=Infinity case) else call it just once to compute the caustics
caustics.update()

// to see the camera helper
caustics.scene.add(caustics.helper)

Caustics function returns the following

export type CausticsType = {
  scene: THREE.Scene // internal caustics scene
  group: THREE.Group // group for user to add into your scene
  helper: THREE.CameraHelper // helper to visualize the caustics camera
  params: CausticsProps // all properties from CausticsProps
  update: () => void // function to render the caustics output

  //internally used render targets
  normalTarget: THREE.WebGLRenderTarget
  normalTargetB: THREE.WebGLRenderTarget
  causticsTarget: THREE.WebGLRenderTarget
  causticsTargetB: THREE.WebGLRenderTarget
}

Grid

storybook

drei counterpart

A y-up oriented, shader-based grid implementation.

export type GridProps = {
  /** plane-geometry size, default: [1,1] */
  args?: Array<number>
  /** Cell size, default: 0.5 */
  cellSize?: number
  /** Cell thickness, default: 0.5 */
  cellThickness?: number
  /** Cell color, default: black */
  cellColor?: THREE.ColorRepresentation
  /** Section size, default: 1 */
  sectionSize?: number
  /** Section thickness, default: 1 */
  sectionThickness?: number
  /** Section color, default: #2080ff */
  sectionColor?: THREE.ColorRepresentation
  /** Follow camera, default: false */
  followCamera?: boolean
  /** Display the grid infinitely, default: false */
  infiniteGrid?: boolean
  /** Fade distance, default: 100 */
  fadeDistance?: number
  /** Fade strength, default: 1 */
  fadeStrength?: number
}

Usage

grid = Grid({
  args: [10.5, 10.5],
  cellSize: 0.6,
  cellThickness: 1,
  cellColor: new THREE.Color('#6f6f6f'),
  sectionSize: 3.3,
  sectionThickness: 1.5,
  sectionColor: new THREE.Color('#9d4b4b'),
  fadeDistance: 25,
  fadeStrength: 1,
  followCamera: false,
  infiniteGrid: true,
})

scene.add(grid.mesh)

// call in animate loop
grid.update(camera)

Grid function returns the following

export type GridType = {
  /* Mesh with gridMaterial to add to your scene  */
  mesh: THREE.Mesh
  /* Call in animate loop to update grid w.r.t camera */
  update: (camera: THREE.Camera) => void
}

Outlines

storybook

drei counterpart

An ornamental component that extracts the geometry from its parent and displays an inverted-hull outline. Supported parents are THREE.Mesh, THREE.SkinnedMesh and THREE.InstancedMesh.

export type OutlinesProps = {
  /** Outline color, default: black */
  color: THREE.Color
  /** Outline opacity, default: 1 */
  opacity: number
  /** Outline transparency, default: false */
  transparent: boolean
  /** Outline thickness, default 0.05 */
  thickness: number
  /** Geometry crease angle (0 === no crease), default: Math.PI */
  angle: number
}

Usage

const outlines = Outlines()
const mesh = new THREE.Mesh(geometry, material)
mesh.add(outlines.group)

// must call generate() to create the outline mesh
outlines.generate()

scene.add(mesh)

Outlines function returns the following

export type OutlinesType = {
  group: THREE.Group
  updateProps: (props: Partial<OutlinesProps>) => void
  generate: () => void
}

Billboard

storybook

drei counterpart

Adds a THREE.Group that always faces the camera.

export type BillboardProps = {
  /**
   * @default true
   */
  follow?: boolean
  /**
   * @default false
   */
  lockX?: boolean
  /**
   * @default false
   */
  lockY?: boolean
  /**
   * @default false
   */
  lockZ?: boolean
}

Usage

const billboard = Billboard()
const mesh = new THREE.Mesh(geometry, material)
billboard.group.add(mesh)

scene.add(billboard)

// call in animate loop
billboard.update(camera)

Billboard function returns the following

export type BillboardType = {
  group: THREE.Group
  /**
   * Should called every frame to update the billboard
   */
  update: (camera: THREE.Camera) => void
  updateProps: (newProps: Partial<BillboardProps>) => void
}

Text

storybook

drei counterpart

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

Required troika-three-text >= 0.46.4

export type TextProps = {
  characters?: string
  color?: number | string
  // the text content
  text: string
  /** Font size, default: 1 */
  fontSize?: number
  maxWidth?: number
  lineHeight?: number
  letterSpacing?: number
  textAlign?: 'left' | 'right' | 'center' | 'justify'
  font?: string
  anchorX?: number | 'left' | 'center' | 'right'
  anchorY?: number | 'top' | 'top-baseline' | 'middle' | 'bottom-baseline' | 'bottom'
  clipRect?: [number, number, number, number]
  depthOffset?: number
  direction?: 'auto' | 'ltr' | 'rtl'
  overflowWrap?: 'normal' | 'break-word'
  whiteSpace?: 'normal' | 'overflowWrap' | 'nowrap'
  outlineWidth?: number | string
  outlineOffsetX?: number | string
  outlineOffsetY?: number | string
  outlineBlur?: number | string
  outlineColor?: number | string
  outlineOpacity?: number
  strokeWidth?: number | string
  strokeColor?: number | string
  strokeOpacity?: number
  fillOpacity?: number
  sdfGlyphSize?: number
  debugSDF?: boolean
  onSync?: (troika: any) => void
  onPreloadEnd?: () => void
}

Usage

const text = Text({
  text: 'Hello World',
})
const mesh = new THREE.Mesh(geometry, material)
mesh.add(text.mesh)

Text function returns the following

export type TextType = {
  mesh: THREE.Mesh
  updateProps: (newProps: Partial<TextProps>) => void
  dispose: () => void
}

You can preload the font and characters:

const preloadRelatedParams = {
  // support ttf/otf/woff(woff2 is not supported)
  font: '/your/font/path',
  characters: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!?.,:;\'"()[]{}<>|/@\\^$-%+=#_&~*',
  onPreloadEnd: () => {
    // this is the callback when font and characters are loaded
  },

Sprite Animator

storybook

drei counterpart

type SpriteAnimatorProps = {
  /** The start frame of the animation */
  startFrame?: number
  /** The end frame of the animation */
  endFrame?: number
  /** The desired frames per second of the animaiton */
  fps?: number
  /** The frame identifier to use, has to be one of animationNames */
  frameName?: string
  /** The URL of the texture JSON (if using JSON-Array or JSON-Hash) */
  textureDataURL?: string
  /** The URL of the texture image */
  textureImageURL?: string
  /** Whether or not the animation should loop */
  loop?: boolean
  /** The number of frames of the animation (required if using plain spritesheet without JSON) */
  numberOfFrames?: number
  /** Whether or not the animation should auto-start when all assets are loaded */
  autoPlay?: boolean
  /** The animation names of the spritesheet (if the spritesheet -with JSON- contains more animation sequences) */
  animationNames?: Array<string>
  /** Event callback when the animation starts */
  onStart?: Function
  /** Event callback when the animation ends */
  onEnd?: Function
  /** Event callback when the animation loops */
  onLoopEnd?: Function
  /** Event callback when each frame changes */
  onFrame?: Function
  /** Control when the animation runs */
  play?: boolean
  /** Control when the animation pauses */
  pause?: boolean
  /** Whether or not the Sprite should flip sides on the x-axis */
  flipX?: boolean
  /** Sets the alpha value to be used when running an alpha test. https://threejs.org/docs/#api/en/materials/Material.alphaTest */
  alphaTest?: number
  /** Displays the texture on a SpriteGeometry always facing the camera, if set to false, it renders on a PlaneGeometry */
  asSprite?: boolean
}

The SpriteAnimator is a powerful tool for animating sprites in a simple and efficient manner. It allows you to create sprite animations by cycling through a sequence of frames from a sprite sheet image or JSON data.

Notes:

  • The SpriteAnimator uses .update() method added to requestAnimation frame loop to for efficient frame updates and rendering.
  • The sprites should contain equal size frames
  • Trimming of spritesheet frames is not yet supported

Usage

const alienSpriteAnimator = SpriteAnimator({
  startFrame: 0,
  autoPlay: true,
  loop: true,
  numberOfFrames: 16,
  alphaTest: 0.01,
  textureImageURL: './sprites/alien.png',
})
await AlienSpriteAnimator.init() // file fetching happens here

alienSpriteAnimator.group.position.set(0, 0.5, 2)

scene.add(alienSpriteAnimator.group)

SpriteAnimator function returns the following object

export type SpriteAnimatorType = {
  group: THREE.Group // A reference to the THREE.Group used for holding the sprite or plane.
  init: Function // Function to initialize, fetch the files and start the animations.
  update: Function // Function to update the sprite animation, needs to be called every frame.
  pauseAnimation: Function // Function to pause the animation.
  playAnimation: Function // Function to play the animation.
  setFrameName: Function // Function to set the frame identifier to use, has to be one of animationNames.
}

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-xr

ðŸĪģ VR/AR with react-three-fiber
TypeScript
1,890
star
15

react-three-flex

💊ðŸ“Ķ Flexbox for react-three-fiber
TypeScript
1,606
star
16

suspend-react

ðŸšĨ Async/await for React components
TypeScript
1,308
star
17

react-postprocessing

📎 postprocessing for react-three-fiber
JavaScript
1,009
star
18

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
19

lamina

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

its-fine

ðŸķðŸ”Ĩ A collection of escape hatches for React.
TypeScript
891
star
21

react-use-measure

🙌 Utility to measure view bounds
TypeScript
799
star
22

react-nil

⃝ A react null renderer
TypeScript
772
star
23

react-three-rapier

ðŸĪš Rapier physics in React
TypeScript
765
star
24

maath

ðŸŠķ Math helpers for the rest of us
TypeScript
755
star
25

threejs-journey

⚛ïļ Bruno Simons journey demos in React
TypeScript
685
star
26

three-stdlib

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

react-three-editor

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

react-three-a11y

â™ŋïļ Accessibility tools for React Three Fiber
TypeScript
507
star
29

react-zdog

⚡ïļðŸķ React bindings for zdog
JavaScript
441
star
30

use-asset

ðŸ“Ķ A promise caching strategy for React Suspense
TypeScript
414
star
31

react-three-offscreen

📚 Offscreen worker canvas for react-three-fiber
TypeScript
397
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