在片段着色器中绘制线段[英] Draw a line segment in a fragment shader

本文是小编为大家收集整理的关于在片段着色器中绘制线段的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在努力理解以下代码,其想法是在片段着色器中绘制一个简单的片段.我试图分解它,但我仍然没有得到???线. 有一个很好的解释真是太棒了.我在So或Google上找不到任何东西.

float lineSegment(vec2 p, vec2 a, vec2 b) {
    float thickness = 1.0/100.0;

    vec2 pa = p - a;
    vec2 ba = b - a;

    float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
    // ????????
    float idk = length(pa - ba*h);

    return smoothstep(0.0, thickness, idk);
}

原始代码来自 thebookofshaders.

推荐答案

假设该行是由点a,b和p定义的,那么pa是从点a到point 和ba向量从a到b.

现在,dot(ba, ba)等于dot(pa,ba) / length(ba),而dot(pa,ba) / length(ba)是向量PA在您的行上的投影.然后,dot(pa,ba)/dot(ba,ba)是在线路长度上归一化的投影.该值在0到1之间夹住,因此您的投影将始终在定义线条的点之间.

然后在length(pa - ba * h)上,ba * h等于dot(pa,ba) / length(ba),这是您的点上的投影,现在夹在点A和B之间.减法pa - ba * h导致一个矢量,该向量表示您的线和点p之间的最小距离.使用该矢量的长度并将其与厚度进行比较,您可以确定点是否落入要绘制的行内.

本文地址:https://www.itbaoku.cn/post/2091109.html

问题描述

I'm struggling to understand the following code, the idea is to draw a simple segment in a fragment shader. I tried to decompose it but I still don't get the ??? line. It would be awesome to have a nice explanation. I couldn't find anything on SO or Google.

float lineSegment(vec2 p, vec2 a, vec2 b) {
    float thickness = 1.0/100.0;

    vec2 pa = p - a;
    vec2 ba = b - a;

    float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
    // ????????
    float idk = length(pa - ba*h);

    return smoothstep(0.0, thickness, idk);
}

Original code comes from TheBookOfShaders.

推荐答案

Assuming the line is defined by the points a, b, and p is the point to evaluate, then pa is the vector that goes from point a to point p and ba the vector from a to b.

Now, dot(ba, ba) is equal to length(ba) ^ 2 and dot(pa,ba) / length(ba) is the projection of the vector pa over your line. Then, dot(pa,ba)/dot(ba,ba) is the projection normalized over the length of your line. That value is clamped between 0 and 1 so your projection will always be in between the point that define your line.

Then on length(pa - ba * h), ba * h is equal to dot(pa,ba) / length(ba) which was the projection of your point over your line, now clamped between points a and b. The subtraction pa - ba * h results in a vector that represents the minimum distance between your line and point p. Using the length of that vector and comparing it against the thickness you can determine whether the point falls inside the line you want to draw.