隐藏线消除
使用深度缓存的2通道绘制的OpenGL实现:
1. 禁写颜色缓存
glColorMask(0, 0, 0, 0);
2. 启用深度测试
glEnable(GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
3. 以多边形填充模式绘制对象,要使用多边形偏移(Pass1)
glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
glPolygonOffset(1.1f, 4.0f);
glEnable (GL_POLYGON_OFFSET_FILL); //启用多边形偏移
drawScene ();
glDisable (GL_POLYGON_OFFSET_FILL);
4. 启用颜色缓存
glColorMask(1, 1, 1, 1);
5. 采用两种线绘制方式之一绘制对象中包含的线段(Pass2).
具体实现代码
int DrawGLScene(GLvoid) // 从这里开始进行所有的绘制
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清除屏幕及深度缓存
glLoadIdentity(); // 重置模型观察矩阵
glTranslatef(0.0f,0.0f,-5.0f); // 移入屏幕 5 个单位
static float xrot=0.0f,yrot=0.0f,zrot=0.0f;
glRotatef(xrot,1.0f,0.0f,0.0f); // 绕X轴旋转
glRotatef(yrot,0.0f,1.0f,0.0f); // 绕Y轴旋转
glRotatef(zrot,0.0f,0.0f,1.0f); // 绕Z轴旋转
glDisable(GL_TEXTURE_2D);
glColorMask(0,0,0,0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPolygonOffset(1.1f, 4.0f);
glEnable (GL_POLYGON_OFFSET_FILL); //启用多边形偏移
//auxSolidSphere(1.0);
auxSolidTeapot(1.0);
glDisable (GL_POLYGON_OFFSET_FILL);
glColorMask(1, 1, 1, 1);
glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
//auxSolidSphere(1.0);
auxSolidTeapot(1.0);
xrot+=1.3f; // X 轴旋转
yrot+=1.2f; // Y 轴旋转
zrot+=1.4f; // Z 轴旋转
return TRUE; // 一切 OK
}
效果图:
#include <GL/glut.h>
int gwin = 0;
static float xrot = 0.0f, yrot = 0.0f, zrot = 0.0f;
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清除屏幕及深度缓存
glLoadIdentity(); // 重置模型观察矩阵
glTranslatef(0.0f, 0.0f, -6.0f); // 移入屏幕 5 个单位
glRotatef(xrot, 1.0f, 0.0f, 0.0f); // 绕X轴旋转
glRotatef(yrot, 0.0f, 1.0f, 0.0f); // 绕Y轴旋转
glRotatef(zrot, 0.0f, 0.0f, 1.0f); // 绕Z轴旋转
glDisable(GL_TEXTURE_2D);
glColorMask(0, 0, 0, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPolygonOffset(1.1f, 4.0f);
glEnable (GL_POLYGON_OFFSET_FILL); //启用多边形偏移
glutSolidTeapot(1.0f);
glDisable (GL_POLYGON_OFFSET_FILL);
glColorMask(1, 1, 1, 1);
glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
glutSolidTeapot(1.0f);
xrot += 1.3f; // X 轴旋转
yrot += 1.2f; // Y 轴旋转
zrot += 1.4f; // Z 轴旋转
glutSwapBuffers();
glutPostRedisplay();
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.f, (GLfloat)w / h, 0.1f, 100.f);
glMatrixMode(GL_MODELVIEW);
}
void init()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(640, 480);
gwin = glutCreateWindow("glPolygonOffset");
init();
glutReshapeFunc(resize);
glutDisplayFunc(render);
// glutIdleFunc(render);
glutMainLoop();
return 0;
}