图解opengl 3D 图形绘制实例

VC6 下载
http://blog.csdn.net/bcbobo21cn/article/details/44200205

opengl环境配置
http://blog.csdn.net/bcbobo21cn/article/details/51044614#t4

以下的demo工程

http://pan.baidu.com/s/1pLgmScj

一 3D旋转物体

码码:

//在窗口和全屏模式下切换,按ESC退出。

#include <Windows.h> //Windows的头文件
#include <gl/glut.h> //包含OpenGL实用库

HGLRC hRC=NULL; //窗口着色描述表句柄
HDC hDC=NULL;//OpenGL渲染描述表句柄
HWND hWnd=NULL; //保存窗口句柄
HINSTANCE hInstance; //保存程序实例

bool keys[256];//保存键盘按键的数组
bool active=TRUE;//窗口的活动标志,缺省为TRUE
bool fullscreen=TRUE; //全屏标志缺省,缺省设定成全屏模式

GLfloat rtri;//用于三角形的角度
GLfloat rquad;//用于四边形的角度

LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);//WndProc的定义

//重置OpenGL窗口大小
GLvoid ResizeGLScene(GLsizei width,GLsizei height)
{
if (height == 0) //防止被零除
{
height =1;//将height设为1
}

glViewport(0,0,width,height);//重置当前的视口
glMatrixMode(GL_PROJECTION);//旋转投影矩阵
glLoadIdentity();//重置投影矩阵

//设置视口的大小
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

glMatrixMode(GL_MODELVIEW);//选择模型观察矩阵
glLoadIdentity();//重置模型观察矩阵
}

int InitGL(GLvoid)//对OpenGL进行设置
{
glShadeModel(GL_SMOOTH);//启用阴影平滑
glClearColor(0.0f,0.0f,0.0f,0.0f);//黑色背景
glClearDepth(1.0f);//设置深度缓存
glEnable(GL_DEPTH_TEST);//启用深度测试
glDepthFunc(GL_LEQUAL);//所作深度测试的类型
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);//告诉系统对透视进行修正

return TRUE;
}

//进行绘制
int DrawGLScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//清除屏幕和深度缓存
glLoadIdentity();//重置当前的模型观察矩阵
glTranslatef(-1.5f,0.0f,-6.0f);//左移1.5单位,并移入屏幕6.0

glRotatef(rtri,0.0f,1.0f,0.0f);//绕Y轴旋转金字塔
glBegin(GL_TRIANGLES); //绘制金字塔各面

glColor3f(1.0f,0.0f,0.0f);//设置当前色为红色
glVertex3f(0.0f,1.0f,0.0f);//上顶点(前侧面)
glColor3f(0.0f,1.0f,0.0f);//设置当前色为绿色
glVertex3f(-1.0f,-1.0f,1.0f);//左下(前侧面)
glColor3f(0.0f,0.0f,1.0f);//设置当前色为蓝色
glVertex3f(1.0f,-1.0f,1.0f);//右下(前侧面)

glColor3f(1.0f,0.0f,0.0f);//设置当前色为红色
glVertex3f(0.0f,1.0f,0.0f);//上顶点(右侧面)
glColor3f(0.0f,1.0f,0.0f);//设置当前色为绿色
glVertex3f(1.0f,-1.0f,1.0f);//左下(右侧面)
glColor3f(0.0f,0.0f,1.0f);//设置当前色为蓝色
glVertex3f(1.0f,-1.0f,-1.0f);//右下(右侧面)

glColor3f(1.0f,0.0f,0.0f);//设置当前色为红色
glVertex3f(0.0f,1.0f,0.0f);//上顶点(后侧面)
glColor3f(0.0f,1.0f,0.0f);//设置当前色为绿色
glVertex3f(1.0f,-1.0f,-1.0f);//左下(后侧面)
glColor3f(0.0f,0.0f,1.0f);//设置当前色为蓝色
glVertex3f(-1.0f,-1.0f,-1.0f);//右下(后侧面)

glColor3f(1.0f,0.0f,0.0f);//设置当前色为红色
glVertex3f(0.0f,1.0f,0.0f);//上顶点(左侧面)
glColor3f(0.0f,1.0f,0.0f);//设置当前色为绿色
glVertex3f(-1.0f,-1.0f,-1.0f);//左下(左侧面)
glColor3f(0.0f,0.0f,1.0f);//设置当前色为蓝色
glVertex3f(-1.0f,-1.0f,1.0f);//右下(左侧面)

glEnd();//三角形绘制结束

glLoadIdentity();//重置模型观察矩阵
glTranslatef(1.5f,0.0f,-7.0f);//先右移再移入屏幕
glRotatef(rquad,1.0f,1.0f,1.0f);//绕XYZ轴旋转立方体

glBegin(GL_QUADS); //绘制正方形
glColor3f(0.0f,1.0f,0.0f);//将当前色设置为绿色
//顶面
glVertex3f(1.0f,1.0f,-1.0f);//右上
glVertex3f(-1.0f,1.0f,-1.0f);//左上
glVertex3f(-1.0f,1.0f,1.0f);//左下
glVertex3f(1.0f,1.0f,1.0f);//右下

//橙色
glColor3f(1.0f,0.5f,0.0f);
    //底面
glVertex3f(1.0f,-1.0f,-1.0f);//右上
glVertex3f(-1.0f,-1.0f,-1.0f);//左上
glVertex3f(-1.0f,-1.0f,1.0f);//左下
glVertex3f(1.0f,-1.0f,1.0f);//右下

//红色
glColor3f(1.0f,0.0f,0.0f);
//前面
glVertex3f(1.0f,1.0f,1.0f);//右上
glVertex3f(-1.0f,1.0f,1.0f);//左上
glVertex3f(-1.0f,-1.0f,1.0f);//左下
glVertex3f(1.0f,-1.0f,1.0f);//右下

//黄色
glColor3f(1.0f,1.0f,0.0f);
//后面
glVertex3f(1.0f,1.0f,-1.0f);//右上
glVertex3f(-1.0f,1.0f,-1.0f);//左上
glVertex3f(-1.0f,-1.0f,-1.0f);//左下
glVertex3f(1.0f,-1.0f,-1.0f);//右下

//蓝色
glColor3f(0.0f,0.0f,1.0f);
//左面
glVertex3f(-1.0f,1.0f,1.0f);//右上
glVertex3f(-1.0f,1.0f,-1.0f);//左上
glVertex3f(-1.0f,-1.0f,-1.0f);//左下
glVertex3f(-1.0f,-1.0f,1.0f);//右下

