# opengl gluLookAt函数实现

 gluLookAt(GLdouble eyex,GLdouble eyey,GLdouble eyez,GLdouble centerx,GLdouble centery,GLdouble centerz,GLdouble upx,GLdouble upy,GLdouble upz);

c++实现

#include <iostream>
#include <cstring>
#include <GL/glut.h>
#include <cmath>
using namespace std;

struct point
{
GLdouble x, y, z;
point()
{
x = y = z = 0;
}
point(GLdouble _x, GLdouble _y, GLdouble _z)
{
x = _x;
y = _y;
z = _z;
}
};
typedef point Vector;
void Normalize( Vector &V)
{
GLdouble tmp = sqrt(V.x*V.x + V.y*V.y + V.z*V.z);
V.x = V.x / tmp;
V.y = V.y / tmp;
V.z = V.z / tmp;
}
Vector Cross(Vector a, Vector b)
{
return Vector(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
}
void MyLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ)
{
GLdouble Mat[16];
memset(Mat, 0, sizeof(Mat));
Mat[15] = 1;
Vector forward(centerX - eyeX, centerY - eyeY, centerZ - eyeZ);
Vector up(upX, upY, upZ);
Normalize(forward);
Vector side = Cross(forward, up);
Normalize(side);
up = Cross(side, forward);
Mat[0] = side.x;
Mat[4] = side.y;
Mat[8] = side.z;
Mat[1] = up.x;
Mat[5] = up.y;
Mat[9] = up.z;
Mat[2] = -forward.x;
Mat[6] = -forward.y;
Mat[10] = -forward.z;
cout<<Mat[10]<<" ";
cout<<endl;
glTranslated(-eyeX, -eyeY, -eyeZ);
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0); //背景黑色
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0); //画笔白色

//  gluLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
MyLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glutWireTeapot(2);
glutSwapBuffers();
}

void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
//  gluLookAt(0, 0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
//
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}