⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lesson44.cpp

📁 关于OpenGL的实例教程源代码
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/*
 *		This Code Was Created By Jeff Molofee 2000
 *		A HUGE Thanks To Fredric Echols For Cleaning Up
 *		And Optimizing This Code, Making It More Flexible!
 *		If You've Found This Code Useful, Please Let Me Know.
 *		Visit My Site At nehe.gamedev.net
 */

#include <windows.h>												// Header File For Windows
#include <gl\gl.h>													// Header File For The OpenGL32 Library
#include <gl\glu.h>													// Header File For The GLu32 Library
#include <stdio.h>													// Header for c standard library
#include <mmsystem.h>												// Header for window multi media lib 
#include "glFont.h"													// Header for fonts
#include "glCamera.h"												// Header for the camera class

HDC			hDC=NULL;												// Private GDI Device Context
HGLRC		hRC=NULL;												// Permanent Rendering Context
HWND		hWnd=NULL;												// Holds Our Window Handle
HINSTANCE	hInstance;												// Holds The Instance Of The Application

/////////////// GLOBALS //////////////////////////////////
bool		keys[256];												// Array Used For The Keyboard Routine
bool		active=TRUE;											// Window Active Flag Set To TRUE By Default
bool		fullscreen=TRUE;										// Fullscreen Flag Set To Fullscreen Mode By Default
bool		infoOn=FALSE;
int			gFrames=0;
DWORD		gStartTime;
DWORD		gCurrentTime;
GLfloat		gFPS;
glFont		gFont;
glCamera	gCamera;



//##################  NEW STUFF  ##################################

GLUquadricObj *qobj;			//the quadric for our cylinder
GLint						cylList;

/////////////// PROTOTYPES ///////////////////////////////
LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);				// Declaration For WndProc
void DrawGLInfo(void);
void CheckKeys(void);

bool LoadTexture(LPTSTR szFileName, GLuint &texid)					// Creates Texture From A Bitmap File
{
	HBITMAP hBMP;													// Handle Of The Bitmap
	BITMAP	BMP;													// Bitmap Structure

	glGenTextures(1, &texid);										// Create The Texture
	hBMP=(HBITMAP)LoadImage(GetModuleHandle(NULL), szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE );

	if (!hBMP)														// Does The Bitmap Exist?
		return FALSE;												// If Not Return False

	GetObject(hBMP, sizeof(BMP), &BMP);								// Get The Object
																	// hBMP:        Handle To Graphics Object
																	// sizeof(BMP): Size Of Buffer For Object Information
																	// &BMP:        Buffer For Object Information

	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);							// Pixel Storage Mode (Word Alignment / 4 Bytes)

	// Typical Texture Generation Using Data From The Bitmap
	glBindTexture(GL_TEXTURE_2D, texid);								// Bind To The Texture ID
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);	// Linear Min Filter
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);	// Linear Mag Filter
	glTexImage2D(GL_TEXTURE_2D, 0, 3, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits);

	DeleteObject(hBMP);												// Delete The Object

	return TRUE;													// Loading Was Successful
}

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)					// Resize And Initialize The GL Window
{
	gCamera.m_WindowHeight = height;								// The camera needs to know the window height
	gCamera.m_WindowWidth = width;									// The camera needs to know the window width

	if (height==0)													// Prevent A Divide By Zero By
	{
		height=1;													// Making Height Equal One
	}

	glViewport(0,0,width,height);									// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);									// Select The Projection Matrix
	glLoadIdentity();												// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,1.0f,1000.0f);

	glMatrixMode(GL_MODELVIEW);										// Select The Modelview Matrix
	glLoadIdentity();												// Reset The Modelview Matrix
}

