正在学习OpenGL,一边学习,一边动手在编,下面的程序改编自nehe的地图加载程序,程序的编译与链接都能通过,可是窗口显示的时候会卡死,个人感觉问题可能出现在display,和reshape 处,以及main函数里面(这块有点不懂),试了很多的方法,还是没能解决问题,还望前辈们能够帮忙指点下,实在是没辙了 /(ㄒoㄒ)/~~
忘记了 这个需要一个.raw格式的图片进行导入 如果需要的话我再传上来,(公司电脑没法上传 /(ㄒoㄒ)/~~)
#include <windows.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <gl\glaux.h>
#define WIDTH 800
#define HEIGHT 535
#define STEP 5
#define HEIGHT_RATIO 0.5f
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib,"Ws2_32.lib")
BYTE mapInfo[WIDTH*HEIGHT];//设置地图信息数组
float scale = 0.15f;
int getHeight(BYTE *map, int X, int Y)//获取地形高度
{
int x = X ;
int y = Y ;
if(!map)
{
MessageBox(NULL, "No map has been found", "Error", MB_OK);
return 0;
}
return map[x + (y * HEIGHT)];
}
void setColor(BYTE *map, int x, int y)//设置地形颜色
{
if(!map) return;
float fColor = -0.15f + (getHeight(map, x, y ) / 256.0f);
glColor3f(0, 0, fColor );
}
void loadFile(char *name, int size, BYTE *map)//加载地图高程信息
{
FILE *file = NULL;
file = fopen( name, "rb" );
if ( file == NULL )
{
MessageBox(NULL, "No file has been found", "Error", MB_OK);
return;
}
fread( map, 1, size, file );
int isSuccess = ferror( file );
if (isSuccess)
{
MessageBox(NULL, "No data has been gotten", "Error", MB_OK);
}
fclose(file);
}
void init(void)//初始化
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
loadFile("pic/map.raw", WIDTH * HEIGHT, mapInfo);
return ;
}
void reshape(int width, int height)
{
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 500.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(190, 50, 50, 160, 45, 50, 0, 1, 0);
glScalef(scale, scale * HEIGHT_RATIO, scale);
}
void display(void) //渲染地图
{
BYTE *map=mapInfo;
int X = 0, Y = 0;
int x, y, z;
if(!map) return;
glBegin( GL_QUADS );
for ( X = 0; X < (WIDTH-STEP); X += STEP)
for ( Y = 0; Y < (HEIGHT-STEP); Y += STEP )
{
x = X;
y = getHeight(map, X, Y );
z = Y;
setColor(map, x, z);
glVertex3i(x, y, z);
x = X;
y = getHeight(map, X, Y + STEP );
z = Y + STEP ;
setColor(map, x, z);
glVertex3i(x, y, z);
x = X + STEP;
y = getHeight(map, X + STEP, Y + STEP );
z = Y + STEP ;
setColor(map, x, z);
glVertex3i(x, y, z);
x = X + STEP;
y = getHeight(map, X + STEP, Y );
z = Y;
setColor(map, x, z);
glVertex3i(x, y, z);
}
glEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
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);
glutMainLoop();
return 0;
}