重绘时如何避免重新启动多边形?

How to avoid restarting the polygon when redraw?

我正在编写一个连续绘制多边形的程序,直到用户单击鼠标右键,但是当我继续在屏幕上绘制其他东西时,多边形消失了,我该如何避免这种情况?这是我的程序:

float mouseX, mouseY;
vector<float> vecX(40);
vector<float> vecY(40);
int numPoints = 0;
int closed = 0;

void mouse(int button, int state, int x, int y)
{
    mouseX = x;
    mouseY = y;

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        if (closed || numPoints > 40)
             numPoints = 0;
        closed = 0;
        vecX[numPoints] = mouseX;
        vecY[numPoints] = mouseY;
        numPoints++;
    }
    if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
        closed = 1;
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);

    if (numPoints)
    {
        glBegin(GL_LINE_STRIP);
        for (int i = 0; i < numPoints; ++i)
            glVertex2f(vecX[i], vecY[i]);
        if (closed)
            glVertex2f(vecX[0], vecY[0]);
        else
            glVertex2f(mouseX, mouseY);
        glEnd();
    }
    glFlush();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(600, 400);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Testing");
    gluOrtho2D(0, 600, 400, 0);

    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMainLoop();
}

vecXvecY用于存储鼠标点击的坐标

折线完成后,您需要将其存储到容器中。使用 std::vector 多段线。折线的类型是 std::vector<float>。开始时,容器中只有 1 条空多段线:

std::vector<std::vector<float>> polylines(1);

左键单击时,新的顶点坐标将添加到容器中的最后一条折线。当您右键单击时,一条新的多段线将添加到容器中:

void mouse(int button, int state, int x, int y)
{
    mouseX = x;
    mouseY = y;

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        polylines.back().push_back(mouseX);
        polylines.back().push_back(mouseY);
    }
    if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
    {
        polylines.push_back(std::vector<float>());
    }
}

在嵌套循环中绘制折线:

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);

    for (auto i=0; i < polylines.size(); ++ i)
    {
        bool is_last = i == polylines.size() - 1;
        const auto& polyline = polylines[i];
        glBegin(is_last ? GL_LINE_STRIP : GL_LINE_LOOP);
        for (auto j = 0; j < polyline.size(); j += 2)
            glVertex2f(polyline[j], polyline[j+1]);
        if (is_last)
            glVertex2f(mouseX, mouseY);
        glEnd();
    }

    glutSwapBuffers();
}