Gathering detailed insights and metrics for @pmndrs/vanilla
Gathering detailed insights and metrics for @pmndrs/vanilla
Gathering detailed insights and metrics for @pmndrs/vanilla
Gathering detailed insights and metrics for @pmndrs/vanilla
npm install @pmndrs/vanilla
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
476 Stars
103 Commits
19 Forks
10 Watching
3 Branches
43 Contributors
Updated on 25 Nov 2024
TypeScript (98.3%)
JavaScript (1.24%)
CSS (0.35%)
Shell (0.08%)
GLSL (0.02%)
Cumulative downloads
Total Downloads
Last day
-19.2%
193
Compared to previous day
Last week
33.5%
993
Compared to previous week
Last month
78.1%
3,368
Compared to previous month
Last year
242.1%
20,965
Compared to previous year
1
1
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 code available under .storybook/stories
1npm install @pmndrs/vanilla
1import { pcss, ... } from '@pmndrs/vanilla'
1type SoftShadowsProps = { 2 /** Size of the light source (the larger the softer the light), default: 25 */ 3 size?: number 4 /** Number of samples (more samples less noise but more expensive), default: 10 */ 5 samples?: number 6 /** Depth focus, use it to shift the focal point (where the shadow is the sharpest), default: 0 (the beginning) */ 7 focus?: number 8}
Injects percent closer soft shadows (pcss) into threes shader chunk.
1// Inject pcss into the shader chunk 2const 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.
1// Remove pcss from the shader chunk, and reset the scene 2reset(renderer, scene, camera)
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.
1const ColorShiftMaterial = shaderMaterial( 2 { time: 0, color: new THREE.Color(0.2, 0.0, 0.1) }, 3 // vertex shader 4 /*glsl*/ ` 5 varying vec2 vUv; 6 void main() { 7 vUv = uv; 8 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); 9 } 10 `, 11 // fragment shader 12 /*glsl*/ ` 13 uniform float time; 14 uniform vec3 color; 15 varying vec2 vUv; 16 void main() { 17 gl_FragColor.rgba = vec4(0.5 + 0.3 * sin(vUv.yxx + time) + color, 1.0); 18 } 19 ` 20) 21 22const mesh = new THREE.Mesh(geometry, new ColorShiftMaterial())
Uniform types can be inferred from the uniforms
argument or passed as a generic type argument.
1 type MyMaterialProps = { 2 time: number, 3 color: THREE.Color, 4 map: THREE.Texture | null 5 } 6 7 const MyMaterial = shaderMaterial<MyMaterialProps>( 8 { 9 time: 0, 10 color: new THREE.Color(0.2, 0.0, 0.1) 11 map: null 12 }, 13 vertexShader, 14 fragmentShader 15 ) 16 17 const material = new MyMaterial() 18 material.time 19 // ^? (property) time: number
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.
1const mesh = new THREE.Mesh(geometry, new MeshDiscardMaterial())
This material makes your geometry distort following simplex noise.
This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.
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.
1export type MeshTransmissionMaterialProps = { 2 /* Transmission, default: 1 */ 3 _transmission?: number 4 /* Thickness (refraction), default: 0 */ 5 thickness?: number 6 /* Roughness (blur), default: 0 */ 7 roughness?: number 8 /* Chromatic aberration, default: 0.03 */ 9 chromaticAberration?: number 10 /* AnisotropicBlur, default: 0.1 */ 11 anisotropicBlur?: number 12 /* Distortion, default: 0 */ 13 distortion?: number 14 /* Distortion scale, default: 0.5 */ 15 distortionScale: number 16 /* Temporal distortion (speed of movement), default: 0.0 */ 17 temporalDistortion: number 18}
1const material = new MeshTransmissionMaterial({ 2 _transmission: 1, 3 thickness: 0, 4 roughness: 0, 5 chromaticAberration: 0.03, 6 anisotropicBlur: 0.1, 7 distortion: 0, 8 distortionScale: 0.5, 9 temporalDistortion: 0.0, 10})
A Volumetric spotlight.
1const material = new SpotLightMaterial({ 2 opacity: 1, // volume shader opacity 3 attenuation: 2.5, // how far the volume will travel 4 anglePower: 12, // volume edge fade 5 spotPosition: new Vector3(0, 0, 0), // spotlight's world position 6 lightColor: new Color('white'), // volume color 7 8 cameraNear: 0, // for depth 9 cameraFar: 1, // for depth 10 depth: null, // for depth , add depthTexture here 11 resolution: new Vector2(0, 0), // for depth , set viewport/canvas resolution here 12})
Optionally you can provide a depth-buffer which converts the spotlight into a soft particle.
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.
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 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.
1type CausticsProps = { 2 /** How many frames it will render, set it to Infinity for runtime, default: 1 */ 3 frames?: number 4 /** Will display caustics only and skip the models, default: false */ 5 causticsOnly: boolean 6 /** Will include back faces and enable the backsideIOR prop, default: false */ 7 backside: boolean 8 /** The IOR refraction index, default: 1.1 */ 9 ior?: number 10 /** The IOR refraction index for back faces (only available when backside is enabled), default: 1.1 */ 11 backsideIOR?: number 12 /** The texel size, default: 0.3125 */ 13 worldRadius?: number 14 /** Intensity of the projected caustics, default: 0.05 */ 15 intensity?: number 16 /** Caustics color, default: THREE.Color('white') */ 17 color?: THREE.Color 18 /** Buffer resolution, default: 2048 */ 19 resolution?: number 20 /** Caustics camera position, it will point towards the contents bounds center, default: THREE.Vector3(5,5,5) */ 21 lightSource?: <THREE.Vector3>| <THREE.Object3D> 22 /** 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)*/ 23 far?: number 24}
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.
1let caustics = Caustics(renderer, { 2 frames: Infinity, 3 resolution: 1024, 4 worldRadius: 0.3, 5 ... 6}) 7 8scene.add(caustics.group) // add caustics group to your scene 9 10caustics.scene.add(yourMesh) // add the mesh you want caustics from into the 'caustics scene' 11 12// call the update() method in your animate loop for runtime (frames=Infinity case) else call it just once to compute the caustics 13caustics.update() 14 15// to see the camera helper 16caustics.scene.add(caustics.helper) 17
Caustics function returns the following
1export type CausticsType = { 2 scene: THREE.Scene // internal caustics scene 3 group: THREE.Group // group for user to add into your scene 4 helper: THREE.CameraHelper // helper to visualize the caustics camera 5 params: CausticsProps // all properties from CausticsProps 6 update: () => void // function to render the caustics output 7 8 //internally used render targets 9 normalTarget: THREE.WebGLRenderTarget 10 normalTargetB: THREE.WebGLRenderTarget 11 causticsTarget: THREE.WebGLRenderTarget 12 causticsTargetB: THREE.WebGLRenderTarget 13}
If you are using a frontend framework, the construction of Caustics
effect by calling Caustics()
might not be enough due to how frameworks handle the component life-cycle, changes when props change, and content projection / rendering children.
To accommodate this use-case, @pmndrs/vanilla
exports the following symbols to help you integrate the caustics effect with your frontend framework:
CausticsProjectionMaterial
: A material that projects the caustics onto the catcher plane.CausticsMaterial
: A material that renders the caustics.createCausticsUpdate
: A function that accepts an updateParameters
function/getter and creates an update
function for the caustics effect. This function should be called in the animation loop implementation of your framework, and updateParameters
should return the latest value of the parameters based on your framework's state management.1export function createCausticsUpdate( 2 updateParameters: () => { 3 params: Omit<CausticsProps, 'color'> 4 scene: THREE.Scene 5 group: THREE.Group 6 camera: THREE.OrthographicCamera 7 plane: THREE.Mesh<PlaneGeometry, InstanceType<typeof CausticsProjectionMaterial>> 8 normalTarget: THREE.WebGLRenderTarget 9 normalTargetB: THREE.WebGLRenderTarget 10 causticsTarget: THREE.WebGLRenderTarget 11 causticsTargetB: THREE.WebGLRenderTarget 12 helper?: THREE.CameraHelper | null 13 } 14): (gl: THREE.WebGLRenderer) => void
Instanced Mesh/Particle based cloud.
1type CloudsProps = { 2 /** cloud texture*/ 3 texture?: Texture | undefined 4 /** Maximum number of segments, default: 200 (make this tight to save memory!) */ 5 limit?: number 6 /** How many segments it renders, default: undefined (all) */ 7 range?: number 8 /** Which material it will override, default: MeshLambertMaterial */ 9 material?: typeof Material 10 /** Frustum culling, default: true */ 11 frustumCulled?: boolean 12}
1type CloudProps = { 2 /** A seeded random will show the same cloud consistently, default: Math.random() */ 3 seed?: number 4 /** How many segments or particles the cloud will have, default: 20 */ 5 segments?: number 6 /** The box3 bounds of the cloud, default: [5, 1, 1] */ 7 bounds?: Vector3 8 /** How to arrange segment volume inside the bounds, default: inside (cloud are smaller at the edges) */ 9 concentrate?: 'random' | 'inside' | 'outside' 10 /** The general scale of the segments */ 11 scale?: Vector3 12 /** The volume/thickness of the segments, default: 6 */ 13 volume?: number 14 /** The smallest volume when distributing clouds, default: 0.25 */ 15 smallestVolume?: number 16 /** An optional function that allows you to distribute points and volumes (overriding all settings), default: null 17 * Both point and volume are factors, point x/y/z can be between -1 and 1, volume between 0 and 1 */ 18 distribute?: ((cloud: CloudState, index: number) => { point: Vector3; volume?: number }) | null 19 /** Growth factor for animated clouds (speed > 0), default: 4 */ 20 growth?: number 21 /** Animation factor, default: 0 */ 22 speed?: number 23 /** Camera distance until the segments will fade, default: 10 */ 24 fade?: number 25 /** Opacity, default: 1 */ 26 opacity?: number 27 /** Color, default: white */ 28 color?: Color 29}
Usage
1// create main clouds group 2clouds = new Clouds({ texture: cloudTexture }) 3scene.add(clouds) 4 5// create cloud and add it to clouds group 6cloud_0 = new Cloud() 7clouds.add(cloud_0) 8// call "cloud_0.updateCloud()" after changing any cloud parameter to see latest changes 9 10// call in animate loop 11clouds.update(camera, clock.getElapsedTime(), clock.getDelta())
A y-up oriented, shader-based grid implementation.
1export type GridProps = { 2 /** plane-geometry size, default: [1,1] */ 3 args?: Array<number> 4 /** Cell size, default: 0.5 */ 5 cellSize?: number 6 /** Cell thickness, default: 0.5 */ 7 cellThickness?: number 8 /** Cell color, default: black */ 9 cellColor?: THREE.ColorRepresentation 10 /** Section size, default: 1 */ 11 sectionSize?: number 12 /** Section thickness, default: 1 */ 13 sectionThickness?: number 14 /** Section color, default: #2080ff */ 15 sectionColor?: THREE.ColorRepresentation 16 /** Follow camera, default: false */ 17 followCamera?: boolean 18 /** Display the grid infinitely, default: false */ 19 infiniteGrid?: boolean 20 /** Fade distance, default: 100 */ 21 fadeDistance?: number 22 /** Fade strength, default: 1 */ 23 fadeStrength?: number 24}
Usage
1grid = Grid({ 2 args: [10.5, 10.5], 3 cellSize: 0.6, 4 cellThickness: 1, 5 cellColor: new THREE.Color('#6f6f6f'), 6 sectionSize: 3.3, 7 sectionThickness: 1.5, 8 sectionColor: new THREE.Color('#9d4b4b'), 9 fadeDistance: 25, 10 fadeStrength: 1, 11 followCamera: false, 12 infiniteGrid: true, 13}) 14 15scene.add(grid.mesh) 16 17// call in animate loop 18grid.update(camera)
Grid function returns the following
1export type GridType = { 2 /* Mesh with gridMaterial to add to your scene */ 3 mesh: THREE.Mesh 4 /* Call in animate loop to update grid w.r.t camera */ 5 update: (camera: THREE.Camera) => void 6}
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
.
1export type OutlinesProps = { 2 /** Outline color, default: black */ 3 color?: THREE.Color 4 /** Line thickness is independent of zoom, default: false */ 5 screenspace?: boolean 6 /** Outline opacity, default: 1 */ 7 opacity?: number 8 /** Outline transparency, default: false */ 9 transparent?: boolean 10 /** Outline thickness, default 0.05 */ 11 thickness?: number 12 /** Geometry crease angle (0 === no crease), default: Math.PI */ 13 angle?: number 14 toneMapped?: boolean 15 polygonOffset?: boolean 16 polygonOffsetFactor?: number 17 renderOrder?: number 18 /** needed if `screenspace` is true */ 19 gl?: THREE.WebGLRenderer 20}
Usage
1const outlines = Outlines() 2const mesh = new THREE.Mesh(geometry, material) 3mesh.add(outlines.group) 4 5// must call generate() to create the outline mesh 6outlines.generate() 7 8scene.add(mesh)
Outlines function returns the following
1export type OutlinesType = { 2 group: THREE.Group 3 updateProps: (props: Partial<OutlinesProps>) => void 4 generate: () => void 5}
Adds a THREE.Group
that always faces the camera.
1export type BillboardProps = { 2 /** 3 * @default true 4 */ 5 follow?: boolean 6 /** 7 * @default false 8 */ 9 lockX?: boolean 10 /** 11 * @default false 12 */ 13 lockY?: boolean 14 /** 15 * @default false 16 */ 17 lockZ?: boolean 18}
Usage
1const billboard = Billboard() 2const mesh = new THREE.Mesh(geometry, material) 3billboard.group.add(mesh) 4 5scene.add(billboard.group) 6 7// call in animate loop 8billboard.update(camera)
Billboard function returns the following
1export type BillboardType = { 2 group: THREE.Group 3 /** 4 * Should called every frame to update the billboard 5 */ 6 update: (camera: THREE.Camera) => void 7 updateProps: (newProps: Partial<BillboardProps>) => void 8}
Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text.
A declarative abstraction around antimatter15/splat. It supports re-use, multiple splats with correct depth sorting, splats can move and behave as a regular object3d's, supports alphahash & alphatest, and stream-loading.
1const loader = new SplatLoader(renderer)
2
3const [shoeSplat, plushSplat, kitchenSplat] = await Promise.all([
4 loader.loadAsync(`shoe.splat`),
5 loader.loadAsync(`plush.splat`),
6 loader.loadAsync(`kitchen.splat`),
7])
8
9const shoe1 = new Splat(shoeSplat, camera, { alphaTest: 0.1 })
10shoe1.position.set(0, 1.6, 2)
11scene.add(shoe1)
12
13// This will re-use the same data, only one load, one parse, one worker, one buffer
14const shoe2 = new Splat(shoeSplat, camera, { alphaTest: 0.1 })
15scene.add(shoe2)
16
17const plush = new Splat(plushSplat, camera, { alphaTest: 0.1 })
18scene.add(plush)
19
20const kitchen = new Splat(kitchenSplat, camera)
21scene.add(kitchen)
In order to depth sort multiple splats correctly you can either use alphaTest, for instance with a low value. But keep in mind that this can show a slight outline under some viewing conditions.
You can also use alphaHash, but this can be slower and create some noise, you would typically get rid of the noise in postprocessing with a TAA pass. You don't have to use alphaHash on all splats.
1const plush = new Splat(plushSplat, camera, { alphaHash: true })
1type SpriteAnimatorProps = { 2 /** The start frame of the animation */ 3 startFrame?: number 4 /** The end frame of the animation */ 5 endFrame?: number 6 /** The desired frames per second of the animaiton */ 7 fps?: number 8 /** The frame identifier to use, has to be one of animationNames */ 9 frameName?: string 10 /** The URL of the texture JSON (if using JSON-Array or JSON-Hash) */ 11 textureDataURL?: string 12 /** The URL of the texture image */ 13 textureImageURL?: string 14 /** Whether or not the animation should loop */ 15 loop?: boolean 16 /** The number of frames of the animation (required if using plain spritesheet without JSON) */ 17 numberOfFrames?: number 18 /** Whether or not the animation should auto-start when all assets are loaded */ 19 autoPlay?: boolean 20 /** The animation names of the spritesheet (if the spritesheet -with JSON- contains more animation sequences) */ 21 animationNames?: Array<string> 22 /** Event callback when the animation starts */ 23 onStart?: Function 24 /** Event callback when the animation ends */ 25 onEnd?: Function 26 /** Event callback when the animation loops */ 27 onLoopEnd?: Function 28 /** Event callback when each frame changes */ 29 onFrame?: Function 30 /** Control when the animation runs */ 31 play?: boolean 32 /** Control when the animation pauses */ 33 pause?: boolean 34 /** Whether or not the Sprite should flip sides on the x-axis */ 35 flipX?: boolean 36 /** Sets the alpha value to be used when running an alpha test. https://threejs.org/docs/#api/en/materials/Material.alphaTest */ 37 alphaTest?: number 38 /** Displays the texture on a SpriteGeometry always facing the camera, if set to false, it renders on a PlaneGeometry */ 39 asSprite?: boolean 40}
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:
.update()
method added to requestAnimation frame loop to for efficient frame updates and rendering.Usage
1const alienSpriteAnimator = SpriteAnimator({
2 startFrame: 0,
3 autoPlay: true,
4 loop: true,
5 numberOfFrames: 16,
6 alphaTest: 0.01,
7 textureImageURL: './sprites/alien.png',
8})
9await AlienSpriteAnimator.init() // file fetching happens here
10
11alienSpriteAnimator.group.position.set(0, 0.5, 2)
12
13scene.add(alienSpriteAnimator.group)
SpriteAnimator function returns the following object
1export type SpriteAnimatorType = { 2 group: THREE.Group // A reference to the THREE.Group used for holding the sprite or plane. 3 init: Function // Function to initialize, fetch the files and start the animations. 4 update: Function // Function to update the sprite animation, needs to be called every frame. 5 pauseAnimation: Function // Function to pause the animation. 6 playAnimation: Function // Function to play the animation. 7 setFrameName: Function // Function to set the frame identifier to use, has to be one of animationNames. 8}
A material that creates a portal into another scene. It is drawn onto the geometry of the mesh that it is applied to. It uses RenderTexture internally, but counteracts the perspective shift of the texture surface, the portals contents are thereby masked by it but otherwise in the same position as if they were in the original scene.
1export type PortalMaterialType = { 2 /** Texture from WebGLRenderTarget */ 3 map: THREE.Texture 4 /** vector 2 containing three.js canvas resolution to keep the portals aligned*/ 5 resolution: THREE.Vector2 6 /** sdf texture to fade the edges of the portal */ 7 sdf?: THREE.Texture | null 8 /** edge fade blur when using sdf texture */ 9 blur: number 10}
Usage:
1const rendererSize = new THREE.Vector2()
2const portalRenderTarget = new THREE.WebGLRenderTarget(512, 512)
3
4const scene = new THREE.Scene() // main scene
5const portalScene = new THREE.Scene() // content inside portal
6
7const portalGeometry = new THREE.PlaneGeometry(2, 2)
8const portalMaterial = new MeshPortalMaterial({
9 map: portalRenderTarget.texture,
10 resolution: rendererSize,
11})
12portalMesh = new THREE.Mesh(portalGeometry, portalMaterial)
13
14// During resize: update the rendererSize Vector2
15window.onresize = () => {
16 ...
17 renderer.getSize(rendererSize)
18 rendererSize.multiplyScalar(renderer.getPixelRatio())
19}
20
21// In the animation loop
22renderer.setAnimationLoop(() => {
23 // render portal scene
24 renderer.setRenderTarget(portalRenderTarget)
25 renderer.render(portalScene, camera)
26 renderer.setRenderTarget(null)
27
28 // render main scene
29 renderer.render(scene, camera)
30})
You can optionally fade or blur the edges of the portal by providing a sdf texture, do not forget to make the material transparent in that case. It uses SDF flood-fill to determine the shape, you can thereby blur any geometry. Import the helper function meshPortalMaterialApplySDF
to auto apply the sdf mask.
1// Create portal material with SDF and edge blur
2const portalMaterial = new MeshPortalMaterial({
3 map: portalRenderTarget.texture,
4 resolution: rendererSize,
5 transparent: true, // Transparency is required for fading/blur
6 blur: 0.5, // Adjust edge blur
7})
8
9// Auto-apply SDF mask to the mesh
10portalMesh = new THREE.Mesh(portalGeometry, portalMaterial)
11meshPortalMaterialApplySDF(portalMesh, 512, renderer) // 512 is SDF texture resolution
12scene.add(portalMesh)
No vulnerabilities found.
No security vulnerabilities found.