跳到主要内容
← Signed Distance Field

Signed Distance Field

SDF Rotation

shader-learning 自学第 9 课:SDF Rotation

实时渲染 · 2D 片段 GLSL

第 9 课:SDF Rotation

实现

uniform vec2 iResolution;
uniform float iTime;

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 drawPental(vec2 uv) {
  float r  = iResolution.y * 0.3;

  vec2 center0 = iResolution * vec2(0.0, 0.0);

  vec2 center1 = iResolution * vec2(-0.03, 0.0) + vec2(+r, +r);
  vec2 center2 = iResolution * vec2(+0.03, 0.0) + vec2(-r, +r);

  float c0 = sdfCircle(center0, r * 0.3, uv);

  float c1 = sdfCircle(center1, r, uv);
  float c2 = sdfCircle(center2, r, uv);

  return min(max(c1, c2), c0);
}

mat2 rotation(float theta){
  return transpose(mat2(
    vec2(cos(theta),-sin(theta)),
    vec2(sin(theta),cos(theta))
  ));
}

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

  // make 0 the center
  uv.x -= iResolution.x * 0.5;
  uv.y -= iResolution.y * 0.5;

  float t = 1.0;
  int steps = 20;
  for (int i = 0; i < steps; i++) {
    float ti = drawPental(rotation(float(i)*2.0*3.14/float(steps))* uv);
    t = min(t, ti);
  }
  t = clamp(t, 0.0, 1.0);


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