考虑到我使用GL_LINES绘制线条,在片段着色器中是否可能添加线条粗细?我看到的大多数示例似乎只访问基元内部的纹素,在片段着色器中需要编写一个线条粗细着色器来获取厚度,并且该着色器需要向线条基元外部的纹素写入数据。如果可能,提供一个非常小而基本的示例会很好。
考虑到我使用GL_LINES绘制线条,在片段着色器中是否可能添加线条粗细?我看到的大多数示例似乎只访问基元内部的纹素,在片段着色器中需要编写一个线条粗细着色器来获取厚度,并且该着色器需要向线条基元外部的纹素写入数据。如果可能,提供一个非常小而基本的示例会很好。
片段着色器有很多可能性。只需看看一些人正在做什么。我自己离那个水平还很远,但这段代码可以给你一个想法:
#define resolution vec2(500.0, 500.0)
#define Thickness 0.003
float drawLine(vec2 p1, vec2 p2) {
vec2 uv = gl_FragCoord.xy / resolution.xy;
float a = abs(distance(p1, uv));
float b = abs(distance(p2, uv));
float c = abs(distance(p1, p2));
if ( a >= c || b >= c ) return 0.0;
float p = (a + b + c) * 0.5;
// median to (p1, p2) vector
float h = 2 / c * sqrt( p * ( p - a) * ( p - b) * ( p - c));
return mix(1.0, 0.0, smoothstep(0.5 * Thickness, 1.5 * Thickness, h));
}
void main()
{
gl_FragColor = vec4(
max(
max(
drawLine(vec2(0.1, 0.1), vec2(0.1, 0.9)),
drawLine(vec2(0.1, 0.9), vec2(0.7, 0.5))),
drawLine(vec2(0.1, 0.1), vec2(0.7, 0.5))));
}
另一种选择是使用texture2D
检查附近像素的颜色 - 这样您可以使图像发光或变厚(例如,如果任何调整像素为白色 - 使当前像素为白色,如果靠近附近像素的下一个像素为白色 - 使当前像素为灰色)。
GL_LINES
在片段着色器中不可能实现。这是因为GL限制您只能在提交给光栅化器的几何图形上绘制,因此您需要使用包含锯齿状原始线条和任何平滑顶点的几何图形。例如,您可以使用几何着色器将您的线扩展到理想线周围的四边形(或者实际上是两个三角形),这可以作为粗线。float distanceToLine(vec2 p1, vec2 p2, vec2 point) {
float a = p1.y-p2.y;
float b = p2.x-p1.x;
return abs(a*point.x+b*point.y+p1.x*p2.y-p2.x*p1.y) / sqrt(a*a+b*b);
}
#ifdef GL_ES
precision mediump float;
#endif
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
float line(vec2 uv, vec2 pt1, vec2 pt2,vec2 resolution)
{
float clrFactor = 0.0;
float tickness = 3.0 / max(resolution.x, resolution.y); //only used for tickness
float r = distance(uv, pt1) / distance(pt1, pt2);
if(r <= 1.0) // if desired Hypothetical circle in range of vector(pt2,pt1)
{
vec2 ptc = mix(pt1, pt2, r); // ptc = connection point of Hypothetical circle and line calculated with interpolation
float dist = distance(ptc, uv); // distance betwenn current pixel (uv) and ptc
if(dist < tickness / 2.0)
{
clrFactor = 1.0;
}
}
return clrFactor;
}
void main()
{
vec2 uv = gl_FragCoord.xy / resolution.xy; //current point
//uv = current pixel
// 0 < uv.x < 1 , 0 < uv.x < 1
// left-down= (0,0)
// right-top= (1,1)
vec2 pt1 = vec2(0.1, 0.1); //line point1
vec2 pt2 = vec2(0.8, 0.7); //line point2
float lineFactor = line(uv, pt1, pt2, resolution.xy);
vec3 color = vec3(.5, 0.7 , 1.0);
gl_FragColor = vec4(color * lineFactor , 1.);
}