GLSL フラグメントシェーダー
GPU で並列実行されるフラグメントシェーダーを記述し、プロシージャルグラフィックス、テクスチャ、視覚効果を生成します。
使用するタイミング
- プロシージャルテクスチャ(木目、大理石、雲、地形)の作成
- 距離関数(SDF)を用いた形状の描画
- パターン、ノイズ、グラデーションの生成
- 視覚効果とアニメーションの構築
- Three.js、WebGL、Processing 向けのカスタムシェーダーの記述
中核となる概念
フラグメントシェーダーはすべてのピクセルで同時に実行されます。各スレッドは:
- ピクセル位置を
gl_FragCoordで受け取る gl_FragColor(vec4: RGBA 0.0〜1.0)で色を返す- 他のスレッドと通信できない(ステートレス)
標準ユニフォーム
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 ユニフォーム
外部リソース
- The Book of Shaders: https://thebookofshaders.com
- LYGIAライブラリ: https://lygia.xyz (再利用可能なシェーダー関数)
- ShaderToy: https://shadertoy.com
- Inigo Quilezの記事: https://iquilezles.org/articles/