# 初试openGl — 三维图形

## 一个简单的三维图形

#include <GL/glut.h>
#include <windows.h>
#include <stdlib.h>
#include <math.h>
#define GLUT_DISABLE_ATEXIT_HACK

GLfloat AngleX;
GLfloat AngleY;
GLfloat sca[3] = {1,1,1};
GLfloat tra[3] = {0,0,0};

void display1(){                    //sphere，cone
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);

glPushMatrix();
{
glRotatef(AngleX, 1.0f, 0.0f, 0.0f);
glRotated(AngleY, 0.0f, 1.0f, 0.0f);
glScalef(sca[0], sca[1], sca[2]);
glTranslatef(tra[0], tra[1], tra[2]);

glBegin(GL_TRIANGLE_FAN);
glColor3f(0.0f, 0.0f, 0.0f);
glutWireSphere(18, 14, 14);
glutWireCone(30, 40, 30, 30);
glEnd();
}
glPopMatrix();

glutSwapBuffers();
}

void reshape(int w, int h){
GLfloat aspect = (GLfloat)w / (GLfloat)h;
GLfloat nRange = 100.0f;

glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);

if (w <= h){
glOrtho(-nRange, nRange, -nRange*aspect, nRange*aspect, -nRange, nRange);
}
else
glOrtho(-nRange, nRange, -nRange / aspect, nRange / aspect, -nRange, nRange);
}

void Skeyboard(GLint key, GLint x, GLint y){   //control Rotate
if (key == GLUT_KEY_UP)
AngleX -= 5.0f;
if (key == GLUT_KEY_DOWN)
AngleX += 5.0f;
if (key == GLUT_KEY_LEFT)
AngleY -= 5.0f;
if (key == GLUT_KEY_RIGHT)
AngleY += 5.0f;

if (AngleX > 355.0f)
AngleX = 0.0f;
if (AngleX < 0.0f)
AngleX = 355.0f;

glutPostRedisplay();
}

void Nkeyboard(unsigned char key, int x, int y){   //control scale and translate
if (key == 'j'){
for (int i = 0; i < 3; i++)
sca[i] += 0.1;
}
if (key == '-'){
for (int i = 0; i < 3; i++)
sca[i] -= 0.1;
}
if (key == 'w'){
tra[1]++;
}
if (key == 's'){
tra[1]--;
}
if (key == 'a'){
tra[0]--;
}
if (key == 'd'){
tra[0]++;
}
if (key = 'q'){
tra[2]++;
}
if (key = 'e'){
tra[2]--;
}

glutPostRedisplay();
}

void init(){
AngleX = 45.0f;
AngleY = 315.f;

glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

glEnable(GL_DEPTH_TEST);
glEnable(GL_DITHER);
}

int main(int argc, char *argv[]){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("三维图形");

glutReshapeFunc(reshape);
glutDisplayFunc(display1);
glutSpecialFunc(Skeyboard);
glutKeyboardFunc(Nkeyboard);

init();
glutMainLoop();
return 0;
}