首先将上节的绘制笑脸整合为函数Smiley(uv, p, size):p为笑脸中心位置,size为笑脸尺度。
float Circle(vec2 uv, vec2 p, float r, float blur)
{
float d = length(uv - p);
float c = smoothstep(r, r-blur, d);
return c;
}
float Smiley(vec2 uv, vec2 p, float size)
{
uv -= p;
uv /= size;
float c = Circle(uv, vec2(0.0), 0.4, 0.05);
c -= Circle(uv, vec2(-0.13, 0.2), 0.07, 0.01);
c -= Circle(uv, vec2(0.13, 0.2), 0.07, 0.01);
float mouth = Circle(uv, vec2(0.0, 0.0), 0.3, 0.02);
mouth -= Circle(uv, vec2(0.0, 0.1), 0.3, 0.02);
mouth = (mouth == 1.0)? 1.0 : 0.0;
c -= mouth;
return c;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = fragCoord/iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
float mask = Smiley(uv, vec2(0.3, 0.3), 1.25);
vec3 col = vec3(0.0);
col = vec3(1.0, 1.0, 0.0) * mask; // yellow
// Output to screen
fragColor = vec4(col,1.0);
}
接下来我们使用平滑阶梯smoothstep()函数绘制矩形
首先可以绘制边界:可以看做边界x值为-0.15,blur为0.05;
c = smoothstep(-0.2, -0.1, uv.x);
绘制右边白转黑边界:可以看做边界x值为0.15,blur为0.05;
c = smoothstep(0.2, 0.1, uv.x);
我们可以编写边界Band函数:使用乘法来取相交的白色部分
float Band(float t, float start, float end, float blur)
{
float step1 = smoothstep(start-blur, start+blur, t);
float step2 = smoothstep(end+blur, end-blur, t);
return step1 * step2;
}
c = Band(uv.x, -0.2, 0.2, 0.01);
由此,我们可以扩展得到我们绘制矩阵的函数:
float Rect(vec2 uv, float left, float right, float bottom, float top, float blur)
{
float band1 = Band(uv.x, left, right, blur);
float band2 = Band(uv.y, bottom, top, blur);
return band1 * band2;
}
c = Rect(uv, -0.5, 0.4, -0.3, 0.2, 0.01);
整体代码:
float Band(float t, float start, float end, float blur)
{
float step1 = smoothstep(start-blur, start+blur, t);
float step2 = smoothstep(end+blur, end-blur, t);
return step1 * step2;
}
float Rect(vec2 uv, float left, float right, float bottom, float top, float blur)
{
float band1 = Band(uv.x, left, right, blur);
float band2 = Band(uv.y, bottom, top, blur);
return band1 * band2;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Normalized pixel coordinates (from 0 to 1)
vec2 uv = fragCoord/iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
float c = 0.0;
c = Rect(uv, -0.5, 0.4, -0.3, 0.2, 0.01);
vec3 col = vec3(0.0);
col = vec3(1.0, 1.0, 1.0) * c;
// Output to screen
fragColor = vec4(col,1.0);
}