• This repository has been archived on 05/Apr/2023
  • Stars
    star
    1,005
  • Rank 45,700 (Top 1.0 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 3 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

๐Ÿฐ An extensible, layer based shader material for ThreeJS

lamina

๐Ÿฐ An extensible, layer based shader material for ThreeJS


Chat on Twitter Chat on Twitter


These demos are real, you can click them! They contain the full code, too. ๐Ÿ“ฆ More examples here


Notice

From @farazzshaikh: Lamina has been archived as of April 5 2023.

This project needs maintainers and a good rewrite from scratch. Lamina does a lot of hacky processing to achieve its API goals. As time has gone by I have started to doubt if itโ€™s worth it. These hacks make it unreliable, unpredictable and slow. Not to mentaion, quite convoluted to maintain and debug. There might be better APIs or implimentations for this kind of library but I currently do not have the bandwidth to dedicate to finding them. Perhaps in the future.

Lamina is built on top of three-custom-shader-material (CSM) and any effects that are achieved by lamina can be done with CSM in a predictable and performant manner albeit at a lower level.

Feel free to use Lamina, however, support will be lacking. If you'd like to resurrect this library, then feel free to reach out on our Discord and tag me (Faraz#9759).


lamina lets you create materials with a declarative, system of layers. Layers make it incredibly easy to stack and blend effects. This approach was first made popular by the Spline team.

import { LayerMaterial, Depth } from 'lamina'

function GradientSphere() {
  return (
    <Sphere>
      <LayerMaterial
        color="#ffffff" //
        lighting="physical"
        transmission={1}
      >
        <Depth
          colorA="#810000" //
          colorB="#ffd0d0"
          alpha={0.5}
          mode="multiply"
          near={0}
          far={2}
          origin={[1, 1, 1]}
        />
      </LayerMaterial>
    </Sphere>
  )
}
Show Vanilla example

Lamina can be used with vanilla Three.js. Each layer is just a class.

import { LayerMaterial, Depth } from 'lamina/vanilla'

const geometry = new THREE.SphereGeometry(1, 128, 64)
const material = new LayerMaterial({
  color: '#d9d9d9',
  lighting: 'physical',
  transmission: 1,
  layers: [
    new Depth({
      colorA: '#002f4b',
      colorB: '#f2fdff',
      alpha: 0.5,
      mode: 'multiply',
      near: 0,
      far: 2,
      origin: new THREE.Vector3(1, 1, 1),
    }),
  ],
})

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

Note: To match the colors of the react example, you must convert all colors to Linear encoding like so:

new Depth({
  colorA: new THREE.Color('#002f4b').convertSRGBToLinear(),
  colorB: new THREE.Color('#f2fdff').convertSRGBToLinear(),
  alpha: 0.5,
  mode: 'multiply',
  near: 0,
  far: 2,
  origin: new THREE.Vector3(1, 1, 1),
}),

Layers

LayerMaterial

LayerMaterial can take in the following parameters:

Prop Type Default
name string "LayerMaterial"
color THREE.ColorRepresentation | THREE.Color "white"
alpha number 1
lighting 'phong' | 'physical' | 'toon' | 'basic' | 'lambert' | 'standard' 'basic'
layers* Abstract[] []

The lighting prop controls the shading that is applied on the material. The material then accepts all the material properties supported by ThreeJS of the material type specified by the lighting prop.

* Note: the layers prop is only available on the LayerMaterial class, not the component. Pass in layers as children in React.

Built-in layers

Here are the layers that lamina currently provides

Name Function
Fragment Layers
Color Flat color.
Depth Depth based gradient.
Fresnel Fresnel shading (strip or rim-lights).
Gradient Linear gradient.
Matcap Load in a Matcap.
Noise White, perlin or simplex noise .
Normal Visualize vertex normals.
Texture Image texture.
Vertex Layers
Displace Displace vertices using. noise

See the section for each layer for the options on it.

Debugger

Lamina comes with a handy debugger that lets you tweek parameters till you're satisfied with the result! Then, just copy the JSX and paste!

Replace LayerMaterial with DebugLayerMaterial to enable it.

<DebugLayerMaterial color="#ffffff">
  <Depth
    colorA="#810000" //
    colorB="#ffd0d0"
    alpha={0.5}
    mode="multiply"
    near={0}
    far={2}
    origin={[1, 1, 1]}
  />
</DebugLayerMaterial>

Any custom layers are automatically compatible with the debugger. However, for advanced inputs, see the Advanced Usage section.

Writing your own layers

You can write your own layers by extending the Abstract class. The concept is simple:

Each layer can be treated as an isolated shader program that produces a vec4 color.

The color of each layer will be blended together using the specified blend mode. A list of all available blend modes can be found here

import { Abstract } from 'lamina/vanilla'

// Extend the Abstract layer
class CustomLayer extends Abstract {
  // Define stuff as static properties!

  // Uniforms: Must begin with prefix "u_".
  // Assign them their default value.
  // Any unifroms here will automatically be set as properties on the class as setters and getters.
  // There setters and getters will update the underlying unifrom.
  static u_color = 'red' // Can be accessed as CustomLayer.color
  static u_alpha = 1 // Can be accessed as CustomLayer.alpha

  // Define your fragment shader just like you already do!
  // Only difference is, you must return the final color of this layer
  static fragmentShader = `   
    uniform vec3 u_color;
    uniform float u_alpha;

    // Varyings must be prefixed by "v_"
    varying vec3 v_Position;

    vec4 main() {
      // Local variables must be prefixed by "f_"
      vec4 f_color = vec4(u_color, u_alpha);
      return f_color;
    }
  `

  // Optionally Define a vertex shader!
  // Same rules as fragment shaders, except no blend modes.
  // Return a non-projected vec3 position.
  static vertexShader = `   
    // Varyings must be prefixed by "v_"
    varying vec3 v_Position;

    void main() {
      v_Position = position;
      return position * 2.;
    }
  `

  constructor(props) {
    // You MUST call `super` with the current constructor as the first argument.
    // Second argument is optional and provides non-uniform parameters like blend mode, name and visibility.
    super(CustomLayer, {
      name: 'CustomLayer',
      ...props,
    })
  }
}

๐Ÿ‘‰ Note: The vertex shader must return a vec3. You do not need to set gl_Position or transform the model view. lamina will handle this automatically down the chain.

๐Ÿ‘‰ Note: You can use lamina's noise functions inside of your own layer without any additional imports: lamina_noise_perlin(), lamina_noise_simplex(), lamina_noise_worley(), lamina_noise_white(), lamina_noise_swirl().

If you need a specialized or advance use-case, see the Advanced Usage section

Using your own layers

Custom layers are Vanilla compatible by default.

To use them with React-three-fiber, you must use the extend function to add the layer to your component library!

import { extend } from "@react-three/fiber"

extend({ CustomLayer })

// ...
const ref = useRef();

// Animate uniforms using a ref.
useFrame(({ clock }) => {
  ref.current.color.setRGB(
    Math.sin(clock.elapsedTime),
    Math.cos(clock.elapsedTime),
    Math.sin(clock.elapsedTime),
  )
})

<LayerMaterial>
  <customLayer
    ref={ref}     // Imperative instance of CustomLayer. Can be used to animate unifroms
    color="green" // Uniforms can be set directly
    alpha={0.5}
  />
</LayerMaterial>

Advanced Usage

For more advanced custom layers, lamina provides the onParse event.

This event runs after the layer's shader and uniforms are parsed.

This means you can use it to inject functionality that isn't by the basic layer extension syntax.

Here is a common use case - Adding non-uniform options to layers that directly sub out shader code.

class CustomLayer extends Abstract {
  static u_color = 'red'
  static u_alpha = 1

  static vertexShader = `...`
  static fragmentShader = `
    // ...
    float f_dist = lamina_mapping_template; // Temp value, will be used to inject code later on.
    // ...
  `

  // Get some shader code based off mapping parameter
  static getMapping(mapping) {
    switch (mapping) {
      default:
      case 'uv':
        return `some_shader_code`

      case 'world':
        return `some_other_shader_code`
    }
  }

  // Set non-uniform defaults.
  mapping: 'uv' | 'world' = 'uv'

  // Non unifrom params must be passed to the constructor
  constructor(props) {
    super(
      CustomLayer,
      {
        name: 'CustomLayer',
        ...props,
      },
      // This is onParse callback
      (self: CustomLayer) => {
        // Add to Leva (debugger) schema.
        // This will create a dropdown select component on the debugger.
        self.schema.push({
          value: self.mapping,
          label: 'mapping',
          options: ['uv', 'world'],
        })

        // Get shader chunk based off selected mapping value
        const mapping = CustomLayer.getMapping(self.mapping)

        // Inject shader chunk in current layer's shader code
        self.fragmentShader = self.fragmentShader.replace('lamina_mapping_template', mapping)
      }
    )
  }
}

In react...

// ...
<LayerMaterial>
  <customLayer
    ref={ref}
    color="green"
    alpha={0.5}
    args={[mapping]} // Non unifrom params must be passed to the constructor using `args`
  />
</LayerMaterial>

Layers

Every layer has these props in common.

Prop Type Default
mode BlendMode "normal"
name string <this.constructor.name>
visible boolean true

All props are optional.

Color

Flat color.

Prop Type Default
color THREE.ColorRepresentation | THREE.Color "red"
alpha number 1

Normal

Visualize vertex normals

Prop Type Default
direction THREE.Vector3 | [number,number,number] [0, 0, 0]
alpha number 1

Depth

Depth based gradient. Colors are lerp-ed based on mapping props which may have the following values:

  • vector: distance from origin to fragment's world position.
  • camera: distance from camera to fragment's world position.
  • world: distance from fragment to center (0, 0, 0).
Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
near number 2
far number 10
origin THREE.Vector3 | [number,number,number] [0, 0, 0]
mapping "vector" | "camera" | "world" "vector"

Fresnel

Fresnel shading.

Prop Type Default
color THREE.ColorRepresentation | THREE.Color "white"
alpha number 1
power number 0
intensity number 1
bias number 2

Gradient

Linear gradient based off distance from start to end in a specified axes. start and end are points on the axes selected. The distance between start and end is used to lerp the colors.

Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
contrast number 1
start number 1
end number -1
axes "x" | "y" | "z" "x"
mapping "local" | "world" | "uv" "local"

Noise

Various noise functions.

Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
colorC THREE.ColorRepresentation | THREE.Color "white"
colorD THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
scale number 1
offset THREE.Vector3 | [number, number, number] [0, 0, 0]
mapping "local" | "world" | "uv" "local"
type "perlin' | "simplex" | "cell" | "curl" "perlin"

Matcap

Set a Matcap texture.

Prop Type Default
map THREE.Texture undefined
alpha number 1

Texture

Set a texture.

Prop Type Default
map THREE.Texture undefined
alpha number 1

BlendMode

Blend modes currently available in lamina

normal divide
add overlay
subtract screen
multiply softlight
lighten reflect
darken negation

Vertex layers

Layers that affect the vertex shader

Displace

Displace vertices with various noise.

Prop Type Default
strength number 1
scale number 1
mapping "local" | "world" | "uv" "local"
type "perlin' | "simplex" | "cell" | "curl" "perlin"
offset THREE.Vector3 | [number,number,number] [0, 0, 0]

More Repositories

1

zustand

๐Ÿป Bear necessities for state management in React
TypeScript
45,348
star
2

react-spring

โœŒ๏ธ A spring physics based React animation library
TypeScript
27,857
star
3

react-three-fiber

๐Ÿ‡จ๐Ÿ‡ญ A React renderer for Three.js
TypeScript
26,202
star
4

jotai

๐Ÿ‘ป Primitive and flexible state management for React
TypeScript
18,007
star
5

use-gesture

๐Ÿ‘‡Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
TypeScript
8,861
star
6

valtio

๐Ÿ’Š Valtio makes proxy-state simple for React and Vanilla
TypeScript
8,738
star
7

drei

๐Ÿฅ‰ useful helpers for react-three-fiber
JavaScript
8,042
star
8

leva

๐ŸŒ‹ React-first components GUI
TypeScript
4,825
star
9

gltfjsx

๐ŸŽฎ Turns GLTFs into JSX components
JavaScript
4,251
star
10

use-cannon

๐Ÿ‘‹๐Ÿ’ฃ physics based hooks for @react-three/fiber
TypeScript
2,700
star
11

react-three-next

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

postprocessing

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

racing-game

๐ŸŽ Open source racing game developed by everyone willing
TypeScript
2,120
star
14

xr

๐Ÿคณ VR/AR for react-three-fiber
TypeScript
2,051
star
15

uikit

๐ŸŽจ user interfaces for react-three-fiber
TypeScript
2,048
star
16

react-three-flex

๐Ÿ’ช๐Ÿ“ฆ Flexbox for react-three-fiber
TypeScript
1,640
star
17

suspend-react

๐Ÿšฅ Async/await for React components
TypeScript
1,358
star
18

react-postprocessing

๐Ÿ“ฌ postprocessing for react-three-fiber
JavaScript
1,074
star
19

detect-gpu

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

react-three-rapier

๐Ÿคบ Rapier physics in React
TypeScript
1,005
star
21

its-fine

๐Ÿถ๐Ÿ”ฅ A collection of escape hatches for React.
TypeScript
978
star
22

react-use-measure

๐Ÿ™Œ Utility to measure view bounds
TypeScript
832
star
23

react-nil

โƒ A react null renderer
TypeScript
785
star
24

maath

๐Ÿชถ Math helpers for the rest of us
TypeScript
783
star
25

threejs-journey

โš›๏ธ Bruno Simons journey demos in React
TypeScript
718
star
26

three-stdlib

๐Ÿ“š Stand-alone library of threejs examples designed to run without transpilation in node & browser
JavaScript
651
star
27

react-three-editor

๐Ÿ”Œ A one of a kind scene editor that writes changes back into your code
TypeScript
615
star
28

react-three-a11y

โ™ฟ๏ธ Accessibility tools for React Three Fiber
TypeScript
534
star
29

ecctrl

๐Ÿ•น๏ธ A floating rigibody character controller
TypeScript
498
star
30

react-three-offscreen

๐Ÿ“บ Offscreen worker canvas for react-three-fiber
TypeScript
443
star
31

react-zdog

โšก๏ธ๐Ÿถ React bindings for zdog
JavaScript
441
star
32

drei-vanilla

๐Ÿฆ drei-inspired helpers for threejs
TypeScript
436
star
33

use-asset

๐Ÿ“ฆ A promise caching strategy for React Suspense
TypeScript
413
star
34

tunnel-rat

๐Ÿ€ Non gratum anus rodentum
TypeScript
329
star
35

react-three-csg

๐Ÿšง Constructive solid geometry for React
TypeScript
264
star
36

react-three-lgl

๐Ÿ”† A React abstraction for the LGL Raycaster
TypeScript
262
star
37

gltf-react-three

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

market

๐Ÿ“ฆ Download CC0 assets ready to use in your next 3D Project
JavaScript
250
star
39

component-material

๐Ÿงฉ Compose modular materials in React
TypeScript
160
star
40

env

๐Ÿ’„ An app to create, edit, and preview HDR environment maps in the browser
TypeScript
151
star
41

react-ogl

๐Ÿฆด A barebones react renderer for ogl.
TypeScript
150
star
42

use-p2

๐Ÿ‘‹๐Ÿ’ฃ 2d physics hooks for @react-three/fiber
TypeScript
144
star
43

react-spring-examples

JavaScript
139
star
44

react-three-gpu-pathtracer

โšก๏ธ A React abstraction for the popular three-gpu-pathtracer
TypeScript
132
star
45

react-three-lightmap

In-browser lightmap/AO baker for react-three-fiber and ThreeJS
TypeScript
127
star
46

cannon-es-debugger

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

rafz

๐Ÿ’ One loop to frame them all.
TypeScript
96
star
48

docs

๐Ÿ–จ๏ธ mdx documentation generator for `pmndrs/*/docs` folders
TypeScript
91
star
49

assets

๐Ÿ“ฆ Importable base64 encoded CC0 assets
Makefile
91
star
50

swc-jotai

Rust
88
star
51

react-three-jolt

โšก Jolt physics in React
TypeScript
84
star
52

react-three-scissor

โœ‚ Multiple scenes, one canvas! WebGL Scissoring implementation for React Three Fiber.
TypeScript
79
star
53

eslint-plugin-valtio

An eslint plugin for better valtio experience
JavaScript
74
star
54

react-three-babel

๐Ÿ› A Babel plugin that automatically builds the extend catalogue of known native Three.js elements
TypeScript
60
star
55

react-spring.io

โœŒ๏ธ A spring physics based React animation library
TypeScript
56
star
56

r3f-website

Website for React Three Fiber
JavaScript
27
star
57

directed

A flexible, minimal scheduler written in TypeScript
TypeScript
24
star
58

market-assets

JavaScript
19
star
59

react-three-8thwall

JavaScript
17
star
60

drei-assets

JavaScript
16
star
61

discord

๐Ÿค– Poimandres Discord Bot
TypeScript
10
star
62

branding

TypeScript
7
star
63

market-assets-do

JavaScript
5
star
64

envinfo

Easily collect useful information for bug reports
JavaScript
4
star
65

leva-wg

1
star