//紫罗兰色
glColor3f(1.0f,0.0f,1.0f);
//右面
glVertex3f(1.0f,1.0f,1.0f);//右上
glVertex3f(1.0f,1.0f,-1.0f);//左上
glVertex3f(1.0f,-1.0f,-1.0f);//左下
glVertex3f(1.0f,-1.0f,1.0f);//右下

glEnd();

//<控制旋转速度>
rtri +=0.02f;   //增加三角形的旋转变量
rquad -=0.015f; //减少四边形的旋转变量

return TRUE;
}

GLvoid KillGLWindow(GLvoid)//正常销毁窗口
{
if(fullscreen)//是否处于全屏模式
{
ChangeDisplaySettings(NULL,0); //是的话,切换回桌面
ShowCursor(TRUE);//显示鼠标指针
}

if(hRC)//是否拥有OpenGL渲染描述表
{
if(!wglMakeCurrent(NULL,NULL)) //能否是否DC和RC描述表
{
MessageBox(NULL,"释放DC或RC失败。","关闭错误",MB_OK | MB_ICONINFORMATION );
}

if(!wglDeleteContext(hRC)) //能否删除RC
{
MessageBox(NULL,"释放RC失败。","关闭错误",MB_OK | MB_ICONINFORMATION );
}

hRC = NULL;
}

if(hDC && !ReleaseDC(hWnd,hDC)) //能否释放DC
{
MessageBox(NULL,"释放DC失败。","关闭错误",MB_OK | MB_ICONINFORMATION );
hDC = NULL;
}

if(hWnd && !DestroyWindow(hWnd)) //能否销毁窗口
{
MessageBox(NULL,"释放窗口句柄失败。","关闭错误",MB_OK | MB_ICONINFORMATION );
hWnd = NULL;
}

if(!UnregisterClass("OpenGL",hInstance)) //能否注销窗口类
{
MessageBox(NULL,"不能注销窗口类。","关闭错误",MB_OK | MB_ICONINFORMATION );
hInstance = NULL;
}
}

