03->OpenGL多边形,glut实现三角形条带和三角形扇

图形学中基本图元是多边形,一般要求是凸多边形,三角形是最简单的凸多边形,在图形渲染中比一般多边形其绘制速度快。今天学习OpenGL绘制三角形条带和三角形扇基础。编程环境!

 

1. 三角形条带

指定顶点序列,按顺序每三个顶点画一个三角形。主要是在画的时候指定参数GL_TRIANGLE_STRIP。(如顶点序列为{0,1,2,3,4,5,6,7},则0,1,2形成一个三角形,1,2,3形成一个三角形,以此类推)

#include <glut.h>
class Point2d { public: GLfloat x = 0.0f; GLfloat y = 0.0f; Point2d(const GLfloat &a, const GLfloat &b) : x(a), y(b) {} Point2d() {} };// GL_TRANGLE_STRIP 三角形条带 void triangles(void) { Point2d p[8]; p[0] = Point2d(-0.5f, -0.8f); p[1] = Point2d(-0.35f, 0.8f); p[2] = Point2d(-0.2f, -0.8f); p[3] = Point2d(0.0f, 0.8f); p[4] = Point2d(0.2f, -0.8f); p[5] = Point2d(0.35f, 0.8f); p[6] = Point2d(0.5f, -0.8f); p[7] = Point2d(0.75f, 0.8f); glColor3f(0.38f, 1.0f, 0.2f);
glPolygonMode(GL_FRONT, GL_LINE); glPolygonMode(GL_BACK, GL_LINE); glLineWidth(
2.0f); glBegin(GL_TRIANGLE_STRIP); for (int i = 0; i < 8; ++i) { glVertex2f(p[i].x, p[i].y); } glEnd(); glFlush(); }

int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(100, 100); glutInitWindowSize(600, 600); glutCreateWindow("三角形条带"); glutDisplayFunc(&triangles); glutMainLoop(); }

2. 三角形扇

指定顶点序列,第一个为顶点,后续按顺序每两个顶点与第一个顶点形成三角形,主要是在画的时候指定参数GL_TRIANGLE_FAN。(如顶点序列为{0,1,2,3,4,5,6,7},则0,1,2形成一个三角形,0,2,3形成一个三角形,0,3,4形成一个三角形,以此类推)

#include <glut.h>
class Point2d {
public:
    GLfloat x = 0.0f;
    GLfloat y = 0.0f;
    Point2d(const GLfloat &a, const GLfloat &b) : x(a), y(b) {}
    Point2d() {}
};

// 扇形
void fan(void) {
    Point2d p[8];
    p[0] = Point2d(-0.8f, 0.0f);
    p[1] = Point2d(0.0f, 0.8f);
    p[2] = Point2d(0.4f, 0.5f);
    p[3] = Point2d(0.7f, 0.2f);
    p[4] = Point2d(0.7f, -0.2f);
    p[5] = Point2d(0.4f, -0.5f);
    p[6] = Point2d(0.0f, -0.8f);

    glColor3f(0.38f, 1.0f, 0.2f);
    glPolygonMode(GL_FRONT, GL_LINE);
    glPolygonMode(GL_BACK, GL_LINE);
    glLineWidth(1.0f);
    glBegin(GL_TRIANGLE_FAN);
    for (int i = 0; i < 7; ++i) {
        glVertex2f(p[i].x, p[i].y);
    }
    glEnd();

    glFlush();
}

int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(600, 600);
    glutCreateWindow("三角形扇");
    glutDisplayFunc(&fan);
    glutMainLoop();
}

 

 

posted @ 2018-08-28 11:59  niokit  阅读(1441)  评论(0编辑  收藏  举报