README
Custom Shader Material
Extend Three.js standard materials with your own shaders!
The demo is real, you can click it! It contains full code, too. 📦
Custom Shader Material (CSM) lets you extend Three.js' material library with your own Vertex and Fragment shaders.
import CustomShaderMaterial from 'three-custom-shader-material'
function Cube() {
const materialRef = useRef()
useFrame((state) => {
if (materialRef.current) {
materialRef.current.uniforms.uTime.value = state.clock.elapsedTime
}
})
return (
<mesh>
<boxGeometry />
<CustomShaderMaterial
ref={materialRef}
baseMaterial={THREE.MeshPhysicalMaterial}
vertexShader={/* glsl */ ` ... `}
fragmentShader={/* glsl */ ` ... `}
uniforms={{
uTime: {
value: 0,
},
}}
flatShading
color={0xff00ff}
// ...
/>
</mesh>
)
}
Show Typescript example
import CustomShaderMaterial from 'three-custom-shader-material'
import CustomShaderMaterialType from 'three-custom-shader-material/vanilla'
function Cube() {
const materialRef = useRef<CustomShaderMaterialType | null>(null)
useFrame((state) => {
if (materialRef.current) {
materialRef.current.uniforms.uTime.value = state.clock.elapsedTime
}
})
return (
<mesh>
<boxGeometry />
<CustomShaderMaterial
ref={materialRef}
baseMaterial={THREE.MeshPhysicalMaterial}
vertexShader={/* glsl */ ` ... `}
fragmentShader={/* glsl */ ` ... `}
uniforms={{
uTime: {
value: 0,
},
}}
flatShading
color={0xff00ff}
// ...
/>
</mesh>
)
}
Show VanillaJS example
import CustomShaderMaterial from 'three-custom-shader-material/vanilla'
function Box() {
const geometry = new THREE.BoxGeometry()
const material = new CustomShaderMaterial({
THREE.MeshPhysicalMaterial // baseMaterial
/* glsl */ ` ... `, // vertexShader
/* glsl */ ` ... `, // fragmentShader
{ uTime: {
value: 0, // uniforms
},
},
{
flatShading: true // options
color: 0xff00ff
}
})
return new THREE.Mesh(geometry, material)
}
Installation
npm
npm install three-custom-shader-material
Yarn
yarn add three-custom-shader-material
Output Variables
CSM provides the following output variables:
Variable | Required | Type | Description | Available In | Notes |
---|---|---|---|---|---|
csm_Position | ❌ | vec3 |
Custom vertex position. | Vertex Shader | csm_Position will be multiplied by projectionMatrix and modelViewPosition furthur down the line. |
csm_Normal | ❌ | vec3 |
Custom vertex normals. | Vertex Shader | |
csm_PointSize | ❌ | float |
Custom gl_PointSize. | Vertex Shader | |
csm_DiffuseColor | ❌ | vec4 |
Custom diffuse color. | Fragment Shader | |
csm_FragColor | ❌ | vec4 |
Custom gl_FragColor. | Fragment Shader |
You must use these variables like you would use standard GLSL output variables.
// gl_Position = projectionMatrix * modelViewPosition * position * vec3(2.0);
csm_Position = position * vec3(2.0);
Credits
Icon made by Freepik from www.flaticon.com.