跳到主要内容
← Signed Distance Field

Signed Distance Field

SDF Box Blur

shader-learning 自学第 16 课:SDF Box Blur

实时渲染 · 2D 片段 GLSL

第 16 课:SDF Box Blur

实现

uniform vec2 iResolution;

const vec3 shapeColor      = vec3(1.0, 0.3, 0.3);
const vec3 backgroundColor = vec3(0.12);

float sdfCircle(vec2 center, float r, vec2 pos) {
  return distance(center, pos) - r;
}

float drawCircle(vec2 pos) {
  float t = sdfCircle(iResolution * 0.5, iResolution.y * 0.4, pos);
  return t;
}

float blurSDF(vec2 pos){
  int RADIUS = 5;

  float result = 0.0;
  for (int dx = -RADIUS; dx <= RADIUS; dx++) {
    for (int dy = -RADIUS; dy <= RADIUS; dy++) {
      vec2 offset = vec2(dx, dy) * 2.0;
      float sdf = drawCircle(pos + offset);

      result += clamp(sdf, 0.0, 1.0);
    }
  }

  float N = (float(RADIUS) * 2.0 + 1.0);
  N *= N;

  return result / N;
}

void main() {
  vec2 uv = gl_FragCoord.xy;

  float t = blurSDF(uv);
  t = clamp(t, 0.0, 1.0);

  gl_FragColor = vec4(mix(shapeColor, backgroundColor, t), 1.0);
}