OpenGL(Win32 窗体应用程序框架)

VS2008为例,下面是“核心步骤”截图:

Step 1:

Step 2:

Step 3:

将“Lesson01.cpp”加到当前工程中,Lesson01.cpp内容如下:

1
2  /*
3 * This Code Was Created By Jeff Molofee 2000
4 * A HUGE Thanks To Fredric Echols For Cleaning Up
5 * And Optimizing This Code, Making It More Flexible!
6 * If You've Found This Code Useful, Please Let Me Know.
7 * Visit My Site At nehe.gamedev.net
8 */
9
10 #include <windows.h> // Header File For Windows
11  #include <gl\gl.h> // Header File For The OpenGL32 Library
12  #include <gl\glu.h> // Header File For The GLu32 Library
13  #include <gl\glaux.h> // Header File For The Glaux Library
14  
15  #pragma comment( lib, "opengl32.lib" )
16  #pragma comment( lib, "glu32.lib" )
17  #pragma comment( lib, "glaux.lib" )
18
19 HDC hDC=NULL; // Private GDI Device Context
20  HGLRC hRC=NULL; // Permanent Rendering Context
21  HWND hWnd=NULL; // Holds Our Window Handle
22  HINSTANCE hInstance; // Holds The Instance Of The Application
23  
24  bool keys[256]; // Array Used For The Keyboard Routine
25  bool active=TRUE; // Window Active Flag Set To TRUE By Default
26  bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
27  
28 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
29  
30 GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
31  {
32 if (height==0) // Prevent A Divide By Zero By
33   {
34 height=1; // Making Height Equal One
35   }
36
37 glViewport(0,0,width,height); // Reset The Current Viewport
38  
39 glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
40   glLoadIdentity(); // Reset The Projection Matrix
41
42 // Calculate The Aspect Ratio Of The Window
43   gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
44
45 glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
46   glLoadIdentity(); // Reset The Modelview Matrix
47 }
48
49 int InitGL(GLvoid) // All Setup For OpenGL Goes Here
50 {
51 glShadeModel(GL_SMOOTH); // Enable Smooth Shading
52 glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
53 glClearDepth(1.0f); // Depth Buffer Setup
54 glEnable(GL_DEPTH_TEST); // Enables Depth Testing
55 glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
56 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
57 return TRUE; // Initialization Went OK
58 }
59
60 int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
61 {
62 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
63 glLoadIdentity(); // Reset The Current Modelview Matrix
64 return TRUE; // Everything Went OK
65 }
66
67 GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
68 {
69 if (fullscreen) // Are We In Fullscreen Mode?
70 {
71 ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
72 ShowCursor(TRUE); // Show Mouse Pointer
73 }
74
75 if (hRC) // Do We Have A Rendering Context?
76 {
77 if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
78 {
79 MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
80 }
81
82 if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
83 {
84 MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
85 }
86 hRC=NULL; // Set RC To NULL
87 }
88
89 if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
90 {
91 MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
92 hDC=NULL; // Set DC To NULL
93 }
94
95 if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
96 {
97 MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
98 hWnd=NULL; // Set hWnd To NULL
99 }
100
101 if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
102 {
103 MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
104 hInstance=NULL; // Set hInstance To NULL
105 }
106 }
107
108 /* This Code Creates Our OpenGL Window. Parameters Are: *
109 * title - Title To Appear At The Top Of The Window *
110 * width - Width Of The GL Window Or Fullscreen Mode *
111 * height - Height Of The GL Window Or Fullscreen Mode *
112 * bits - Number Of Bits To Use For Color (8/16/24/32) *
113 * fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
114
115 BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
116 {
117 GLuint PixelFormat; // Holds The Results After Searching For A Match
118 WNDCLASS wc; // Windows Class Structure
119 DWORD dwExStyle; // Window Extended Style
120 DWORD dwStyle; // Window Style
121 RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
122 WindowRect.left=(long)0; // Set Left Value To 0
123 WindowRect.right=(long)width; // Set Right Value To Requested Width
124 WindowRect.top=(long)0; // Set Top Value To 0
125 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height
126
127 fullscreen=fullscreenflag; // Set The Global Fullscreen Flag
128
129 hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
130 wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
131 wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
132 wc.cbClsExtra = 0; // No Extra Window Data
133 wc.cbWndExtra = 0; // No Extra Window Data
134 wc.hInstance = hInstance; // Set The Instance
135 wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
136 wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
137 wc.hbrBackground = NULL; // No Background Required For GL
138 wc.lpszMenuName = NULL; // We Don't Want A Menu
139 wc.lpszClassName = "OpenGL"; // Set The Class Name
140
141 if (!RegisterClass(&wc)) // Attempt To Register The Window Class
142 {
143 MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
144 return FALSE; // Return FALSE
145 }
146
147 if (fullscreen) // Attempt Fullscreen Mode?
148 {
149 DEVMODE dmScreenSettings; // Device Mode
150 memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
151 dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
152 dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
153 dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
154 dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
155 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
156
157 // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
158 if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
159 {
160 // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
161 if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card.\
          Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
162 {
163 fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
164 }
165 else
166 {
167 // Pop Up A Message Box Letting User Know The Program Is Closing.
168 MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
169 return FALSE; // Return FALSE
170 }
171 }
172 }
173
174 if (fullscreen) // Are We Still In Fullscreen Mode?
175 {
176 dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
177 dwStyle=WS_POPUP; // Windows Style
178 ShowCursor(FALSE); // Hide Mouse Pointer
179 }
180 else
181 {
182 dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
183 dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
184 }
185
186 AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
187
188 // Create The Window
189 if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
190 "OpenGL", // Class Name
191 title, // Window Title
192 dwStyle | // Defined Window Style
193 WS_CLIPSIBLINGS | // Required Window Style
194 WS_CLIPCHILDREN, // Required Window Style
195 0, 0, // Window Position
196 WindowRect.right-WindowRect.left, // Calculate Window Width
197 WindowRect.bottom-WindowRect.top, // Calculate Window Height
198 NULL, // No Parent Window
199 NULL, // No Menu
200 hInstance, // Instance
201 NULL))) // Dont Pass Anything To WM_CREATE
202 {
203 KillGLWindow(); // Reset The Display
204 MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
205 return FALSE; // Return FALSE
206 }
207
208 static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
209 {
210 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
211 1, // Version Number
212 PFD_DRAW_TO_WINDOW | // Format Must Support Window
213 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
214 PFD_DOUBLEBUFFER, // Must Support Double Buffering
215 PFD_TYPE_RGBA, // Request An RGBA Format
216 bits, // Select Our Color Depth
217 0, 0, 0, 0, 0, 0, // Color Bits Ignored
218 0, // No Alpha Buffer
219 0, // Shift Bit Ignored
220 0, // No Accumulation Buffer
221 0, 0, 0, 0, // Accumulation Bits Ignored
222 16, // 16Bit Z-Buffer (Depth Buffer)
223 0, // No Stencil Buffer
224 0, // No Auxiliary Buffer
225 PFD_MAIN_PLANE, // Main Drawing Layer
226 0, // Reserved
227 0, 0, 0 // Layer Masks Ignored
228 };
229
230 if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
231 {
232 KillGLWindow(); // Reset The Display
233 MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
234 return FALSE; // Return FALSE
235 }
236
237 if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
238 {
239 KillGLWindow(); // Reset The Display
240 MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
241 return FALSE; // Return FALSE
242 }
243
244 if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
245 {
246 KillGLWindow(); // Reset The Display
247 MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
248 return FALSE; // Return FALSE
249 }
250
251 if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
252 {
253 KillGLWindow(); // Reset The Display
254 MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
255 return FALSE; // Return FALSE
256 }
257
258 if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
259 {
260 KillGLWindow(); // Reset The Display
261 MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
262 return FALSE; // Return FALSE
263 }
264
265 ShowWindow(hWnd,SW_SHOW); // Show The Window
266 SetForegroundWindow(hWnd); // Slightly Higher Priority
267 SetFocus(hWnd); // Sets Keyboard Focus To The Window
268 ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
269
270 if (!InitGL()) // Initialize Our Newly Created GL Window
271 {
272 KillGLWindow(); // Reset The Display
273 MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
274 return FALSE; // Return FALSE
275 }
276
277 return TRUE; // Success
278 }
279
280 LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
281 UINT uMsg, // Message For This Window
282 WPARAM wParam, // Additional Message Information
283 LPARAM lParam) // Additional Message Information
284 {
285 switch (uMsg) // Check For Windows Messages
286 {
287 case WM_ACTIVATE: // Watch For Window Activate Message
288 {
289 if (!HIWORD(wParam)) // Check Minimization State
290 {
291 active=TRUE; // Program Is Active
292 }
293 else
294 {
295 active=FALSE; // Program Is No Longer Active
296 }
297
298 return 0; // Return To The Message Loop
299 }
300
301 case WM_SYSCOMMAND: // Intercept System Commands
302 {
303 switch (wParam) // Check System Calls
304 {
305 case SC_SCREENSAVE: // Screensaver Trying To Start?
306 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
307 return 0; // Prevent From Happening
308 }
309 break; // Exit
310 }
311
312 case WM_CLOSE: // Did We Receive A Close Message?
313 {
314 PostQuitMessage(0); // Send A Quit Message
315 return 0; // Jump Back
316 }
317
318 case WM_KEYDOWN: // Is A Key Being Held Down?
319 {
320 keys[wParam] = TRUE; // If So, Mark It As TRUE
321 return 0; // Jump Back
322 }
323
324 case WM_KEYUP: // Has A Key Been Released?
325 {
326 keys[wParam] = FALSE; // If So, Mark It As FALSE
327 return 0; // Jump Back
328 }
329
330 case WM_SIZE: // Resize The OpenGL Window
331 {
332 ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
333 return 0; // Jump Back
334 }
335 }
336
337 // Pass All Unhandled Messages To DefWindowProc
338 return DefWindowProc(hWnd,uMsg,wParam,lParam);
339 }
340
341 int WINAPI WinMain( HINSTANCE hInstance, // Instance
342 HINSTANCE hPrevInstance, // Previous Instance
343 LPSTR lpCmdLine, // Command Line Parameters
344 int nCmdShow) // Window Show State
345 {
346 MSG msg; // Windows Message Structure
347 BOOL done=FALSE; // Bool Variable To Exit Loop
348
349 // Ask The User Which Screen Mode They Prefer
350 if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",
      MB_YESNO|MB_ICONQUESTION)==IDNO)
351 {
352 fullscreen=FALSE; // Windowed Mode
353 }
354
355 // Create Our OpenGL Window
356 if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
357 {
358 return 0; // Quit If Window Was Not Created
359 }
360
361 while(!done) // Loop That Runs While done=FALSE
362 {
363 if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
364 {
365 if (msg.message==WM_QUIT) // Have We Received A Quit Message?
366 {
367 done=TRUE; // If So done=TRUE
368 }
369 else // If Not, Deal With Window Messages
370 {
371 TranslateMessage(&msg); // Translate The Message
372 DispatchMessage(&msg); // Dispatch The Message
373 }
374 }
375 else // If There Are No Messages
376 {
377 // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
378 if (active) // Program Active?
379 {
380 if (keys[VK_ESCAPE]) // Was ESC Pressed?
381 {
382 done=TRUE; // ESC Signalled A Quit
383 }
384 else // Not Time To Quit, Update Screen
385 {
386 DrawGLScene(); // Draw The Scene
387 SwapBuffers(hDC); // Swap Buffers (Double Buffering)
388 }
389 }
390
391 if (keys[VK_F1]) // Is F1 Being Pressed?
392 {
393 keys[VK_F1]=FALSE; // If So Make Key FALSE
394 KillGLWindow(); // Kill Our Current Window
395 fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
396 // Recreate Our OpenGL Window
397 if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
398 {
399 return 0; // Quit If Window Was Not Created
400 }
401 }
402 }
403 }
404
405 // Shutdown
406 KillGLWindow(); // Kill The Window
407 return (msg.wParam); // Exit The Program
408 }
409

Step 4:

设置字符集为“No Set

运行结果:

原文地址:https://www.cnblogs.com/kekec/p/1789058.html