AI Skill Library

WebGL & GLSL Shaders

WebGL pipeline, vertex and fragment shaders, uniforms, varyings, common effects.

webglglslshader3dfrontend
# WebGL & GLSL Shaders

## WebGL pipeline
CPU (JS) -> Vertex Shader (runs per vertex) -> Rasterization -> Fragment Shader (runs per pixel) -> Screen

## Minimal WebGL program
```js
const canvas = document.querySelector('canvas')
const gl = canvas.getContext('webgl2')

const vert = `#version 300 es
in vec2 a_pos;
void main() { gl_Position = vec4(a_pos, 0, 1); }`

const frag = `#version 300 es
precision highp float;
out vec4 outColor;
void main() { outColor = vec4(1, 0.5, 0, 1); }` // orange

function compile(type, src) {
  const s = gl.createShader(type)
  gl.shaderSource(s, src)
  gl.compileShader(s)
  return s
}
const prog = gl.createProgram()
gl.attachShader(prog, compile(gl.VERTEX_SHADER, vert))
gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, frag))
gl.linkProgram(prog)
gl.useProgram(prog)

const buf = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buf)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, 0,1]), gl.STATIC_DRAW)
const loc = gl.getAttribLocation(prog, 'a_pos')
gl.enableVertexAttribArray(loc)
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLES, 0, 3)
```

## GLSL types
`float`, `int`, `bool`
`vec2`, `vec3`, `vec4` -- float vectors
`mat2`, `mat3`, `mat4` -- matrices
`sampler2D`, `samplerCube` -- textures

## Uniforms (JS -> shader)
```glsl
uniform float u_time;
uniform vec2 u_resolution;
uniform sampler2D u_texture;
```
```js
const loc = gl.getUniformLocation(prog, 'u_time')
gl.uniform1f(loc, performance.now() / 1000)
```

## Common patterns in Three.js ShaderMaterial
```glsl
// Vertex shader
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

// Fragment shader
uniform float uTime;
varying vec2 vUv;
void main() {
  vec3 color = vec3(vUv, abs(sin(uTime)));
  gl_FragColor = vec4(color, 1.0);
}
```

## Built-in GLSL functions
`sin`, `cos`, `abs`, `fract`, `floor`, `ceil`, `mod`, `clamp`, `mix`, `step`, `smoothstep`
`length`, `normalize`, `dot`, `cross`, `reflect`, `refract`
`texture2D(sampler, uv)`

## Common effects
- **Noise**: Simplex / Perlin noise for organic motion
- **SDF (Signed Distance Fields)**: render shapes without geometry
- **Fresnel**: edge glow effect -- `pow(1.0 - dot(normal, viewDir), 3.0)`
- **Displacement**: offset vertex position with noise in vertex shader
- **Post-processing**: render to texture, then apply full-screen quad shader

## Tools
- Shadertoy.com -- live GLSL playground
- glsl-canvas VSCode extension
- Book of Shaders (thebookofshaders.com) -- interactive tutorial

API: /api/skills/webgl-glsl