Nehe教程第10课4D世界源程序及资源
#include <stdlib.h> #include <math.h> #include <stdio.h> #include <windows.h> // Windows的头文件 #include <gl/glew.h> // 包含最新的gl.h,glu.h库 #include <gl/glut.h> // 包含OpenGL实用库 #include <gl/glaux.h> HGLRC hRC=NULL; //窗口着色描述表句柄 HDC hDC=NULL; //设备渲染描述表句柄 HWND hWND=NULL; //窗口句柄 HINSTANCE hInstance; //保存程序的实例 bool keys[256]; bool active=TRUE; //窗口的活动状态,缺省为true bool fullscreen=TRUE; //全屏的缺省状态=true bool blend; // Blending ON/OFF bool bp; // B Pressed? bool fp; // F Pressed? const float piover180 = 0.0174532925f; float heading; float xpos; float zpos; GLfloat yrot; // Y Rotation GLfloat walkbias = 0; GLfloat walkbiasangle = 0; GLfloat lookupdown = 0.0f; GLfloat z=0.0f; // Depth Into The Screen GLuint filter; // Which Filter To Use GLuint texture[3]; // Storage For 3 Textures typedef struct tagVERTEX { float x,y,z; float u,v; } VERTEX; typedef struct tagTRIANGLE { VERTEX vertex[3]; }TRIANGLE; typedef struct tagSECTOR { int numtriangles; TRIANGLE *triangle; } SECTOR; SECTOR sector1;//our model goes here: LRESULT CALLBACK WndProc(HWND, UINT,WPARAM, LPARAM); //Declaration for wndproc void readstr(FILE*f,char*string) { do { fgets(string,255,f); } while ((string[0]=='/')||(string[0]=='\n'));//考察是否有必要处理 return; } void SetupWorld() { float x,y,z,u,v; int numtriangles; FILE*filein; char oneline[255]; filein = fopen("data/world.txt", "rt"); // File To Load World Data From readstr(filein,oneline); sscanf(oneline,"NUMPOLLIES %d\n",&numtriangles); sector1.triangle=new TRIANGLE[numtriangles]; sector1.numtriangles=numtriangles; for (int triloop=0; triloop<numtriangles; triloop++ ) { for (int vertloop=0; vertloop<3;vertloop++) { readstr(filein,oneline);//读入一行数据 sscanf(oneline,"%f %f %f %f %f",&x,&y,&z,&u,&v); sector1.triangle[triloop].vertex[vertloop].x=x; sector1.triangle[triloop].vertex[vertloop].y=y; sector1.triangle[triloop].vertex[vertloop].z=z; sector1.triangle[triloop].vertex[vertloop].u=u; sector1.triangle[triloop].vertex[vertloop].v=v; } } fclose(filein); return; } AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image { FILE *File=NULL; // File Handle if (!Filename) // Make Sure A Filename Was Given { return NULL; // If Not Return NULL } File=fopen(Filename,"r"); // Check To See If The File Exists if (File) // Does The File Exist? { fclose(File); // Close The Handle return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer } return NULL; // If Load Failed Return NULL } int LoadGLTextures() // Load Bitmaps And Convert To Textures { int Status=FALSE; // Status Indicator AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL // Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit if (TextureImage[0]=LoadBMP("Data/Mud.bmp")) { Status=TRUE; // Set The Status To TRUE glGenTextures(3, &texture[0]); // Create Three Textures // Create Nearest Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); // Create Linear Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); // Create MipMapped Texture glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); // Free The Texture Image Memory } free(TextureImage[0]); // Free The Image Structure } return Status; // Return The Status } GLvoid ReSizeGLScene(GLsizei width,GLsizei height) { if (height==0) { 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); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } int InitGL(GLvoid) // All Setup For OpenGL Goes Here { if (!LoadGLTextures()) // Jump To Texture Loading Routine { return FALSE; // If Texture Didn't Load Return FALSE } glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Set The Blending Function For Translucency glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This Will Clear The Background Color To Black glClearDepth(1.0); // Enables Clearing Of The Depth Buffer glDepthFunc(GL_LESS); // The Type Of Depth Test To Do glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); SetupWorld(); return TRUE; } int DrawGLScene(GLvoid) { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity(); GLfloat x_m,y_m,z_m,u_m,v_m; GLfloat xtrans=-xpos; GLfloat ztrans=-zpos; GLfloat ytrans=-walkbias-0.25f;//用于头部上下摆动 GLfloat sceneroty=360.0f-yrot;//位于游戏者方向的360度角 int numtriangles; glRotatef(lookupdown,1.0f,0,0);//上下旋转 glRotatef(sceneroty,0,1.0f,0);//根据游戏者正面所对方向做的旋转 glTranslatef(xtrans,ytrans,ztrans);//以游戏者为中心的平移场景 glBindTexture(GL_TEXTURE_2D,texture[filter]); numtriangles=sector1.numtriangles; //处理每条边 for (int loop_m=0;loop_m<numtriangles;loop_m++) { glBegin(GL_TRIANGLES); glNormal3f( 0.0f, 0.0f, 1.0f); x_m = sector1.triangle[loop_m].vertex[0].x; y_m = sector1.triangle[loop_m].vertex[0].y; z_m = sector1.triangle[loop_m].vertex[0].z; u_m = sector1.triangle[loop_m].vertex[0].u; v_m = sector1.triangle[loop_m].vertex[0].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); x_m = sector1.triangle[loop_m].vertex[1].x; y_m = sector1.triangle[loop_m].vertex[1].y; z_m = sector1.triangle[loop_m].vertex[1].z; u_m = sector1.triangle[loop_m].vertex[1].u; v_m = sector1.triangle[loop_m].vertex[1].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); x_m = sector1.triangle[loop_m].vertex[2].x; y_m = sector1.triangle[loop_m].vertex[2].y; z_m = sector1.triangle[loop_m].vertex[2].z; u_m = sector1.triangle[loop_m].vertex[2].u; v_m = sector1.triangle[loop_m].vertex[2].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); glEnd(); } return TRUE; } GLvoid KillGLWindow(GLvoid) { if (fullscreen) { ChangeDisplaySettings(NULL,0); //Windows API 把缺省显示设备的设置改变为由第一个参数设定的图形模式 ShowCursor(TRUE); //Window32API 显示鼠标 } if (hRC) { if (!wglMakeCurrent(NULL,NULL)) { MessageBox(NULL,"释放DC或RC失败","Shutdown Error",MB_OK|MB_ICONINFORMATION); } if (!wglDeleteContext(hRC)) { MessageBox(NULL,"释放RC失败","Shutdown Error",MB_OK|MB_ICONINFORMATION); } hRC=NULL; //setRC toNull } if (hDC&&!ReleaseDC(hWND,hDC)) { MessageBox(NULL,"不能释放DC失败","Shutdown Error",MB_OK|MB_ICONINFORMATION); hDC=NULL; } if (hWND&&!DestroyWindow(hWND)) { MessageBox(NULL,"释放窗口句柄失败","Shutdown Error",MB_OK|MB_ICONINFORMATION); hWND=NULL; } if (!UnregisterClass("OpenGL",hInstance)) { MessageBox(NULL,"不能注销窗口类","Shutdown Error",MB_OK|MB_ICONINFORMATION); hInstance=NULL; } } //创建OpenGL窗口 窗口标题 宽 高 颜色位 全屏标志 BOOL CreateGLWindow(char* title,int width,int height,int bits,bool fullscreenflag) { GLuint PixelFormat; WNDCLASS wc; DWORD dwStyle;//窗口风格 DWORD dwExStyle;//扩展窗口风格 RECT WindowRect; WindowRect.left=(long)0; WindowRect.right=(long)width; WindowRect.top=(long)0; WindowRect.bottom=(long)height; fullscreen=fullscreenflag; hInstance=GetModuleHandle(NULL);//获取一个应用程序或动态链接库的模块句柄 ,NULL返回自身应用程序句柄 wc.style=CS_VREDRAW|CS_HREDRAW|CS_OWNDC;//移动时重画,并为窗口取得DC wc.lpfnWndProc=(WNDPROC)WndProc; //WndProc处理消息 wc.cbClsExtra = 0; // 无额外窗口数据 wc.cbWndExtra = 0; // 无额外窗口数据 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,"注册窗口失败"," Error",MB_OK|MB_ICONEXCLAMATION);//EXCLAMATION感叹号 return FALSE; } if (fullscreen)//全屏模式 { DEVMODE dmScreenSettings; //设备模式 memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); //确保内存清空为0 dmScreenSettings.dmSize=sizeof(dmScreenSettings); //DEVMODE结构的大小 dmScreenSettings.dmPelsWidth=width; dmScreenSettings.dmPelsHeight=height; //所选屏幕高度 dmScreenSettings.dmBitsPerPel=bits; //每像素颜色数 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSHEIGHT|DM_PELSWIDTH; if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // 若模式失败,提供两个选项:退出或在窗口内运行。 if (MessageBox(NULL,"全屏模式在当前显示卡上设置失败!\n使用窗口模式","Nehe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=false; } else//用户选择退出 { // MessageBox(NULL,"程序将被关闭","Error",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); //Windows API真正适合窗口 //Create thewindow if (!(hWND=CreateWindowEx(dwExStyle, "OpenGL", title, WS_CLIPSIBLINGS|WS_CLIPCHILDREN|dwStyle,//必须的窗体风格属性 0,0, WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top, //计算调整好的窗口高度 NULL, //无父窗口 NULL, //无子菜单 hInstance, NULL))) //不向WM_CREATE传递消息 { KillGLWindow(); MessageBox(NULL,"不能创建窗口","Error",MB_OK|MB_ICONEXCLAMATION); return FALSE; } static PIXELFORMATDESCRIPTOR pfd= // /pfd 告诉窗口我们所希望的东东,即窗口使用的像素格式 { 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))) { KillGLWindow(); MessageBox(NULL,"不能创建像素格式","错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // 能够设置象素格式么? { KillGLWindow(); // 重置显示区 MessageBox(NULL,"不能设置像素格式","错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 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); if (!InitGL()) // 初始化新建的GL窗口 { KillGLWindow(); // 重置显示区 MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 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; // 如果是,设为TRUE return 0; // 返回 } case WM_KEYUP: // 有键放开么? { keys[wParam] = FALSE; // 如果是,设为FALSE return 0; // 返回 } case WM_SIZE: // 调整OpenGL窗口大小 { ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width,HiWord=Height return 0; // 返回 } } return DefWindowProc(hWnd,uMsg,wParam,lParam); } int WINAPI WinMain( HINSTANCE hInstance, // 当前窗口实例 HINSTANCE hPrevInstance, // 前一个窗口实例 LPSTR lpCmdLine, // 命令行参数 int nCmdShow) // 窗口显示状态 { MSG msg; // Windowsx消息结构 BOOL done=FALSE; // 用来退出循环的Bool 变量 // 提示用户选择运行模式 if (MessageBox(NULL,"你想在全屏模式下运行么?", "设置全屏模式",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // FALSE为窗口模式 } // 创建OpenGL窗口 if (!CreateGLWindow("NeHe's 加载3D世界",640,480,16,fullscreen)) { return 0; // 失败退出 } while(!done) // 保持循环直到 done=TRUE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // 有消息在等待吗? { if (msg.message==WM_QUIT) // 收到退出消息? { done=TRUE; // 是,则done=TRUE } else // 不是,处理窗口消息 { TranslateMessage(&msg); // 翻译消息 DispatchMessage(&msg); // 发送消息 } } else // 如果没有消息 { if (active) // 程序激活的么? { if (keys[VK_ESCAPE]) // ESC 按下了么? { done=TRUE; // ESC 发出退出信号 } else // 不是退出的时候,刷新屏幕 { DrawGLScene(); // 绘制场景 SwapBuffers(hDC); // 交换缓存 (双缓存) if (keys['B'] && !bp) { bp=TRUE; blend=!blend; if (!blend) { glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } else { glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); } } if (!keys['B']) { bp=FALSE; } if (keys['F'] && !fp) { fp=TRUE; filter+=1; if (filter>2) { filter=0; } } if (!keys['F']) { fp=FALSE; } if(keys[VK_PRIOR]) { z-=0.02f; } if(keys[VK_NEXT]) { z+=0.02f; } if (keys[VK_UP]) { xpos-=(float)sin(heading*piover180)*0.05f; zpos-=(float)cos(heading*piover180)*0.05f; if (walkbiasangle >= 359.0f) { walkbiasangle=0.0f; } else { walkbiasangle+=10; } walkbias=(float)sin(walkbiasangle*piover180)/20.0f; } if (keys[VK_DOWN]) { xpos+=(float)sin(heading*piover180)*0.05f; zpos+=(float)cos(heading*piover180)*0.05f; if (walkbiasangle <=1.0f) { walkbiasangle=359.0f; } else { walkbiasangle-=10; } walkbias=(float)sin(walkbiasangle*piover180)/20.0f; } if(keys[VK_RIGHT]) { heading-=1.0f; yrot=heading; //yrot-=1.5f;//向左旋转场景,产生向右旋转相机的错觉 } if (keys[VK_LEFT]) { heading+=1.0f; yrot=heading; // yrot+=1.5f; } if (keys[VK_PRIOR]) { lookupdown-= 1.0f; } if (keys[VK_NEXT]) { lookupdown+= 1.0f; } } } if (keys[VK_F1]) // F1键按下了么? { keys[VK_F1]=FALSE; // 若是,使对应的Key数组中的值为 FALSE KillGLWindow(); // 销毁当前的窗口 fullscreen=!fullscreen; // 切换 全屏 / 窗口 模式 // 重建 OpenGL 窗口 if (!CreateGLWindow("NeHe's 加载3D世界",640,480,16,fullscreen)) { return 0; // 如果窗口未能创建,程序退出 } } } } // 关闭程序 KillGLWindow(); return (msg.wParam); }