OpenGL: 用户自定义几何变换

代码如下:

#define GLUT_DISABLE_ATEXIT_HACK

#include "gl/glut.h"
#pragma comment(lib, "glut32.lib")

void OnDisplay(void)
{
	GLfloat mat[]=
	{
		1.0f, 0.0f,  0.0f, 0.0f,
		0.0f, -1.0f, 0.0f, 0.0f,
		0.0f, 0.0f,  1.0f, 0.0f,
		0.0f, 0.0f,  0.0f, 1.0f
	};
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
	glRotatef(15.0f, 0.0f, 1.0f, 0.0f);

	glColor3f(1.0f, 0.0f, 1.0f);
	glBegin(GL_QUADS);
	{
		glVertex3i(0, -30, -30);
		glVertex3i(0, 30, -30);
		glVertex3i(0, 30, 30);
		glVertex3i(0, -30, 30);
	}
	glEnd();

	glPushMatrix();
	{
		glTranslatef(30.0f, 0.0f, 0.0f);
		glColor3f(1.0f, 1.0f, 0.0f);
		glutSolidCube(50.0f);
	}
	glPopMatrix();

	glPushMatrix();
	{
		glMultMatrixf(mat);
		glTranslatef(-30.0f, 0.0f, 0.0f);
		glColor3f(1.0f, 0.0f, 0.0f);
		glutSolidCube(50.0f);
	}
	glPopMatrix();

	glutSwapBuffers();
}

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

	glViewport(0, 0, w, h);

	glMatrixMode(GL_PROJECTION);     //将当前矩阵指定为投影模式
	glLoadIdentity();

	//设置三维投影区
	if (w <= h)
	{
		glOrtho(-nRange, nRange, -nRange * aspect, nRange * aspect, -nRange, nRange);
	} 
	else
	{
		glOrtho(-nRange, nRange, -nRange / aspect, nRange / aspect, -nRange, nRange);
	}
}
void SetupLights()
{
	GLfloat ambientLight[]  ={0.2f,  0.2f,  0.2f,  1.0f};//环境光
	GLfloat diffuseLight[]  ={0.9f,  0.9f,  0.9f,  1.0f};//漫反射
	GLfloat specularLight[] ={1.0f,  1.0f,  1.0f,  1.0f};//镜面光
	GLfloat lightPos[]      ={50.0f, 80.0f, 60.0f, 1.0f};//光源位置

	glEnable(GL_LIGHTING);								//启用光照
	glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);		//设置环境光源
	glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);		//设置漫反射光源
	glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);	//设置镜面光源
	glLightfv(GL_LIGHT0, GL_POSITION, lightPos);		//设置灯光位置
	glEnable(GL_LIGHT0);								//打开第一个灯光

	glEnable(GL_COLOR_MATERIAL);						//启用材质的颜色跟踪
	glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);	//指定材料着色的面
	glMaterialfv(GL_FRONT, GL_SPECULAR, specularLight); //指定材料对镜面光的反应
	glMateriali(GL_FRONT, GL_SHININESS, 100);           //指定反射系数
}
void main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(600, 480);
	glutCreateWindow("OpenGL用户自定义几何变换");

	glutReshapeFunc(OnReShape);
	glutDisplayFunc(OnDisplay);

	SetupLights();

	glutMainLoop();
}

运行效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值