在openGL中绘制可变宽度线(无glLineWidth)

Dec*_*ira 9 opengl

在不使用glLineWidth的情况下绘制可变宽度线的最佳方法是什么?只画一个矩形?各种平行线?以上都不是?

Ozg*_*tak 14

您可以绘制两个三角形:

// Draws a line between (x1,y1) - (x2,y2) with a start thickness of t1 and
// end thickness t2.
void DrawLine(float x1, float y1, float x2, float y2, float t1, float t2)
{
    float angle = atan2(y2 - y1, x2 - x1);
    float t2sina1 = t1 / 2 * sin(angle);
    float t2cosa1 = t1 / 2 * cos(angle);
    float t2sina2 = t2 / 2 * sin(angle);
    float t2cosa2 = t2 / 2 * cos(angle);

    glBegin(GL_TRIANGLES);
    glVertex2f(x1 + t2sina1, y1 - t2cosa1);
    glVertex2f(x2 + t2sina2, y2 - t2cosa2);
    glVertex2f(x2 - t2sina2, y2 + t2cosa2);
    glVertex2f(x2 - t2sina2, y2 + t2cosa2);
    glVertex2f(x1 - t2sina1, y1 + t2cosa1);
    glVertex2f(x1 + t2sina1, y1 - t2cosa1);
    glEnd();
}
Run Code Online (Sandbox Code Playgroud)

  • 这太复杂了!太多的三角学也不需要它. (3认同)

bob*_*obo 9

好的,这个怎么样:(Ozgar)


       A
      / \
     /      \
    . p1        \
   /                \
  /                    D
 B -                 .p2
      -   -    -    C

所以AB width1和CD是width2.

然后,

// find line between p1 and p2
Vector p1p2 = p2 - p1 ;

// find a perpendicular
Vector perp = p1p2.perpendicular().normalize()

// Walk from p1 to A
Vector A = p1 + perp*(width1/2)
Vector B = p1 - perp*(width1/2)

Vector C = p2 - perp*(width2/2)
Vector D = p2 - perp*(width2/2)

// wind triangles
Triangle( A, B, D )
Triangle( B, D, C )
Run Code Online (Sandbox Code Playgroud)

注意这个算法可能存在CW/CCW绕组问题 - 如果perp在上图中计算为(-y,x)那么它将是CCW绕组,如果(y,-x)那么它将是CW绕组.


bas*_*ero 1

假设你的原始点是 (x1,y1) -> (x2,y2)。使用以下点 (x1-width/2, y1)、(x1+width/2,y1)、(x2-width/2, y2)、(x2+width/2,y2) 构造一个矩形,然后使用四边形/三边形来绘制它。这是简单天真的方法。请注意,对于大线宽,您会得到奇怪的端点行为。那么你真正想做的是使用向量数学进行一些智能平行线计算(这应该不会那么糟糕)。由于某种原因,我想到了点/叉积和矢量投影。