BOOL CreateGLWindow(char * title,int width,int height,int bits,bool fullscreenflag)
{
GLuint PixelFormat;//保存查找匹配的结果
WNDCLASS wc;//窗口类结构
DWORD dwExStyle; //扩展窗口风格
DWORD dwStyle;//窗口风格
RECT WindowRect;//取得矩形的左上角和右下角的坐标值
WindowRect.left=(long)0;//将Left设为0
WindowRect.right=(long)width;//将Right设为要求的宽度
WindowRect.top=(long)0;
WindowRect.bottom=(long)height;

fullscreen = fullscreenflag;//设置全局全屏标志

hInstance         = GetModuleHandle(NULL);//取得窗口的实例
wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;//移动时重画,并为窗口取得DC
wc.lpfnWndProc    = WndProc;//WndProc处理消息
wc.cbClsExtra     = 0;//无额外窗口数据Specifies the number of extra bytes to allocate following the window-class structure. 
wc.cbWndExtra     = 0; //无额外窗口数据Specifies the number of extra bytes to allocate following the window instance.
wc.hInstance      = hInstance;//设置实例
wc.hIcon          = LoadIcon(NULL,IDI_WINLOGO);//装入缺省图标
wc.hCursor        = LoadCursor(NULL,IDC_ARROW);//装入鼠标指针
wc.hbrBackground  = NULL;         //GL不需要背景
wc.lpszMenuName   = NULL ;         //不需要菜单
wc.lpszClassName  = "OpenGL";     //设定类名字

if(!RegisterClass(&wc)) //尝试注册窗口类
{
MessageBox(NULL,"注册窗口失败","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

if(fullscreen)
{
DEVMODE dmScreenSettings; //设备模式
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));//确保内存清空为零
dmScreenSettings.dmSize=sizeof(dmScreenSettings);//Devmode结构的大小
dmScreenSettings.dmPelsWidth = width;//所选屏幕宽度
dmScreenSettings.dmPelsHeight = height;//所选屏幕高度
dmScreenSettings.dmBitsPerPel = bits; //每像素所选的色彩浓度
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

//尝试设置显示模式并返回结果。注:CDS_FULLSCREEN移去了状态条。
if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
//若模式失败,提供两个选项:退出或在窗口内运行。
if(MessageBox(NULL,"全屏模式在当前显卡上设置失败!\n使用窗口模式?",
"提示",MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE;//选择窗口模式
}
else
{
//弹出一个对话框,告诉用户程序结束
MessageBox(NULL,"程序将被关闭","错误",MB_OK | MB_ICONSTOP);
return FALSE;
}
}
}

if(fullscreen)
{
dwExStyle = WS_EX_APPWINDOW; //扩展窗体风格
dwStyle = WS_POPUP; //窗体风格
ShowCursor(FALSE); //隐藏鼠标指针
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;//扩展窗体风格
dwStyle = WS_OVERLAPPEDWINDOW; //窗体风格
}

AdjustWindowRectEx(&WindowRect,dwStyle,FALSE,dwExStyle);//调整窗口达到真正要求的大小

//窗体自适应各种分辨率以居中方式显示
LONG nX, nY;

nX = (::GetSystemMetrics(SM_CXSCREEN) - width) / 2;
nY = (::GetSystemMetrics(SM_CYSCREEN) - height) / 2;

if(!(hWnd = CreateWindowEx(dwExStyle, //扩展窗体风格
"OpenGL", //类名字
title,    //窗口标题
WS_CLIPSIBLINGS | WS_CLIPCHILDREN| //必须的窗体风格属性
dwStyle,   //选择的窗体属性
nX,nY,   //窗口位置
WindowRect.right - WindowRect.left, //计算调整好的窗口宽度
WindowRect.bottom - WindowRect.top, //计算调整好的窗体高度
NULL, //无父窗口
NULL, //无菜单
hInstance, //实例
NULL))) //不向WM_CREATE传递任何东西
{
KillGLWindow();//重置显示区
MessageBox(NULL,"不能创建一个窗口设备描述表","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

static PIXELFORMATDESCRIPTOR pfd = //pdf告诉窗口希望的东西,即窗口使用的像素格式
{
sizeof(PIXELFORMATDESCRIPTOR), //上述格式描述符的大小
1,       //版本号
PFD_DRAW_TO_WINDOW |  //格式支持窗口
PFD_SUPPORT_OPENGL |  //格式支持OpenGL
PFD_DOUBLEBUFFER,  //支持双缓冲
PFD_TYPE_RGBA,     //申请RGBA格式
bits,              //选定色彩深度
0,0,0,0,0,0,       //忽略的色彩位
0,                 //无Alpha缓存
0,                 //忽略Shift Bit
0,                 //无累加缓存
0,0,0,0,           //忽略聚集位
16,                //16位Z-缓存(深度缓存)
0,                 //无蒙板缓存
0,                 //无辅助缓存
PFD_MAIN_PLANE,    //主绘图层
0,                 //Reserved
0,0,0              //忽略层遮罩
};

if(!(hDC = GetDC(hWnd))) //是否取得设备描述表
{
KillGLWindow();//重置显示区
MessageBox(NULL,"不能创建一种相匹配的像素格式","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

if(!(PixelFormat = ChoosePixelFormat(hDC,&pfd))) //Windows是否找到相应的像素格式
{
KillGLWindow();//重置显示区
MessageBox(NULL,"不能设置像素格式","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

if(!SetPixelFormat(hDC,PixelFormat,&pfd)) //是否能够设置像素格式
{
KillGLWindow();//重置显示区
MessageBox(NULL,"不能设置像素格式","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

if (!(hRC = wglCreateContext(hDC))) //能否取得着色描述表
{
KillGLWindow();//重置显示区
MessageBox(NULL,"不能创建OpenGL渲染描述表","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

if(!wglMakeCurrent(hDC,hRC)) //尝试激活着色描述表
{
KillGLWindow();
MessageBox(NULL,"不能激活当前的OpenGL渲染描述表","错误",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

ShowWindow(hWnd,SW_SHOW);//显示窗口
SetForegroundWindow(hWnd);//提供优先级别
SetFocus(hWnd);//设置键盘的焦点至此窗口
ResizeGLScene(width,height);//设置透视GL屏幕

if (!InitGL()) //初始化新建的GL窗口
{
KillGLWindow();
MessageBox(NULL,"Initialization","ERROR",MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

return TRUE;
}

//处理所有的窗口消息
LRESULT CALLBACK WndProc(HWND hWnd,//窗口的句柄
UINT uMsg,//窗口的消息
WPARAM wParam,//附加的消息内容
LPARAM lParam) //附加的消息内容
{
switch(uMsg) //检查检查Windows消息
{
case WM_ACTIVATE:  //监视窗口激活消息
{
if(!HIWORD(wParam)) //检查最小化状态
{
active = TRUE; //程序处于激活状态
}
else
{
active = FALSE;//程序不再激活
}

return 0;//返回消息循环
}

case WM_SYSCOMMAND: //系统中断命令
{
switch(wParam) //检查系统调用
{
case  SC_SCREENSAVE: //屏保运行
case SC_MONITORPOWER: //显示器进入节电模式
return 0; //阻止发生
}
break; //退出
}
case WM_CLOSE: //收到Close消息
{
PostQuitMessage(0);//发出退出消息
return 0;
}
case WM_KEYDOWN: //有键按下
{
keys[wParam] = TRUE;
return 0;
}
case WM_KEYUP: //有键放开
{
keys[wParam] = FALSE;
return 0;
}
case WM_SIZE: //调整OpenGL窗口大小
{
ResizeGLScene(LOWORD(lParam),HIWORD(lParam));//LOWORD=width,HIWORD=height
return 0;
}
}

//向DefWindowProc传递所有未处理的消息
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

//Windows程序的入口,调用窗口创建例程,处理窗口消息,并监视人机交互。
int WINAPI WinMain(HINSTANCE hInstance,//当前窗口实例
  HINSTANCE hPrevInstance, //前一个窗口实例
  LPSTR lpCmdLine, //命令行参数
  int nCmdShow) //窗口显示状态
{
MSG msg;//Windows消息结构
BOOL done=FALSE;//用来退出循环的BOOL变量
//提示用户选择运行模式
if (MessageBox(NULL,"你想在全屏模式下运行么?","设置全屏模式",MB_YESNO | MB_ICONQUESTION) == IDNO)
{
fullscreen = FALSE; //设置为窗口模式
}

//创建OpenGL窗口
if(!CreateGLWindow("OpenGL 3D 旋转物体",640,480,16,fullscreen))
{
return 0;       //失败退出
}

while(!done)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) //是否有消息在等待
{
if(msg.message == WM_QUIT) //收到退出消息
{
done = TRUE;
}
else //处理窗口消息
{
TranslateMessage(&msg);  //翻译消息
DispatchMessage(&msg);   //发送消息
}
}
else //如果没有消息
{
//绘制场景。监视ESC键和来自DrawGLScene()的退出消息
if(active)
{
if(keys[VK_ESCAPE])
{
done = TRUE;
}
else //没有退出,刷新屏幕
{
DrawGLScene();//绘制场景
SwapBuffers(hDC);//交换缓存(双缓存)
}
}
if(keys[VK_F1])
{
keys[VK_F1]=FALSE;
KillGLWindow();
fullscreen = !fullscreen;//切换全屏/窗口模式
//重建OpenGL窗口
if(!CreateGLWindow("3D旋转实例",640,480,16,fullscreen))
{
return 0;
}
}
}
}

//关闭程序
KillGLWindow(); //销毁窗口
return (msg.wParam); //退出程序
}


效果:


代码比较长;用notepad++折叠起来看下函数;



二 3D机器人

代码:
#include <gl/glut.h>
#include <stdlib.h>
#include <stdio.h>

#define SOLID 1
#define WIRE 2

int moveX,moveY;
int spinX = 0;
int spinY = 0;
int des = 0;

void init() {
   //定义光源的颜色和位置
   GLfloat ambient[] = { 0.5, 0.8, 0.1, 0.1 };  
   GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };  
   GLfloat position[] = { -80.0, 50.0, 25.0, 1.0 };  
   //选择光照模型
   GLfloat lmodel_ambient[] = { 0.4, 0.4, 0.4, 1.0 };  
   GLfloat local_view[] = { 0.0 };  
   glClearColor(0.0, 0.0, 0.0, 0.0);   
   glShadeModel(GL_SMOOTH);  
   //设置环境光
   glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);  
   //设置漫射光
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);  
   //设置光源位置
   glLightfv(GL_LIGHT0, GL_POSITION, position);  
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);  
   glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);  
   //启动光照
   glEnable(GL_LIGHTING);  
   //启用光源
   glEnable(GL_LIGHT0);  
}

//画球
void drawBall(double R, double x, double y,double z, int MODE) {
	glPushMatrix();
	glTranslated(x,y,z);
	if (MODE == SOLID) {
		glutSolidSphere(R,20,20);
	} else if (MODE ==WIRE) {
		glutWireSphere(R,20,20);
	}
	glPopMatrix();
}

//画半球
void drawHalfBall(double R, double x, double y,double z, int MODE) {
	glPushMatrix();
	glTranslated(x,y,z);
	GLdouble eqn[4]={0.0, 1.0, 0.0, 0.0};
	glClipPlane(GL_CLIP_PLANE0,eqn);
	glEnable(GL_CLIP_PLANE0);
	if (MODE == SOLID) {
		glutSolidSphere(R,20,20);
	} else if (MODE ==WIRE) {
		glutWireSphere(R,20,20);
	}
	glDisable(GL_CLIP_PLANE0);
	glPopMatrix();
}

//画长方体
void drawSkewed(double l, double w, double h, double x, double y, double z, int MODE) {
	glPushMatrix();
	glScaled(l, w, h);
	glTranslated(x, y, z);
	if (MODE == SOLID) {
		glutSolidCube(1);
	} else if (MODE ==WIRE) {
		glutWireCube(1);
	}
	glPopMatrix();
}

void display(void) {
	//清除缓冲区颜色
	glClear(GL_COLOR_BUFFER_BIT);
	//定义白色
	glColor3f(1.0, 1.0, 1.0); 
	//圆点放坐标中心
	glLoadIdentity();  
	//从哪个地方看
	gluLookAt(-2.0, -1.0, 20.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); 
	glPushMatrix();
	glRotated(spinX, 0, 1, 0);
	glRotated(spinY, 1, 0, 0);
	glTranslated(0, 0, des);
	//头
	drawBall(2, 0, 1, 0, SOLID);
	//身体
	drawSkewed(5, 4.4, 4, 0, -0.75, 0, SOLID);
	//肩膀
	drawHalfBall(1, 3.5, -2.1, 0, SOLID);
	drawHalfBall(1, -3.5, -2.1, 0, SOLID);
	//胳膊
	drawSkewed(1, 3, 1, 3.5, -1.3, 0, SOLID);
	drawSkewed(1, 3, 1, -3.5, -1.3, 0, SOLID);
	//手
	drawBall(1, 3.5, -6.4, 0, SOLID);
	drawBall(1, -3.5, -6.4, 0, SOLID);
	//腿
	drawSkewed(1.2, 3, 2, 1, -2.4, 0, SOLID);
	drawSkewed(1.2, 3, 2, -1, -2.4, 0, SOLID);
	//脚
	drawSkewed(1.5, 1, 3, 0.9, -9.2, 0, SOLID);
	drawSkewed(1.5, 1, 3, -0.9, -9.2, 0, SOLID);
	glPopMatrix();
    glutSwapBuffers();
}
//鼠标点击事件
void mouseClick(int btn, int state, int x, int y) {
    moveX = x;
	moveY = y;
	GLfloat ambient[] = { (float)rand() / RAND_MAX, (float)rand() / RAND_MAX, (float)rand() / RAND_MAX, 0.1 };  
	 //设置环境光
	glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);  
	//启用光源
	glEnable(GL_LIGHT0);  
}

//键盘事件
void keyPressed(unsigned char key, int x, int y) {
    switch (key) {
    case 'a':
        spinX -= 2;
        break;
    case 'd':
         spinX += 2;  
        break;
    case 'w':
        des += 2;
        break;
    case 's':
        des -= 2;
		break;
	}
	glutPostRedisplay();
}
// 鼠标移动事件 
void mouseMove(int x, int y) {
	int dx = x - moveX;
	int dy = y - moveY;
	printf("dx;%dx,dy:%dy\n",dx,dy);
	spinX += dx;
	spinY += dy;
	glutPostRedisplay();
	moveX = x;
	moveY = y;
}

void reshape(int w, int h) {
	//定义视口大小
	glViewport(0, 0, (GLsizei) w, (GLsizei) h); 
	//投影显示
	glMatrixMode(GL_PROJECTION);
	//坐标原点在屏幕中心
	glLoadIdentity();
	//操作模型视景
	gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
	glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
	//初始化
	glutInit(&argc, argv);
	//设置显示模式
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	//初始化窗口大小
	glutInitWindowSize(500, 500); 
	//定义左上角窗口位置
	glutInitWindowPosition(100, 100);
	//创建窗口
	glutCreateWindow(argv[0]);
	//初始化
	init();
	//显示函数
	glutDisplayFunc(display);
	//窗口大小改变时的响应
	glutReshapeFunc(reshape);
	//鼠标点击事件,鼠标点击或者松开时调用
    glutMouseFunc(mouseClick);
	//鼠标移动事件,鼠标按下并移动时调用
    glutMotionFunc(mouseMove);
	//键盘事件
	glutKeyboardFunc(keyPressed);
	//循环
	glutMainLoop();
	return 0;
}
效果;


折叠其代码来看下函数;



三 绘制立方体

代码:
#include <gl/glut.h>  //引用相关包

void display(void)
{
 
 glClear(GL_COLOR_BUFFER_BIT);  //清空颜色缓冲区
 glColor3f(0,1,1);   //重置颜色
 glLoadIdentity();   //清空矩阵
 glTranslatef(0,0,-5); //将场景中的物体沿z轴负方向移动5个单位长
 glRotatef(40,0,1,0);
 //gluLookAt(0,0,5,0,0,0,0,2,0); //视点变换
 glScalef(1,2,1);  //模型变换
 glutWireCube(1.2); //绘制实心立方体和线框立方体
 glFlush();   //刷新窗口以显示当前绘制图形
} 
void init(void)
{
 glClearColor(0,0,0,0);
 glShadeModel(GL_FLAT); //选择平面明暗模式或光滑明暗模式
}

void reshape(int w,int h)
{
 glViewport(0,0,(GLsizei)w,(GLsizei)h);   //设置机口
 glMatrixMode(GL_PROJECTION);  //指定哪一个矩阵是当前矩阵
 glLoadIdentity();
    gluPerspective(60,1,1.5,20);   //创建透视投影矩阵(fovy,aspect,zNear,zFar);
 //glFrustum(-1,1,-1,1,1.5,20.0);  //用透视矩阵乘以当前矩阵(left,Right,bottom,top,near,far);
 glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char *argv[])
{
 glutInit(&argc, argv); //固定格式
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);   //缓存模式
 glutInitWindowSize(400, 400);    //显示框的大小
    glutInitWindowPosition(400,400); //确定显示框左上角的位置
    glutCreateWindow("绘制立方体");
 init();
    glutDisplayFunc(display);
 glutReshapeFunc(reshape);
    glutMainLoop(); //进人GLUT事件处理循环
    return 0;
}
效果:




上述分别是

glutWireCube(1.2);

glutWireCube(2.0);

的效果;

四 绘制立方体二

代码:

#include<windows.h>
#include<math.h>
 
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
 
#include <stdlib.h>
 
void init(void)
{
  glClearColor(0.75,0.75,0.75,0.0);
  glMatrixMode(GL_MODELVIEW);//设置当前矩阵模式为视图模型矩阵
  glLoadIdentity();
//设置视点的位置,视线的方向和相机的向上方向
  gluLookAt(0,0,0, 0,0,-1, 0,1,0); //该设置为默认设置
  glScalef(0.3,1.0,0.5); //产生比例变换,分别设置物体在x,y,z方向上缩放因子,根据需要自己可以设置
  glRotatef(45,1.0,1.0,1.0);//产生旋转变换,让物体绕(1,1,1)轴旋转45度
  glMatrixMode(GL_PROJECTION);//设置当前矩阵模式为投影矩阵
  glFrustum(-4,4,-4,4,0,20);////设置场景投影时的可视范围
}
 //float points[8][3] = {{0,0,0},{0,0.5,0},{0.5,0,0},{0.5,0.5,0},{0,0,0.5},{0,0.5,0.5},{0.5,0,0.5},{0.5,0.5,0.5}};
 float points[8][3] = {{0,0,0},{0,0.75,0},{0.75,0,0},{0.75,0.75,0},{0,0,0.75},{0,0.75,0.75},{0.75,0,0.75},{0.75,0.75,0.75}};
 float colors[6][3] = {{0.25,0,0},{0.25,0.25,0.25},{0,0,0.25},{0.5,0.25,0},{0,0.25,0.25},{0.25,0,0.25}};
 
void vertexArray(void)
{
 glClear(GL_COLOR_BUFFER_BIT);
// glColor 3f(1.0,1.0,0.0);
 //glPolygonMode(GL_FRONT, GL_LINE);// 设置多边形的显示模式为面填充模式,该设置也是默认设置
 glFrontFace(GL_CCW); //设置前面的面的模式为逆时针模式, 该设置也是默认设置
 //glShadeModel(GL_SHADE_MODEL);// 默认就是此参数,可忽略,为了明确说明特意指定
 
 
void quad(GLint n1,GLint n2,GLint n3,GLint n4,GLint index);
    quad(6,2,3,7,1);
    quad(5,1,0,4,2);
    quad(7,3,1,5,3);
    quad(4,0,2,6,4);
    quad(2,0,1,3,5);
    quad(7,5,4,6,6);
glFlush();
}
 
void quad(GLint n1,GLint n2,GLint n3,GLint n4,GLint index)
{
    glColor3f(0.0,1.0,0.0);
    glEnable(GL_POLYGON_OFFSET_FILL);
    glPolygonOffset(1.0,1.0);
    glDisable(GL_POLYGON_OFFSET_FILL);
    glColor3f(colors[index][0],colors[index][1],colors[index][2]);
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    //glPolygonMode(GL_FRONT, GL_LINE);
    glPolygonMode(GL_BACK, GL_LINE);
    //glColor3f(1.0,1.0,0);
    glBegin(GL_QUADS);
        glVertex3fv(points[n1]);
        glVertex3fv(points[n2]);
        glVertex3fv(points[n3]);
        glVertex3fv(points[n4]);
    glEnd();
}
 
int main (int argc, char** argv)
{
 
    glutInit (&argc, argv);                         // Initialize GLUT.
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);   // Set display mode.
    glutInitWindowPosition (50, 100);   // Set top-left display-window position.
    glutInitWindowSize (600, 500);      // Set display-window width and height.
    glutCreateWindow ("An Example OpenGL Program"); // Create display window.
       init();                           // Execute initialization procedure.
    glutDisplayFunc (vertexArray);       // Send graphics to display window.
    glutMainLoop ( );// Send graphics to display window.                  // Display everything and wait.
       return 0;
}
效果:


五 任意两点间画圆柱体

#include <gl/glut.h>  
#include <cstdio>  
#include <cstdlib>  
#include <cmath>  
void    init(void);  
void    reshape(int w,int h);  
void    display(void);  
  
void RenderBone(float x0, float y0, float z0, float x1, float y1, float z1 );  
int main(int argc, char** argv)  
{  
    glutInit(&argc, argv);  
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);   
    glutInitWindowSize (500, 500);  
    glutInitWindowPosition (100, 100);  
    glutCreateWindow("Sphere");  
    init ();  
    glutReshapeFunc(reshape);  
    glutDisplayFunc(display);  
    glutMainLoop();  
    return 0;  
}  
void init (void)  
{   
    glClearColor (0.6, 0.6, 0.6, 0.0);  
    glClearDepth(1);  
    glShadeModel(GL_SMOOTH);  
    GLfloat _ambient[]={1.0,1.0,1.0,1.0};  
	//GLfloat _ambient[]={2.0,2.0,2.0,2.0};  
    GLfloat _diffuse[]={1.0,1.0,0.0,1.0};  
    GLfloat _specular[]={1.0,1.0,1.0,1.0};  
    GLfloat _position[]={300,300,300,0};  
    glLightfv(GL_LIGHT0,GL_AMBIENT,_ambient);  
    glLightfv(GL_LIGHT0,GL_DIFFUSE,_diffuse);  
    glLightfv(GL_LIGHT0,GL_SPECULAR,_specular);  
    glLightfv(GL_LIGHT0,GL_POSITION,_position);  
    glEnable(GL_TEXTURE_2D);  
    glEnable(GL_LIGHTING);  
    glEnable(GL_LIGHT0);  
    glEnable(GL_DEPTH_TEST);  
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  
}  
void reshape(int w, int h)  
{  
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);  
    glMatrixMode(GL_PROJECTION);  
    glLoadIdentity();  
    glOrtho(0.0, 500, 0.0, 500, -500, 500);  
    glMatrixMode(GL_MODELVIEW);  
    glLoadIdentity();  
}  
void display(void)  
{  
    glMatrixMode(GL_MODELVIEW);  
    glLoadIdentity();  
    glClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);  
    glPushMatrix();  
    {  
        //RenderBone(100, 100, 100, 200, 300, 500);  
		RenderBone(200, 200, 200, 300, 400, 600);  
    } glPopMatrix();  
  
    glFlush();  
    glutPostRedisplay();  
}  
void RenderBone(float x0, float y0, float z0, float x1, float y1, float z1 )  
{  
    GLdouble  dir_x = x1 - x0;  
    GLdouble  dir_y = y1 - y0;  
    GLdouble  dir_z = z1 - z0;  
    GLdouble  bone_length = sqrt( dir_x*dir_x + dir_y*dir_y + dir_z*dir_z );  
    static GLUquadricObj *  quad_obj = NULL;  
    if ( quad_obj == NULL )  
        quad_obj = gluNewQuadric();  
    gluQuadricDrawStyle( quad_obj, GLU_FILL );  
    gluQuadricNormals( quad_obj, GLU_SMOOTH );  
    glPushMatrix();  
    // 平移到起始点  
    glTranslated( x0, y0, z0 );  
    // 计算长度  
    double  length;  
    length = sqrt( dir_x*dir_x + dir_y*dir_y + dir_z*dir_z );  
    if ( length < 0.0001 ) {   
        dir_x = 0.0; dir_y = 0.0; dir_z = 1.0;  length = 1.0;  
    }  
    dir_x /= length;  dir_y /= length;  dir_z /= length;  
    GLdouble  up_x, up_y, up_z;  
    up_x = 0.0;  
    up_y = 1.0;  
    up_z = 0.0;  
    double  side_x, side_y, side_z;  
    side_x = up_y * dir_z - up_z * dir_y;  
    side_y = up_z * dir_x - up_x * dir_z;  
    side_z = up_x * dir_y - up_y * dir_x;  
    length = sqrt( side_x*side_x + side_y*side_y + side_z*side_z );  
    if ( length < 0.0001 ) {  
        side_x = 1.0; side_y = 0.0; side_z = 0.0;  length = 1.0;  
    }  
    side_x /= length;  side_y /= length;  side_z /= length;  
    up_x = dir_y * side_z - dir_z * side_y;  
    up_y = dir_z * side_x - dir_x * side_z;  
    up_z = dir_x * side_y - dir_y * side_x;  
    // 计算变换矩阵  
    GLdouble  m[16] = { side_x, side_y, side_z, 0.0,  
        up_x,   up_y,   up_z,   0.0,  
        dir_x,  dir_y,  dir_z,  0.0,  
        0.0,    0.0,    0.0,    1.0 };  
    glMultMatrixd( m );  
    // 圆柱体参数  
    GLdouble radius= 25;        // 半径  
    GLdouble slices = 8.0;      //  段数  
    GLdouble stack = 3.0;       // 递归次数  
    gluCylinder( quad_obj, radius, radius, bone_length, slices, stack );   
    glPopMatrix();  
} 
效果:



修改此句以改变半径;

GLdouble radius= 25;        // 半径

六 球体

#include <windows.h>  
#include <gl/GL.h>  
#include <gl/glu.h>  
#include <gl/glut.h>  
#include <cstdlib>  
const GLfloat lightPosition[] = {10.0,10.0,10.0,0.0};  
const GLfloat whiteLight[] = {0.8,0.8,0.8,1.0};  
GLfloat matSpecular [] = {0.3,0.3,0.3,1.0};  
GLfloat matShininess [] = {20.0};  
GLfloat matEmission [] = {0.3,0.3,0.3,1.0};  
GLfloat spin = 0;  
void init()  
{  
    glClearColor(0.3,0.3,0.3,1.0);  
    glClearDepth(1.0);  
    glShadeModel(GL_SMOOTH);  
    glEnable(GL_LIGHTING);  
    glEnable(GL_LIGHT0);  
    glEnable(GL_DEPTH_TEST);  
    glMatrixMode(GL_MODELVIEW);  
    glLoadIdentity();  
    glLightfv(GL_LIGHT0,GL_POSITION,lightPosition);  
    glLightfv(GL_LIGHT0,GL_DIFFUSE,whiteLight);  
    glLightfv(GL_LIGHT0,GL_SPECULAR,whiteLight);  
}  
void display()  
{     
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);  
    glMatrixMode(GL_PROJECTION);  
    glLoadIdentity();;  
    glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);  
      
    glMatrixMode(GL_MODELVIEW);  
    glPushMatrix();  
    glRotatef(spin,0.0,1.0,0.0);  
    glMaterialfv(GL_FRONT,GL_SPECULAR,matSpecular);  
    glMaterialfv(GL_FRONT,GL_SHININESS,matShininess);  
    glMaterialfv(GL_FRONT,GL_EMISSION,matEmission);  
    //glutSolidSphere(6.0,16,16);  
	glutSolidSphere(3.0,16,16);  
    glPopMatrix();  
    glFlush();  
}  
void reshape(int w,int h)  
{  
    glViewport(0.0,0.0,(GLsizei) w,(GLsizei) h);  
}  
void keyboardFunc(unsigned char key,int x,int y)  
{  
    switch(key)  
    {  
    case 'a':  
        spin +=30;  
        break;  
    case 'd':  
        spin -=30;  
        break;  
    }  
    if(spin<360)  
        spin +=360;  
    else if(spin>=360)  
        spin -=360;  
    glutPostRedisplay();  
}  
void mouseFunc(int button,int state,int x,int y)  
{  
    if(state==GLUT_DOWN){  
    switch (button)  
    {  
    case GLUT_LEFT_BUTTON:  
        matEmission[0]+=1.0;  
        if(matEmission[0]>1.0)  
            matEmission[0]-=1.1;  
        break;  
    case GLUT_MIDDLE_BUTTON:  
        matEmission[1]+=1.0;  
        if(matEmission[1]>1.0)  
            matEmission[1]-=1.1;  
        break;  
    case GLUT_RIGHT_BUTTON:  
        matEmission[2]+=1.0;  
        if(matEmission[2]>1.0)  
            matEmission[2]-=1.1;  
        break;  
    }  
    glutPostRedisplay();      
    }  
}  
int main(int argc,char *argv[])  
{     
    glutInit(&argc,argv);  
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA|GLUT_DEPTH);  
    glutInitWindowSize(450,450);  
    glutInitWindowPosition(150,150);  
    glutCreateWindow("rotate sphere");  
    glutDisplayFunc(display);  
    glutReshapeFunc(reshape);  
    glutKeyboardFunc(keyboardFunc);  
    glutMouseFunc(mouseFunc);  
    init();  
    glutMainLoop();  
    return EXIT_SUCCESS;  
} 
效果:



上述分别是

    //glutSolidSphere(6.0,16,16);  
glutSolidSphere(3.0,16,16); 

的效果;

七 球体,圆圈,茶壶......

#include <gl/glut.h>  
#include <math.h>  
#include <stdio.h>  
//圆周率宏  
#define GL_PI 3.1415f  
//获取屏幕的宽度  
GLint SCREEN_WIDTH=0;  
GLint SCREEN_HEIGHT=0;  
//设置程序的窗口大小  
GLint windowWidth=400;  
GLint windowHeight=300;  
//绕x轴旋转角度  
GLfloat xRotAngle=0.0f;  
//绕y轴旋转角度  
GLfloat yRotAngle=0.0f;  
//受支持的点大小范围  
GLfloat sizes[2];  
//受支持的点大小增量  
GLfloat step;  
  
enum MODELS{  
    SPHERE=0,  
    CONE,  
    CUBE,  
    TORUS,  
    DODECAHEDRON,  
    TEAPOT,  
    OCTAHEDRON,  
    TETRAHEDRON,  
    ICOSAHEDRON  
};  
GLint iModel=SPHERE;  
GLboolean bWire=GL_TRUE;  
//菜单回调函数  
void processMenu(int value){  
    switch(value){  
        case 1:  
            iModel=SPHERE;  
            break;  
        case 2:  
            iModel=CONE;  
            break;  
        case 3:  
            iModel=CUBE;  
            break;  
        case 4:  
            iModel=TORUS;  
            break;  
        case 5:  
            iModel=DODECAHEDRON;  
            break;  
        case 6:  
            iModel=TEAPOT;  
            break;  
        case 7:  
            iModel=OCTAHEDRON;  
            break;  
        case 8:  
            iModel=TETRAHEDRON;  
            break;  
        case 9:  
            iModel=ICOSAHEDRON;  
            break;  
        case 10:  
            bWire=GL_TRUE;  
            break;  
        case 11:  
            bWire=GL_FALSE;  
            break;  
        default:  
            break;  
    }  
    //重新绘制  
    glutPostRedisplay();  
}  
//显示回调函数  
void renderScreen(void){  
    //将窗口颜色清理为黑色  
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);  
    //将模板缓冲区值全部清理为1  
    glClearStencil(1);  
    //使能模板缓冲区  
    glEnable(GL_STENCIL_TEST);  
    //把整个窗口清理为当前清理颜色:黑色。清除深度缓冲区、模板缓冲区  
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);  
    //将当前Matrix状态入栈  
    glPushMatrix();  
    //坐标系绕x轴旋转xRotAngle  
    glRotatef(xRotAngle,1.0f,0.0f,0.0f);  
    //坐标系绕y轴旋转yRotAngle  
    glRotatef(yRotAngle,0.0f,1.0f,0.0f);  
    //进行平滑处理   
    glEnable(GL_POINT_SMOOTH);  
    glHint(GL_POINT_SMOOTH,GL_NICEST);  
    glEnable(GL_LINE_SMOOTH);  
    glHint(GL_LINE_SMOOTH,GL_NICEST);  
    glEnable(GL_POLYGON_SMOOTH);  
    glHint(GL_POLYGON_SMOOTH,GL_NICEST);  
      
    //白色绘制坐标系  
    glColor3f(1.0f,1.0f,1.0f);  
    glBegin(GL_LINES);  
        glVertex3f(-9.0f,0.0f,0.0f);  
        glVertex3f(9.0f,0.0f,0.0f);  
        glVertex3f(0.0f,-9.0f,0.0f);  
        glVertex3f(0.0f,9.0f,0.0f);  
        glVertex3f(0.0f,0.0f,-9.0f);  
        glVertex3f(0.0f,0.0f,9.0f);  
    glEnd();  
  
    glPushMatrix();  
    glTranslatef(9.0f,0.0f,0.0f);  
    glRotatef(90.0f,0.0f,1.0f,0.0f);  
    glutSolidCone(0.3,0.6,10,10);  
    glPopMatrix();  
  
    glPushMatrix();  
    glTranslatef(0.0f,9.0f,0.0f);  
    glRotatef(-90.0f,1.0f,0.0f,0.0f);  
    glutSolidCone(0.3,0.6,10,10);  
    glPopMatrix();  
  
    glPushMatrix();  
    glTranslatef(0.0f,0.0f,9.0f);  
    glRotatef(90.0f,0.0f,0.0f,1.0f);  
    glutSolidCone(0.3,0.6,10,10);  
    glPopMatrix();  
  
    //设置绘画颜色为金色  
    glColor3f(0.0f,1.0f,0.0f);  
    switch(iModel){  
        //球  
        case SPHERE:  
            if(bWire){  
                glutWireSphere(8.0f,20,20);  
            }  
            else{  
                glutSolidSphere(8.0f,20,20);  
            }  
            break;  
        //锥体  
        case CONE:  
            if(bWire){  
                glutWireCone(4.0f,8.0f,20,20);  
            }  
            else{  
                glutSolidCone(4.0f,8.0f,20,20);  
            }  
            break;  
        //立体  
        case CUBE:  
            if(bWire){  
                glutWireCube(8.0f);  
            }  
            else{  
                glutSolidCube(8.0f);  
            }  
            break;  
        //甜圈  
        case TORUS:  
            if(bWire){  
                glutWireTorus(3.0f,6.0f,20,20);  
            }  
            else{  
                glutSolidTorus(3.0f,6.0f,20,20);  
            }  
            break;  
        //十六面体,默认半径1.0  
        case DODECAHEDRON:  
            glScalef(6.0f,6.0f,6.0f);//x,y,z轴均放大6倍  
            if(bWire){  
                glutWireDodecahedron();  
            }  
            else{  
                glutSolidDodecahedron();  
            }  
            break;  
        //茶壶  
        case TEAPOT:  
            if(bWire){  
                glutWireTeapot(8.0f);  
            }  
            else{  
                glutSolidTeapot(8.0f);  
            }  
            break;  
        //八面体,默认半径1.0  
        case OCTAHEDRON:  
            glScalef(6.0f,6.0f,6.0f);//x,y,z轴均放大6倍  
            if(bWire){  
                glutWireOctahedron();  
            }  
            else{  
                glutSolidOctahedron();  
            }  
            break;  
        //四面体,默认半径1.0  
        case TETRAHEDRON:  
            glScalef(6.0f,6.0f,6.0f);//x,y,z轴均放大6倍  
            if(bWire){  
                glutWireTetrahedron();  
            }  
            else{  
                glutSolidTetrahedron();  
            }  
            break;  
        //二十面体,默认半径1.0  
        case ICOSAHEDRON:  
            glScalef(6.0f,6.0f,6.0f);//x,y,z轴均放大6倍  
            if(bWire){  
                glutWireIcosahedron();  
            }  
            else{  
                glutSolidIcosahedron();  
            }  
            break;  
        default:  
            break;  
    }  
  
    //恢复压入栈的Matrix  
    glPopMatrix();  
    //交换两个缓冲区的指针  
    glutSwapBuffers();  
}  
//设置Redering State   
void setupRederingState(void){  
    //设置清理颜色为黑色  
    glClearColor(0.0f,0.0,0.0,1.0f);  
    //设置绘画颜色为绿色  
    glColor3f(1.0f,1.0f,0.0f);  
    //使能深度测试  
    glEnable(GL_DEPTH_TEST);  
    //获取受支持的点大小范围  
    glGetFloatv(GL_POINT_SIZE_RANGE,sizes);  
    //获取受支持的点大小增量  
    glGetFloatv(GL_POINT_SIZE_GRANULARITY,&step);  
    printf("point size range:%f-%f\n",sizes[0],sizes[1]);  
    printf("point step:%f\n",step);  
}  
//窗口大小变化回调函数  
void changSize(GLint w,GLint h){  
    //横宽比率  
    GLfloat ratio;  
    //设置坐标系为x(-100.0f,100.0f)、y(-100.0f,100.0f)、z(-100.0f,100.0f)  
    GLfloat coordinatesize=10.0f;  
    //窗口宽高为零直接返回  
    if((w==0)||(h==0))  
        return;  
    //设置视口和窗口大小一致  
    glViewport(0,0,w,h);  
    //对投影矩阵应用随后的矩阵操作  
    glMatrixMode(GL_PROJECTION);  
    //重置当前指定的矩阵为单位矩阵   
    glLoadIdentity();  
    ratio=(GLfloat)w/(GLfloat)h;  
    //正交投影  
    if(w<h)  
        glOrtho(-coordinatesize,coordinatesize,-coordinatesize/ratio,coordinatesize/ratio,-coordinatesize,coordinatesize);  
    else  
        glOrtho(-coordinatesize*ratio,coordinatesize*ratio,-coordinatesize,coordinatesize,-coordinatesize,coordinatesize);  
    //对模型视图矩阵堆栈应用随后的矩阵操作  
    glMatrixMode(GL_MODELVIEW);  
    //重置当前指定的矩阵为单位矩阵   
    glLoadIdentity();  
}  
  
