参考了tabfuns的一篇文章:踏入OpenGL大门——VS2015开发环境配置(详细图文)
配置好OpenGL-VS2015的开发环境。
新建工程
打开VS2015新建一个C++win32控制台程序,根据上面配置开发环境的流程,配置好项目属性的VC++目录,附加依赖项.
头文件stadafx.h修改为:
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: 在此处引用程序需要的其他头文件
#include <glew.h> // 注意glew.h在前面,然后才是freeglut.h
#include <freeglut.h>
#pragma comment(lib,"glew32.lib") // 你也可以在项目->属性->链接器->输入->附加依赖项中添加这个库文件
#include <iostream>
using namespace std;
第一个OpenGL程序:
#include "stdafx.h"
void displayFunc();
int main(int argc,char *argv[])
{
glutInit(&argc, argv);
glutCreateWindow("我的第一个OpenGL程序");
if (glewInit())
{
cerr << "Unable to initialize GLEW ... exiting" << endl;
exit(EXIT_FAILURE);
}
glutDisplayFunc(displayFunc);
glutMainLoop();
//cin.get();
return 0;
}
绘制一个简单的立方体的代码:
#include "stdafx.h"
//#include <gl\glut.h>
//6个面的绘制顺序,存储的是顶点的下标
static const GLint quads[][4] = {
0, 2, 3, 1,
0, 4, 6, 2,
0, 1, 5, 4,
4, 5, 7, 6,
1, 3, 7, 5,
2, 6, 7, 3,
};
void draw_cube(GLfloat x,GLfloat y,GLfloat z){
//8个顶点
static const GLfloat vetexs[][3] = {
0.0,0.0,0.0,
x,0.0,0.0,
0.0,y,0.0,
x,y,0.0,
0.0,0.0,z,
x,0.0,z,
0.0,y,z,
x,y,z
};
glClear(GL_COLOR_BUFFER_BIT);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glRotated(15,1,0,0);
glRotated(15,0,1,0);
glTranslatef(-x/2,-y/2,-z/2); //平移至中心
//画立方体
for(int i = 0;i<6;i++){
glBegin(GL_QUADS);
glVertex3f(vetexs[quads[i][0]][0],vetexs[quads[i][0]][1],vetexs[quads[i][0]][2]);
glVertex3f(vetexs[quads[i][1]][0],vetexs[quads[i][1]][1],vetexs[quads[i][1]][2]);
glVertex3f(vetexs[quads[i][2]][0],vetexs[quads[i][2]][1],vetexs[quads[i][2]][2]);
glVertex3f(vetexs[quads[i][3]][0],vetexs[quads[i][3]][1],vetexs[quads[i][3]][2]);
glEnd();
}
}
void mydisplay(){
draw_cube(1.0,0.2,0.8);
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow("HelloOpenGL");
glutDisplayFunc(&mydisplay);
glutMainLoop();
return 0;
}
网友评论