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

查看:129
本文介绍了在片段着色器中绘制线段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

原始代码来自 TheBookOfShaders.

推荐答案

假定线由点abp定义,则点pa是向量从点a到点pba的向量从ab.

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.

现在,dot(ba, ba)等于length(ba) ^ 2,并且dot(pa,ba) / length(ba)是矢量pa在行上的投影.然后,dot(pa,ba)/dot(ba,ba)是在行的长度上标准化的投影.该值固定在0到1之间,因此您的投影将始终在定义直线的点之间.

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.

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

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.

这篇关于在片段着色器中绘制线段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