int InitGL(GLvoid)													// All Setup For OpenGL Goes Here
{
	GLuint tex=0;

	glShadeModel(GL_SMOOTH);										// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);							// Black Background
	glClearDepth(1.0f);												// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);										// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);											// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);				// Really Nice Perspective Calculations

	LoadTexture("Art/Font.bmp", tex);								// Load the font texture
	if(tex != 0)													// Make sure it was loaded
	{
		gFont.SetFontTexture(tex);									// Set the font texture
		gFont.SetWindowSize(1024, 768);								// The font class needs to know the window size
		gFont.BuildFont(1.0f);					                    // Build the font
	}
	else
	{
		MessageBox(NULL,											// We didn't load the font texture
					"Failed to load font texture.",					// so tell the user about it.
					"Error", 
					MB_OK);
	}

	gCamera.m_MaxHeadingRate = 1.0f;								// Set our Maximum rates for the camera
	gCamera.m_MaxPitchRate = 1.0f;									// Set our Maximum rates for the camera
	gCamera.m_HeadingDegrees = 0.0f;								// Set our Maximum rates for the camera

	// Try and load the HardGlow texture tell the user if we can't find it then quit
	LoadTexture("Art/HardGlow2.bmp", gCamera.m_GlowTexture);
	if(gCamera.m_GlowTexture == 0) {
		MessageBox(NULL, "Failed to load Hard Glow texture.", "Error", MB_OK);
		return(FALSE);
	}
	
	// Try and load the BigGlow texture tell the user if we can't find it then quit
	LoadTexture("Art/BigGlow3.bmp", gCamera.m_BigGlowTexture);
	if(gCamera.m_BigGlowTexture == 0) {
		MessageBox(NULL, "Failed to load Big Glow texture.", "Error", MB_OK);
		return(FALSE);
	}
	
	// Try and load the Halo texture tell the user if we can't find it then quit
	LoadTexture("Art/Halo3.bmp", gCamera.m_HaloTexture);
	if(gCamera.m_HaloTexture == 0) {
		MessageBox(NULL, "Failed to load Halo texture.", "Error", MB_OK);
		return(FALSE);
	}
	
	// Try and load the Streaks texture tell the user if we can't find it then quit
	LoadTexture("Art/Streaks4.bmp", gCamera.m_StreakTexture);
	if(gCamera.m_StreakTexture == 0) {
		MessageBox(NULL, "Failed to load Streaks texture.", "Error", MB_OK);
		return(FALSE);
	}

//##################  NEW STUFF  ##################################

	// Just create a cylinder that will be used as occluder object
	cylList = glGenLists(1);
	qobj = gluNewQuadric();
	gluQuadricDrawStyle(qobj, GLU_FILL); 
	gluQuadricNormals(qobj, GLU_SMOOTH);
	glNewList(cylList, GL_COMPILE);
		glEnable(GL_COLOR_MATERIAL);
		glColor3f(0.0f, 0.0f, 1.0f);
		glEnable(GL_LIGHT0);
		glEnable(GL_LIGHTING);
		glTranslatef(0.0f,0.0f,-2.0f);
		gluCylinder(qobj, 0.5, 0.5, 4.0, 15, 5);
		glDisable(GL_LIGHTING);
		glDisable(GL_LIGHT0);
		glDisable(GL_COLOR_MATERIAL);
	glEndList();

	gStartTime = timeGetTime();										// Get the time the app started

	return TRUE;													// Initialization Went OK
}

int DrawGLScene(GLvoid)												// Here's Where We Do All The Drawing
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);				// Clear Screen And Depth Buffer
	glLoadIdentity();												// Reset The Current Modelview Matrix

	// We want our light source to be 50 units if front 
	// of the camera all the time to make it look like 
	// it is infinately far away from the camera. We only
	// do this to the z coordinate because we want to see
	// the flares adjust if we fly in a straight line.
	gCamera.m_LightSourcePos.z = gCamera.m_Position.z - 50.0f;

	//##################### NEW STUFF ##########################
	// Draw our cylinder and make it "do something"
	// Of course we do that BEFORE testing for occlusion
	// We need our depth buffer to be filled to check against occluder objects
	glPushMatrix();
		glLoadIdentity();
		glTranslatef(0.0f, 0.0f, -20.0f);
		glRotatef(timeGetTime() / 50.0f, 0.3f, 0.0f, 0.0f);
		glRotatef(timeGetTime() / 50.0f, 0.0f, 0.5f, 0.0f);
		glCallList(cylList);
	glPopMatrix();

	gCamera.SetPrespective();										// Set our perspective/oriention on the world
	gCamera.RenderLensFlare();										// Render the lens flare
	gCamera.UpdateFrustumFaster();									// Update the frustum as fast as possible.
	
	if(infoOn == TRUE) {											// Check to see if info has been toggled by 1,2
		DrawGLInfo();												// Info is on so draw the GL information.								
	}

	CheckKeys();													// Check to see if the user pressed any keys.

	return TRUE;
}

GLvoid KillGLWindow(GLvoid)											// Properly Kill The Window
{
	if (fullscreen)													// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);								// If So Switch Back To The Desktop
		ShowCursor(TRUE);											// Show Mouse Pointer
	}

	if (hRC)														// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))								// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))									// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;													// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))								// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;													// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))								// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;													// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))						// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;												// Set hInstance To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;									// Holds The Results After Searching For A Match
	WNDCLASS	wc;												// Windows Class Structure
	DWORD		dwExStyle;										// Window Extended Style
	DWORD		dwStyle;										// Window Style
	RECT		WindowRect;										// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;									// Set Left Value To 0
	WindowRect.right=(long)width;								// Set Right Value To Requested Width
	WindowRect.top=(long)0;										// Set Top Value To 0
	WindowRect.bottom=(long)height;								// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;									// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -