图形学中基本图元是多边形,一般要求是凸多边形,三角形是最简单的凸多边形,在图形渲染中比一般多边形其绘制速度快。今天学习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[];
p[] = Point2d(-0.5f, -0.8f);
p[] = Point2d(-0.35f, 0.8f);
p[] = Point2d(-0.2f, -0.8f);
p[] = Point2d(0.0f, 0.8f);
p[] = Point2d(0.2f, -0.8f);
p[] = Point2d(0.35f, 0.8f);
p[] = Point2d(0.5f, -0.8f);
p[] = 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 = ; i < ; ++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(, );
glutInitWindowSize(, );
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[];
p[] = Point2d(-0.8f, 0.0f);
p[] = Point2d(0.0f, 0.8f);
p[] = Point2d(0.4f, 0.5f);
p[] = Point2d(0.7f, 0.2f);
p[] = Point2d(0.7f, -0.2f);
p[] = Point2d(0.4f, -0.5f);
p[] = 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 = ; i < ; ++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(, );
glutInitWindowSize(, );
glutCreateWindow("三角形扇");
glutDisplayFunc(&fan);
glutMainLoop();
}