SmoothStep
該函數(shù)用于求解兩個(gè)值之間的樣條插值。
函數(shù)用法
float smoothstep(float edge0, float edge1, float x)
vec2 smoothstep(vec2 edge0, vec2 edge1, vec2 x)
vec3 smoothstep(vec3 edge0, vec3 edge1, vec3 x)
vec4 smoothstep(vec4 edge0, vec4 edge1, vec4 x)
vec2 smoothstep(float edge0, float edge1, vec2 x)
vec3 smoothstep(float edge0, float edge1, vec3 x)
vec4 smoothstep(float edge0, float edge1, vec4 x)
解析
函數(shù)接受的輸入有三個(gè)俄精。其中:
edge0 代表樣條插值函數(shù)的下界刁笙;
edge1 代表樣條插值函數(shù)的上界改橘;
x 代表用于插值的源輸入滋尉。
該函數(shù)的輸出值是界于0到1之間的數(shù)。一般情況下飞主,如果我們想要?jiǎng)?chuàng)建一個(gè)能夠輸出平滑過(guò)渡的閾值函數(shù)狮惜,smoothstep就是很好的選擇。
背后計(jì)算介紹
smoothstep函數(shù)的背后計(jì)算等同于如下計(jì)算:
genType t;
t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
return (3.0 - 2.0 * t) * t * t;
即先按照給定的上界和下界對(duì)給定的源輸入進(jìn)行歸一化碌识,使輸出值在0到1之間碾篡。之后將該值運(yùn)用到樣條插值函數(shù)中。這里選用的插值函數(shù)為 (3.0 - 2.0 * t) * t * t筏餐。
當(dāng)edge0=0, edge1=1時(shí)开泽,橫軸為源輸入,縱軸為輸出(y = smoothstep(0.000, 1.0, x);魁瞪。則如下圖:
我們用shader腳本將線條畫(huà)出來(lái)看一下(片段著色器):
varying vec2 v_texCoord;
const float line_width = 3.0; // 線寬
vec3 line_color = vec3(1.0, 0.4, 0.0); // 線的顏色
vec3 background_color = vec3(0.0); // 背景的顏色
void main()
{
float delta = line_width * 0.001;
float x = v_texCoord.x;
float y = 1.0 - v_texCoord.y;
float line_y = smoothstep(0.0, 1.0, x);
if (abs(y - line_y) <= delta){
gl_FragColor = vec4(line_color, 1.0);
}
else{
gl_FragColor = vec4(background_color, 1.0);
}
}
結(jié)果如下圖: