我试图在片段着色器中绘制一条非常简单的曲线,其中有一个水平部分、一个过渡部分,然后是另一个水平部分。它看起来像下面这样:
我的方法:
我没有使用贝塞尔曲线(这会使厚度变得更复杂),而是尝试走捷径。基本上,我只是使用一个平滑的步骤在水平线段之间进行过渡,这给出了一条不错的曲线。为了计算曲线的厚度,对于任何给定的片段 x,我计算了 y 并最终计算了我们应该在直线上的位置 (x,y) 的坐标。不幸的是,这并没有计算到曲线的最短距离,如下所示。
下图可能有助于理解我遇到问题的功能。
// Start is a 2D point where the line will start
// End is a 2d point where the line will end
// transition_x is the "x" position where we're use a smoothstep to transition between points
float CurvedLine(vec2 start, vec2 end, float transition_x) {
// Setup variables for positioning the line
float curve_width_frac = bendWidth; // How wide should we make the S bend
float thickness = abs(end.x - start.x) * curve_width_frac; // normalize
float start_blend = transition_x - thickness;
float end_blend = transition_x + thickness;
// for the current fragment, if you draw a line straight up, what's the first point it hits?
float progress_along_line = smoothstep(start_blend, end_blend, frag_coord.x);
vec2 point_on_line_from_x = vec2(frag_coord.x, mix(start.y,end.y, progress_along_line)); // given an x, this is the Y
// Convert to application specific stuff since units are a little odd
vec2 nearest_coord = point_on_line_from_x * dimensions;
vec2 rad_as_coord = rad * dimensions;
// return pseudo distance function where 1 is inside and 0 is outside
return 1.0 - smoothstep(lineWidth * dimensions.y, lineWidth * 1.2 * dimensions.y, distance(nearest_coord, rad_as_coord));
// return mix(vec4(1.0), vec4(0.0), s));
}
所以我很熟悉给定一条线或线段,计算到该线的最短距离,但我不太确定如何用这个曲线段来解决它。任何建议将不胜感激。
最佳答案
我会分两次完成:
渲染细曲线
还不使用目标颜色,而是使用黑白/灰度......黑色背景白线使下一步更容易。
平滑原图和阈值
因此,只需使用任何 FIR 平滑或高斯模糊即可将颜色渗出至厚度距离的一半。在此之后,只需根据背景对结果进行阈值处理,然后重新着色为想要的颜色。平滑需要来自 #1 的渲染图像作为输入。您可以使用带有圆形掩码的简单卷积:
0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0
顺便说一句。像这样卷积后的颜色强度将是距中心距离的函数,因此如果需要,它可以用作纹理坐标或着色参数 ...
此外,您还可以使用 2 个嵌套的 for 循环代替卷积矩阵:
// convolution col=vec4(0.0,0.0,0.0,0.0); for (y=-r;y<=+r;y++) for (x=-r;x<=+r;x++) if ((x*x)+(y*y)<=r*r) col+=texture2D(sampler,vec2(x0+x*mx,y0+y*my)); // threshold & recolor if (col.r>threshold) col=col_curve; // assuming 1st pass has red channel used else col=col_background;
其中
x0,y0
是您的片段在纹理中的位置,mx,my
从像素缩放到纹理坐标比例。当x+x0
和y+y0
可能在您的纹理之外时,您还需要处理边缘情况。
注意曲线越厚,速度越慢......对于更高的厚度,应用更小的半径平滑几次(更多遍)更快
这里有一些相关的QA可以涵盖一些步骤:
- OpenGL Scale Single Pixel Line用于多 channel (旧 api)
- How to implement 2D raycasting light effect in GLSL扫描输入纹理
关于opengl - GLSL片段着色器——绘制简单的粗曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113080/