#include <GL/glut.h> #include <GL/glu.h> #include <conio.h> #include <stdlib.h> #include <GL/glaux.h> #include <fstream> #include <math.h>
int ww=600,hh=600; int mouseX,mouseY;
GLint viewport[4],winX,winY,viewportX,viewportY; GLdouble modelview[16]; GLdouble projection[16];
GLfloat viewportZ,winZ; GLdouble posX,posY,posZ;
void mouse(int button,int state,int x,int y) { if (state==GLUT_DOWN&&button==GLUT_LEFT_BUTTON) {
winX=winY=winZ=0.0; posX=posY=posZ=0.0; viewportZ=viewportY=viewportX=0.0; winX=x; winY=y;
viewportX=winX; viewportY=hh-y; glReadBuffer(GL_FRONT); glGetIntegerv(GL_VIEWPORT, viewport); glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection);
//获得屏幕坐标对应世界坐标的深度 glReadPixels(viewportX,viewportY, 1,1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
viewportZ=winZ; //获得相应世界坐标 gluUnProject(viewportX, viewportY, viewportZ, modelview, projection, viewport, &posX, &posY, &posZ);
}
}
void init() { //设置观察和投影方式 glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0,-400,400,0,0,0,0,1,0); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60, 1, 0, 1000);
}
void reshape(GLsizei w,GLsizei h) {
ww=w; hh=h; glViewport(0,0,w,h); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60., (double)w/(double)h, 1, 900.0); glMatrixMode(GL_MODELVIEW);
} void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0,1.0,0.0); glPolygonMode (GL_FRONT, GL_FILL); glPolygonMode (GL_BACK, GL_LINE); glBegin(GL_QUADS);
glVertex3f(-256.0f,-256.0f,0.0f); glVertex3f(256.0f,-256.0f,0.0f); glVertex3f(256.0f,256.0f,0.0f); glVertex3f(-256.0f,256.0f,0.0f); glEnd();
glutSwapBuffers(); } int main(int argc, char ** argv) { glutInit(& argc, argv); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glClearDepth(1.0f); glDepthFunc(GL_LEQUAL); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE);
glutInitWindowSize(600,600); glutInitWindowPosition(0,0); glutCreateWindow("三维场景"); init(); glutDisplayFunc(display);
glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(mousemove);
glutMainLoop(); }
|