GLSL 片段著色器
撰寫 GPU 加速的片段著色器,用於程序化圖形、紋理與視覺效果。
使用時機
- 建立程序化紋理(木紋、大理石、雲朵、地形)
- 使用距離場(SDF)繪製形狀
- 生成圖案、雜訊、漸層
- 建立視覺效果與動畫
- 為 Three.js、WebGL、Processing 撰寫自訂著色器
核心概念
片段著色器在每個像素上同時執行。每個執行緒:
- 透過
gl_FragCoord接收像素位置 - 透過
gl_FragColor(vec4:RGBA 0.0-1.0)回傳顏色 - 無法與其他執行緒通訊(無狀態)
標準 Uniform 變數
uniform float u_time; // 已流逝的秒數
uniform vec2 u_resolution; // 畫布大小(寬度, 高度)
uniform vec2 u_mouse; // 滑鼠位置(像素)
歸一化座標:vec2 st = gl_FragCoord.xy / u_resolution;
常用函式
| 函式 | 用途 | 範例 |
|---|---|---|
mix(a,b,t) | 線性插值 | mix(red, blue, 0.5) |
step(edge,x) | 硬閥值 | step(0.5, st.x) |
smoothstep(e0,e1,x) | 平滑閥值 | smoothstep(0.2, 0.8, st.x) |
fract(x) | 小數部分 | fract(st * 3.0) 用於平鋪 |
mod(x,y) | 模數 | mod(st.x, 0.25) |
clamp(x,min,max) | 限制數值 | clamp(col, 0.0, 1.0) |
length(v) | 向量長度 | length(st - 0.5) |
distance(a,b) | 歐幾里得距離 | distance(st, center) |
dot(a,b) | 內積 | dot(normal, lightDir) |
normalize(v) | 單位向量 | normalize(direction) |
atan(y,x) | 角度(弧度) | atan(st.y-0.5, st.x-0.5) |
sin/cos/pow/abs | 數學運算 | 硬體加速 |
快速範例
圓形:
float d = distance(st, vec2(0.5));
float circle = 1.0 - smoothstep(0.2, 0.21, d);
矩形:
vec2 bl = step(vec2(0.1), st);
vec2 tr = step(vec2(0.1), 1.0 - st);
float rect = bl.x * bl.y * tr.x * tr.y;
平鋪:
st = fract(st * 4.0); // 4x4 網格
動畫:
float wave = sin(st.x * 10.0 + u_time) * 0.5 + 0.5;
參考資料(漸進式揭露)
基礎
references/glsl-fundamentals-data-types-vectors-precision-coordinates.mdreferences/glsl-shaping-functions-step-smoothstep-curves-interpolation.md
繪圖
references/glsl-colors-rgb-hsb-gradients-mixing-color-spaces.mdreferences/glsl-shapes-sdf-circles-rectangles-polar-distance-fields.mdreferences/glsl-shapes-polygon-star-polar-sdf-combinations.md
程序化
references/glsl-patterns-tiling-fract-matrices-transformations.mdreferences/glsl-pattern-symmetry-truchet-domain-warping.mdreferences/glsl-noise-random-perlin-simplex-cellular-voronoi.mdreferences/glsl-cellular-voronoi-worley-noise-patterns.mdreferences/glsl-fbm-fractional-brownian-motion-turbulence-octaves.mdreferences/glsl-procedural-textures-clouds-marble-wood-terrain.md
API 參考
references/glsl-shader-builtin-functions-complete-api-reference.md
工具
- 線上編輯器: editor.thebookofshaders.com
- glslViewer: 用於執行 .frag 檔案的 CLI 工具
- glslCanvas: 用於嵌入即時著色器的 HTML 元件
- ShaderToy: 使用 iTime、iResolution、iMouse 等 Uniform 變數
外部資源
- The Book of Shaders:https://thebookofshaders.com
- LYGIA Library:https://lygia.xyz(可重複使用的著色器函式)
- ShaderToy:https://shadertoy.com
- Inigo Quilez 文章:https://iquilezles.org/articles/