OpenGL(三)图形变换之裁剪变化
通过裁剪平面程序例子学习裁剪相关知识
#include
#include
#include
static GLfloat xRot =0.0f;
static GLfloat yRot = 0.0f;
void SetupRC(void)
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glShadeModel(GL_FLAT); //明暗模式 以最后的所填颜色填充
}
void ChangeSize(int w, int h)
{
if (h == 0)
h = 1;
//设置视区尺寸
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//设置修剪空间
GLfloat fAspect = (float)w / (float)h;
gluPerspective(60, fAspect, 1.0, 20.0f);
glMatrixMode(GL_MODELVIEW);
}
//在窗口中绘制图形
void RenderScene(void)
{
//定义裁剪平面方程系数,这里平面方程为x=0;
GLdouble equ[4] = { 1.0, 0.0, 0.0 ,0.0};
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f,0.0f,0.0f); //红色
glPushMatrix();
//沿x轴负向平移一段距离,保证良好的观察效果
glTranslatef(0.0,0.0,-5.0);
//设置裁剪平面
glClipPlane(GL_CLIP_PLANE0,equ);
glEnable(GL_CLIP_PLANE0);
//使球体旋转
glRotatef(xRot,1.0f,0.0f,0.0f);
glRotated(yRot,0.0f,1.0f,0.0f);
//绘制一个球体
glutWireSphere(2.0f,20,20);
glPopMatrix();
glFlush();
}
void SpecialKeys(int key,int x,int y)
{
if (key == GLUT_KEY_UP) xRot -= 5.0f;
if (key == GLUT_KEY_DOWN) xRot += 5.0f;
if (key == GLUT_KEY_LEFT) yRot -= 5.0f;
if (key == GLUT_KEY_RIGHT) yRot += 5.0f;
if (xRot > 356.0f) xRot = 0.0f;
if (xRot < -1.0) xRot = 355.0f;
if (yRot>356.0f) yRot = 0.0f;
if (yRot < -1.0f) yRot = 355.0f;
}
int main(int argc, char *argv[])
{
//glutInit is used to initialize the GLUT library
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("GLClipPlane");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
SetupRC();
glutMainLoop();
return 0;
}
程序运行结果:
学习点:
2.
- void glClipPlane(GLenum plane, const GLdouble *equation);
定义一个裁剪平面。equation参数指向平面方程Ax + By + Cz + D = 0的4个系数。equation=(0,-1,0,0),前三个参数(0,-1,0)可以理解为法线向下,只有向下的,即Y<0的才能显示,最后一个参数0表示从z=0平面开始。这样就是裁剪掉上半平面。
相应的equation=(0,1,0,0)表示裁剪掉下半平面,
equation=(1,0,0,0)表示裁剪掉左半平面,
equation=(-1,0,0,0)表示裁剪掉右半平面,
equation=(0,0,-1,0)表示裁剪掉前半平面,
equation=(0,0,1,0)表示裁剪掉后半平面