//按键输入处理回调函数  
void specialKey(int key,int x,int y){  
  
    if(key==GLUT_KEY_UP){  
        xRotAngle-=5.0f;  
    }  
    else if(key==GLUT_KEY_DOWN){  
        xRotAngle+=5.0f;  
    }  
    else if(key==GLUT_KEY_LEFT){  
        yRotAngle-=5.0f;  
    }  
    else if(key==GLUT_KEY_RIGHT){  
        yRotAngle+=5.0f;  
    }  
    //重新绘制  
    glutPostRedisplay();  
}  
  
int main(int argc, char* argv[])  
{  
    int nModelMenu;  
    int nWireMenu;  
    int nMainMenu;  
    //初始化glut   
    glutInit(&argc,argv);  
    //使用双缓冲区、深度缓冲区、模板缓冲区  
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);  
    //获取系统的宽像素  
    SCREEN_WIDTH=glutGet(GLUT_SCREEN_WIDTH);  
    //获取系统的高像素  
    SCREEN_HEIGHT=glutGet(GLUT_SCREEN_HEIGHT);  
    //创建窗口,窗口名字为OpenGL Glut Demo  
    glutCreateWindow("OpenGL Glut Demo");  
    //设置窗口大小  
    glutReshapeWindow(windowWidth,windowHeight);  
    //窗口居中显示  
    glutPositionWindow((SCREEN_WIDTH-windowWidth)/2,(SCREEN_HEIGHT-windowHeight)/2);  
    //创建二级菜单  
    nModelMenu=glutCreateMenu(processMenu);  
    glutAddMenuEntry("Sphere",1);  
    glutAddMenuEntry("Cone",2);  
    glutAddMenuEntry("Cube",3);  
    glutAddMenuEntry("Torus",4);  
    glutAddMenuEntry("Dodecahedron",5);  
    glutAddMenuEntry("Teapot",6);  
    glutAddMenuEntry("Octahedron",7);  
    glutAddMenuEntry("Tetrahedron",8);  
    glutAddMenuEntry("Icosahedron",9);  
    nWireMenu=glutCreateMenu(processMenu);  
    glutAddMenuEntry("Wire",10);  
    glutAddMenuEntry("Solid",11);  
    nMainMenu=glutCreateMenu(processMenu);  
    glutAddSubMenu("Model",nModelMenu);  
    glutAddSubMenu("WireOrSolid",nWireMenu);  
    //将菜单榜定到鼠标右键上  
    glutAttachMenu(GLUT_RIGHT_BUTTON);  
    //窗口大小变化时的处理函数  
    glutReshapeFunc(changSize);  
    //设置显示回调函数   
    glutDisplayFunc(renderScreen);  
    //设置按键输入处理回调函数  
    glutSpecialFunc(specialKey);  
    //设置全局渲染参数  
    setupRederingState();  
    glutMainLoop();  
    return 0;  
} 
右键选择mode查看不同3d图形;光标键调整角度;
球体;


调整角度;


甜圈;


这只就是著名的雪山飞壶;


折叠起代码来看下函数;


Glut下提供了一些现成的绘制立体的API,如glutWireSphere绘制球,glutWireCone绘制椎体,glutWireCube绘制立体,glutWireTorus绘制甜圈,glutWireTeapot绘制茶壶,glutWireOctahedron绘制八面体。
Glut提供的多面体API默认半径是1.0f的,使用glScalef对其进行放大。

八 opengl资源链接

http://blog.csdn.net/one_in_one/article/category/960777
http://blog.csdn.net/yearafteryear/article/category/1442065
http://blog.csdn.net/Augusdi/article/category/685679
http://cuiqingcai.com/category/technique/cc


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页