SKILL.md
readonlyread-only
name
threejs-shaders
description
Three.js 著色器 - GLSL、ShaderMaterial、uniforms、自訂特效。用於建立自訂視覺特效、修改頂點、撰寫片段著色器或擴充內建材質。
Three.js 著色器
快速開始
import * as THREE from "three";
const material = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
color: { value: new THREE.Color(0xff0000) },
},
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 color;
void main() {
gl_FragColor = vec4(color, 1.0);
}
`,
});
// 在動畫迴圈中更新
material.uniforms.time.value = clock.getElapsedTime();
ShaderMaterial vs RawShaderMaterial
ShaderMaterial
Three.js 提供內建的 uniforms 與 attributes。
const material = new THREE.ShaderMaterial({
vertexShader: `
// 可用的內建 uniforms:
// uniform mat4 modelMatrix;
// uniform mat4 modelViewMatrix;
// uniform mat4 projectionMatrix;
// uniform mat4 viewMatrix;
// uniform mat3 normalMatrix;
// uniform vec3 cameraPosition;
// 可用的內建 attributes:
// attribute vec3 position;
// attribute vec3 normal;
// attribute vec2 uv;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`,
});
RawShaderMaterial
完全控制 - 你需要定義所有東西。
const material = new THREE.RawShaderMaterial({
uniforms: {
projectionMatrix: { value: camera.projectionMatrix },
modelViewMatrix: { value: new THREE.Matrix4() },
},
vertexShader: `
precision highp float;
attribute vec3 position;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
precision highp float;
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`,
});
Uniforms
Uniform 類型
const material = new THREE.ShaderMaterial({
uniforms: {
// 數值
floatValue: { value: 1.5 },
intValue: { value: 1 },
// 向量
vec2Value: { value: new THREE.Vector2(1, 2) },
vec3Value: { value: new THREE.Vector3(1, 2, 3) },
vec4Value: { value: new THREE.Vector4(1, 2, 3, 4) },
// 顏色(轉換為 vec3)
colorValue: { value: new THREE.Color(0xff0000) },
// 矩陣
mat3Value: { value: new THREE.Matrix3() },
mat4Value: { value: new THREE.Matrix4() },
// 紋理
textureValue: { value: texture },
cubeTextureValue: { value: cubeTexture },
// 陣列
floatArray: { value: [1.0, 2.0, 3.0] },
vec3Array: {
value: [new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0)],
},
},
});
GLSL 宣告
// 在著色器中
uniform float floatValue;
uniform int intValue;
uniform vec2 vec2Value;
uniform vec3 vec3Value;
uniform vec3 colorValue; // 顏色變成 vec3
uniform vec4 vec4Value;
uniform mat3 mat3Value;
uniform mat4 mat4Value;
uniform sampler2D textureValue;
uniform samplerCube cubeTextureValue;
uniform float floatArray[3];
uniform vec3 vec3Array[2];
更新 Uniforms
// 直接賦值
material.uniforms.time.value = clock.getElapsedTime();
// 向量/顏色更新
material.uniforms.position.value.set(x, y, z);
material.uniforms.color.value.setHSL(hue, 1, 0.5);
// 矩陣更新
material.uniforms.matrix.value.copy(mesh.matrixWorld);
Varyings
將資料從頂點著色器傳遞到片段著色器。
const material = new THREE.ShaderMaterial({
vertexShader: `
varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vPosition;
void main() {
vUv = uv;
vNormal = normalize(normalMatrix * normal);
vPosition = (modelViewMatrix * vec4(position, 1.0)).xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vPosition;
void main() {
// 使用插值後的數值
gl_FragColor = vec4(vNormal * 0.5 + 0.5, 1.0);
}
`,
});
常見著色器模式
紋理取樣
const material = new THREE.ShaderMaterial({
uniforms: {
map: { value: texture },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform sampler2D map;
varying vec2 vUv;
void main() {
vec4 texColor = texture2D(map, vUv);
gl_FragColor = texColor;
}
`,
});
頂點位移
const material = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
amplitude: { value: 0.5 },
},
vertexShader: `
uniform float time;
uniform float amplitude;
void main() {
vec3 pos = position;
// 波浪位移
pos.z += sin(pos.x * 5.0 + time) * amplitude;
pos.z += sin(pos.y * 5.0 + time) * amplitude;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
void main() {
gl_FragColor = vec4(0.5, 0.8, 1.0, 1.0);
}
`,
});
菲涅耳效應
const material = new THREE.ShaderMaterial({
vertexShader: `
varying vec3 vNormal;
varying vec3 vWorldPosition;
void main() {
vNormal = normalize(normalMatrix * normal);
vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vWorldPosition;
void main() {
// cameraPosition 由 ShaderMaterial 自動提供
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float fresnel = pow(1.0 - dot(viewDirection, vNormal), 3.0);
vec3 baseColor = vec3(0.0, 0.0, 0.5);
vec3 fresnelColor = vec3(0.5, 0.8, 1.0);
gl_FragColor = vec4(mix(baseColor, fresnelColor, fresnel), 1.0);
}
`,
});
基於噪聲的效果
// 簡單的隨機函數
float random(vec2 st) {
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453);
}
// 值噪聲
float noise(vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);
float a = random(i);
float b = random(i + vec2(1.0, 0.0));
float c = random(i + vec2(0.0, 1.0));
float d = random(i + vec2(1.0, 1.0));
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
}
// 使用方式
float n = noise(vUv * 10.0 + time);
漸層
// 線性漸層
vec3 color = mix(colorA, colorB, vUv.y);
// 放射漸層
float dist = distance(vUv, vec2(0.5));
vec3 color = mix(centerColor, edgeColor, dist * 2.0);
// 自訂曲線的平滑漸層
float t = smoothstep(0.0, 1.0, vUv.y);
vec3 color = mix(colorA, colorB, t);
邊緣光
const material = new THREE.ShaderMaterial({
vertexShader: `
varying vec3 vNormal;
varying vec3 vViewPosition;
void main() {
vNormal = normalize(normalMatrix * normal);
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vViewPosition = mvPosition.xyz;
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vViewPosition;
void main() {
vec3 viewDir = normalize(-vViewPosition);
float rim = 1.0 - max(0.0, dot(viewDir, vNormal));
rim = pow(rim, 4.0);
vec3 baseColor = vec3(0.2, 0.2, 0.8);
vec3 rimColor = vec3(1.0, 0.5, 0.0);
gl_FragColor = vec4(baseColor + rimColor * rim, 1.0);
}
`,
});
溶解效果
uniform float progress;
uniform sampler2D noiseMap;
void main() {
float noise = texture2D(noiseMap, vUv).r;
if (noise < progress) {
discard;
}
// 邊緣發光
float edge = smoothstep(progress, progress + 0.1, noise);
vec3 edgeColor = vec3(1.0, 0.5, 0.0);
vec3 baseColor = vec3(0.5);
gl_FragColor = vec4(mix(edgeColor, baseColor, edge), 1.0);
}
擴充內建材質
onBeforeCompile
修改現有材質的著色器。
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
material.onBeforeCompile = (shader) => {
// 加入自訂 uniform
shader.uniforms.time = { value: 0 };
// 儲存參考以便更新
material.userData.shader = shader;
// 修改頂點著色器
shader.vertexShader = shader.vertexShader.replace(
"#include <begin_vertex>",
`
#include <begin_vertex>
transformed.y += sin(position.x * 10.0 + time) * 0.1;
`,
);
// 加入 uniform 宣告
shader.vertexShader = "uniform float time;\n" + shader.vertexShader;
};
// 在動畫迴圈中更新
if (material.userData.shader) {
material.userData.shader.uniforms.time.value = clock.getElapsedTime();
}
常見注入點
// 頂點著色器區塊
"#include <begin_vertex>"; // 在 position 計算之後
"#include <project_vertex>"; // 在 gl_Position 之後
"#include <beginnormal_vertex>"; // 法線計算開始
// 片段著色器區塊
"#include <color_fragment>"; // 在 diffuse color 之後
"#include <output_fragment>"; // 最終輸出
"#include <fog_fragment>"; // 在 fog 套用之後
GLSL 內建函數
數學函數
// 基本
abs(x), sign(x), floor(x), ceil(x), fract(x)
mod(x, y), min(x, y), max(x, y), clamp(x, min, max)
mix(a, b, t), step(edge, x), smoothstep(edge0, edge1, x)
// 三角函數
sin(x), cos(x), tan(x)
asin(x), acos(x), atan(y, x), atan(x)
radians(degrees), degrees(radians)
// 指數函數
pow(x, y), exp(x), log(x), exp2(x), log2(x)
sqrt(x), inversesqrt(x)
向量函數
// 長度與距離
length(v), distance(p0, p1), dot(x, y), cross(x, y)
// 正規化
normalize(v)
// 反射與折射
reflect(I, N), refract(I, N, eta)
// 逐分量比較
lessThan(x, y), lessThanEqual(x, y)
greaterThan(x, y), greaterThanEqual(x, y)
equal(x, y), notEqual(x, y)
any(bvec), all(bvec)
紋理函數
// GLSL 1.0(預設)- 使用 texture2D/textureCube
texture2D(sampler, coord)
texture2D(sampler, coord, bias)
textureCube(sampler, coord)
// GLSL 3.0(glslVersion: THREE.GLSL3)- 使用 texture()
// texture(sampler, coord) 取代 texture2D/textureCube
// 另外使用 out vec4 fragColor 取代 gl_FragColor
// 紋理大小(GLSL 1.30+)
textureSize(sampler, lod)
常見材質屬性
const material = new THREE.ShaderMaterial({
uniforms: {
/* ... */
},
vertexShader: "/* ... */",
fragmentShader: "/* ... */",
// 渲染
transparent: true,
opacity: 1.0,
side: THREE.DoubleSide,
depthTest: true,
depthWrite: true,
// 混合
blending: THREE.NormalBlending,
// AdditiveBlending, SubtractiveBlending, MultiplyBlending
// 線框
wireframe: false,
wireframeLinewidth: 1, // 注意:>1 在大多數平台上無效(WebGL 限制)
// 擴充功能
extensions: {
derivatives: true, // 用於 fwidth, dFdx, dFdy
fragDepth: true, // gl_FragDepth
drawBuffers: true, // 多重渲染目標
shaderTextureLOD: true, // texture2DLod
},
// GLSL 版本
glslVersion: THREE.GLSL3, // 用於 WebGL2 功能
});
著色器包含
使用 Three.js 著色器區塊
import { ShaderChunk } from "three";
const fragmentShader = `
${ShaderChunk.common}
${ShaderChunk.packing}
uniform sampler2D depthTexture;
varying vec2 vUv;
void main() {
float depth = texture2D(depthTexture, vUv).r;
float linearDepth = perspectiveDepthToViewZ(depth, 0.1, 1000.0);
gl_FragColor = vec4(vec3(-linearDepth / 100.0), 1.0);
}
`;
外部著色器檔案
// 搭配 vite/webpack
import vertexShader from "./shaders/vertex.glsl";
import fragmentShader from "./shaders/fragment.glsl";
const material = new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
});
實例化著色器
// 實例化 attribute
const offsets = new Float32Array(instanceCount * 3);
// 填入 offsets...
geometry.setAttribute("offset", new THREE.InstancedBufferAttribute(offsets, 3));
const material = new THREE.ShaderMaterial({
vertexShader: `
attribute vec3 offset;
void main() {
vec3 pos = position + offset;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`,
});
除錯著色器
// 檢查編譯錯誤
material.onBeforeCompile = (shader) => {
console.log("頂點著色器:", shader.vertexShader);
console.log("片段著色器:", shader.fragmentShader);
};
// 視覺除錯
fragmentShader: `
void main() {
// 除錯 UV
gl_FragColor = vec4(vUv, 0.0, 1.0);
// 除錯法線
gl_FragColor = vec4(vNormal * 0.5 + 0.5, 1.0);
// 除錯位置
gl_FragColor = vec4(vPosition * 0.1 + 0.5, 1.0);
}
`;
// 檢查 WebGL 錯誤
renderer.debug.checkShaderErrors = true;
效能提示
- 最小化 uniforms:將相關數值分組為向量
- 避免條件判斷:使用 mix/step 取代 if/else
- 預先計算:盡可能將計算移到 JavaScript
- 使用紋理:對於複雜函數,使用查找表
- 限制 overdraw:盡量避免透明物件
// 與其用:
if (value > 0.5) {
color = colorA;
} else {
color = colorB;
}
// 改用:
color = mix(colorB, colorA, step(0.5, value));
另請參閱
threejs-materials- 內建材質類型threejs-postprocessing- 全螢幕著色器效果threejs-textures- 著色器中的紋理取樣






