SmoothStep
該函數(shù)用于求解兩個值之間的樣條插值。
函數(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ù)接受的輸入有三個。其中:
edge0 代表樣條插值函數(shù)的下界;
edge1 代表樣條插值函數(shù)的上界;
x 代表用于插值的源輸入。
該函數(shù)的輸出值是界于0到1之間的數(shù)。一般情況下,如果我們想要創(chuàng)建一個能夠輸出平滑過渡的閾值函數(shù),smoothstep就是很好的選擇。
背后計算介紹
smoothstep函數(shù)的背后計算等同于如下計算:
genType t;
t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
return (3.0 - 2.0 * t) * t * t;
即先按照給定的上界和下界對給定的源輸入進行歸一化,使輸出值在0到1之間。之后將該值運用到樣條插值函數(shù)中。這里選用的插值函數(shù)為 (3.0 - 2.0 * t) * t * t。
當edge0=0, edge1=1時,橫軸為源輸入,縱軸為輸出(y = smoothstep(0.000, 1.0, x);。則如下圖:

我們用shader腳本將線條畫出來看一下(片段著色器):
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é)果如下圖:
