标签:
修改部分位于星号行列之间。
1 #include <windows.h> 2 #include <gl/glew.h> 3 #include <gl/glut.h> 4 5 /* 6 * Every OpenGL program is linked to a Rendering Context. 7 * A Rendering Context is what links OpenGL calls to the Device Context. 8 * In order for your program to draw to a Window you need to create a Device Context. 9 * The DC connects the Window to the GDI (Graphics Device Interface). 10 */ 11 12 HGLRC hRC = NULL; // Permanent rendering context 13 HDC hDC = NULL; // Private GDI device context 14 HWND hWnd = NULL; // Holds our window handle 15 HINSTANCE hInstance; // Holds the instance of the application 16 17 /* 18 * It‘s important to make this global so that each procedure knows if 19 * the program is running in fullscreen mode or not. 20 */ 21 22 bool keys[256]; // Array used for the keyboard routine 23 bool active = TRUE; // Window active flag set to TRUE by default 24 bool fullscreen = TRUE; // Fullscreen flag set to fullscreen mode by default 25 26 /* 27 * CreateGLWindow() has a reference to WndProc() but WndProc() comes after CreateGLWindow(). 28 */ 29 30 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration for WndProc 31 32 /* 33 * The job of the next section of code is to resize the OpenGL scene 34 * whenever the window (assuming you are using a Window rather than fullscreen mode) has been resized. 35 */ 36 37 GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize and initialize the GL window 38 { 39 if (height == 0) { // Prevent a divide by zero by 40 height = 1; // Making height equal one 41 } 42 43 glViewport(0, 0, width, height); // Reset the current viewport 44 45 /* 46 * The following lines set the screen up for a perspective view. 47 * Meaning things in the distance get smaller. This creates a realistic looking scene. 48 * The perspective is calculated with a 45 degree viewing angle based on 49 * the windows width and height. The 0.1f, 100.0f is the starting point and 50 * ending point for how deep we can draw into the screen. 51 * 52 * The projection matrix is responsible for adding perspective to our scene. 53 * glLoadIdentity() restores the selected matrix to it‘s original state. 54 * The modelview matrix is where our object information is stored. 55 * Lastly we reset the modelview matrix. 56 */ 57 58 glMatrixMode(GL_PROJECTION); // Select the projection matrix 59 glLoadIdentity(); // Reset the projection matrix 60 61 // Calculate the aspect ratio of the window 62 gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f); 63 64 glMatrixMode(GL_MODELVIEW); // Seclet the modelview matrix 65 glLoadIdentity(); // Reset the modelview matrix 66 } 67 68 int InitGL(GLvoid) // All setup for OpenGL goes here 69 { 70 /* 71 * Smooth shading blends colors nicely across a polygon, and smoothes out lighting. 72 */ 73 74 glShadeModel(GL_SMOOTH); // Enables smooth shading 75 76 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black background 77 78 /* 79 * Think of the depth buffer as layers into the screen. 80 * The depth buffer keeps track of how deep objects are into the screen. 81 */ 82 83 glClearDepth(1.0f); // Depth buffer setup 84 glEnable(GL_DEPTH_TEST); // Enable depth testing 85 glDepthFunc(GL_LEQUAL); // The typr of depth test to do 86 87 /* 88 * Next we tell OpenGL we want the best perspective correction to be done. 89 * This causes a very tiny performance hit, but makes the perspective view look a bit better. 90 */ 91 92 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really nice perspective calculations 93 94 return TRUE; 95 } 96 97 /* 98 * For now all we will do is clear the screen to the color we previously decided on, 99 * clear the depth buffer and reset the scene. We wont draw anything yet. 100 */ 101 /******************************************************************************************************************************************/ 102 /******************************************************************************************************************************************/ 103 int DrawGLScene(GLvoid) // Here‘s where we do all the drawing 104 { 105 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen and the depth buffer 106 glLoadIdentity(); // Reset the current modelview matrix 107 108 /* 109 * When you do a glLoadIdentity() what you are doing is moving back to 110 * the center of the screen with the X axis(轴) running left to right, 111 * the Y axis moving up and down, and the Z axis moving into, and out of the screen. 112 */ 113 /* 114 * glTranslatef(x, y, z) moves along the X, Y and Z axis, in that order. 115 * When you translate, you are not moving a set amount(数量) from the center of the screen, 116 * you are moving a set amount from wherever you currently were on the screen. 117 */ 118 glTranslatef(-1.5f, 0.0f, -6.0f); // Move left 1.5 units and into the screen 6.0 119 glBegin(GL_TRIANGLES); // Drawing using traingles 120 glColor3f(1.0, 0.0, 0.0); // Set the color to red 121 glVertex3f(0.0f, 1.0f, 0.0f); // Top 122 glColor3f(0.0, 1.0, 0.0); // Set the color to green 123 glVertex3f(-1.0f, -1.0f, 0.0f); // Bottom left 124 glColor3f(0.0, 0.0, 1.0); // Set the color to blue 125 glVertex3f(1.0f, -1.0f, 0.0f); // Bottom right 126 glEnd(); // Finished drawing the traingles 127 128 glTranslatef(3.0f, 0.0f, 0.0f); // Move left 3 units 129 130 /* 131 * By drawing in a clockwise order, the square will be drawn as a back face. 132 * Meaning the side of the quad we see is actually the back. 133 * Objects drawn in a counter clockwise order will be facing us. 134 */ 135 136 glBegin(GL_QUADS); // Draw a quad 137 glColor3f(0.75, 0.0, 0.0); 138 glVertex3f(-1.0f, 1.0f, 0.0f); // Top left 139 glColor3f(1.0, 0.5, 0.0); 140 glVertex3f(1.0f, 1.0f, 0.0f); // Top right 141 glColor3f(1.0, 1.0, 0.25); 142 glVertex3f(1.0f, -1.0f, 0.0f); // Bottom right 143 glColor3f(1.0, 0.0, 1.0); 144 glVertex3f(-1.0f, -1.0f, 0.0f); // Bottom left 145 glEnd(); // Done drawing the quad 146 return TRUE; // everthing went OK 147 } 148 /******************************************************************************************************************************************/ 149 /******************************************************************************************************************************************/ 150 /* 151 * The job of KillGLWindow() is to release the Rendering Context, 152 * the Device Context and finally the Window Handle. 153 */ 154 155 GLvoid KillGLWindow(GLvoid) // Properly kill the window 156 { 157 if (fullscreen) { // Are we in fullscreen mode 158 159 /* 160 * We use ChangeDisplaySettings(NULL,0) to return us to our original desktop. 161 * After we‘ve switched back to the desktop we make the cursor visible again. 162 */ 163 164 ChangeDisplaySettings(NULL, 0); // if so switch back to the desktop 165 ShowCursor(TRUE); // Show mouse pointer 166 } 167 168 if (hRC) { // Do we have a rendering context 169 if (!wglMakeCurrent(NULL, NULL)) { // Are we able to release the DC and RC contexts 170 MessageBox(NULL, "Release of DC and RC failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); 171 } 172 173 if (!wglDeleteContext(hRC)) { // Are we able to delete the RC 174 MessageBox(NULL, "Release rendering context failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); 175 hRC = NULL; // Set RC to NULL 176 } 177 178 if (hDC && !ReleaseDC(hWnd, hDC)) { // Are we able to release the DC 179 MessageBox(NULL, "Release device context failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); 180 hDC = NULL; // Set DC to NULL 181 } 182 if (hWnd && !DestroyWindow(hWnd)) { // Are we able to destroy the window 183 MessageBox(NULL, "Could not release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); 184 hWnd = NULL; // Set hWnd to NULL 185 } 186 187 if (!UnregisterClass("OpenGL", hInstance)) { // Are we able to unregister class 188 MessageBox(NULL, "Could not register class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); 189 hInstance = NULL; // Set hInstance to NULL 190 } 191 } 192 } 193 194 /* 195 * The next section of code creates our OpenGL Window. 196 */ 197 198 BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) 199 { 200 /* 201 * Find a pixel format that matches the one we want 202 */ 203 GLuint PixelFormat; // Holds the result after serching for a match 204 205 /* 206 * Before you create a window, you MUST register a Class for the window 207 */ 208 WNDCLASS wc; // Windows class structure 209 210 /* 211 * dwExStyle and dwStyle will store the Extended and normal Window Style Information. 212 */ 213 DWORD dwExStyle; // Window extend style 214 DWORD dwStyle; // Window style 215 216 RECT WindowRect; // Grabs rectangle upper left/lower right values 217 WindowRect.left = (long)0; // Set left value to 0 218 WindowRect.right = (long)width; // Set right value to requested width 219 WindowRect.top = (long)0; // Set top value to 0 220 WindowRect.bottom = (long)height; // Set bottom value to requested height 221 222 fullscreen = fullscreenflag; // Set the global fullscreen flag 223 224 /* 225 * The style CS_HREDRAW and CS_VREDRAW force the Window to redraw whenever it is resized. 226 * CS_OWNDC creates a private DC for the Window. Meaning the DC is not shared across applications. 227 * WndProc is the procedure that watches for messages in our program. 228 * No extra Window data is used so we zero the two fields. Then we set the instance. 229 * Next we set hIcon to NULL meaning we don‘t want an ICON in the Window, 230 * and for a mouse pointer we use the standard arrow. The background color doesn‘t matter 231 * (we set that in GL). We don‘t want a menu in this Window so we set it to NULL, 232 * and the class name can be any name you want. I‘ll use "OpenGL" for simplicity. 233 */ 234 hInstance = GetModuleHandle(NULL); // Grab an instance for our window 235 wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw on move, and own DC for window 236 wc.lpfnWndProc = (WNDPROC)WndProc; // WndProc handles message 237 wc.cbClsExtra = 0; // No extra window date 238 wc.cbWndExtra = 0; // No extra window date 239 wc.hInstance = hInstance; // set the instance 240 wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load the default icon 241 wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load the arrow pointer 242 wc.hbrBackground = NULL; // No background requried for GL 243 wc.lpszMenuName = NULL; // We don‘t want a menu 244 wc.lpszClassName = "OpenGL"; // set the class name 245 246 if (!RegisterClass(&wc)) { // Attempt to register the window class 247 MessageBox(NULL, "Failed to register the window class.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 248 return FALSE; // Exit and return false 249 } 250 251 if (fullscreen) { // attempt fullsreen model 252 253 /* 254 T* here are a few very important things you should keep in mind when switching to full screen mode. 255 * Make sure the width and height that you use in fullscreen mode is the same as 256 * the width and height you plan to use for your window, and most importantly, 257 * set fullscreen mode BEFORE you create your window. 258 */ 259 DEVMODE dmScreenSettings; // Device mode 260 memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Make sure memory‘s cleared 261 dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size of devmode structure 262 dmScreenSettings.dmPelsWidth = width; // Select window width 263 dmScreenSettings.dmPelsHeight = height; // Select window height 264 dmScreenSettings.dmBitsPerPel = bits; // Select bits per pixel 265 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; 266 267 /* 268 * In the line below ChangeDisplaySettings tries to switch to a mode that matches 269 * what we stored in dmScreenSettings. I use the parameter CDS_FULLSCREEN when switching modes, 270 * because it‘s supposed to remove the start bar at the bottom of the screen, 271 * plus it doesn‘t move or resize the windows on your desktop when you switch to 272 * fullscreen mode and back. 273 */ 274 //Try to set selected mode and get results. Note: CDS_FULLSCREEN gets rid of start bar 275 if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { 276 //If the mode fails, offer two options. Quit or run in a window 277 if (MessageBox(NULL, "The requested fullscreen mode is not supported by\n your video card. Use" 278 "windowed mode instead?", "GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) 279 { 280 fullscreen = FALSE; // Select windowed mode (fullscreen=FLASE) 281 } 282 else { 283 // Pop up a message box letting user know the programe is closing. 284 MessageBox(NULL, "Program will now close.", "ERROR", MB_OK | MB_ICONSTOP); 285 return FALSE; // Exit and return FALSE 286 } 287 } 288 } 289 290 if (fullscreen) { // Are we still in fullscreen mode 291 292 /* 293 * If we are still in fullscreen mode we‘ll set the extended style to WS_EX_APPWINDOW, 294 * which force a top level window down to the taskbar once our window is visible. 295 * For the window style we‘ll create a WS_POPUP window. 296 * This type of window has no border around it, making it perfect for fullscreen mode. 297 298 * Finally, we disable the mouse pointer. If your program is not interactive, 299 * it‘s usually nice to disable the mouse pointer when in fullscreen mode. It‘s up to you though. 300 */ 301 dwExStyle = WS_EX_APPWINDOW; // Window extended style 302 dwStyle = WS_POPUP; // Window style 303 ShowCursor(FALSE); // Hide mosue pointer 304 } 305 else { 306 307 /* 308 * If we‘re using a window instead of fullscreen mode, 309 * we‘ll add WS_EX_WINDOWEDGE to the extended style. This gives the window a more 3D look. 310 * For style we‘ll use WS_OVERLAPPEDWINDOW instead of WS_POPUP. 311 * WS_OVERLAPPEDWINDOW creates a window with a title bar, sizing border, 312 * window menu, and minimize / maximize buttons. 313 */ 314 dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window extended style 315 dwStyle = WS_OVERLAPPEDWINDOW; // Window style 316 } 317 318 /* 319 * By using the AdjustWindowRectEx command none of our OpenGL scene will be covered up by the borders, 320 * instead, the window will be made larger to account for the pixels needed to draw the window border. 321 * In fullscreen mode, this command has no effect. 322 */ 323 AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust window to true resqusted 324 325 /* 326 * WS_CLIPSIBLINGS and WS_CLIPCHILDREN are both REQUIRED for OpenGL to work properly. 327 * These styles prevent other windows from drawing over or into our OpenGL Window. 328 */ 329 if (!(hWnd = CreateWindowEx(dwExStyle, // Extended style for the window 330 "OpenGL", // Class name 331 title, // Window title 332 WS_CLIPSIBLINGS | // Requried window style 333 WS_CLIPCHILDREN | // Requried window style 334 dwStyle, // Select window style 335 0, 0, // Window position 336 WindowRect.right - WindowRect.left, // Calculate adjusted window width 337 WindowRect.bottom - WindowRect.top, // Calculate adjusted window height 338 NULL, // No parent window 339 NULL, // No menu 340 hInstance, // Instance 341 NULL))) // Don‘t pass anything to WM_CREATE 342 { 343 KillGLWindow(); //Reset the display 344 MessageBox(NULL, "Window creation error.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 345 return FALSE; // Retrurn FALSE; 346 } 347 348 /* 349 * aside from the stencil buffer and the (slow) accumulation buffer 350 */ 351 static PIXELFORMATDESCRIPTOR pfd = // pfd tells windows how we want things to be 352 { 353 sizeof(PIXELFORMATDESCRIPTOR), // Size of this pixel format descriptor 354 1, // Version number 355 PFD_DRAW_TO_WINDOW | // Format must support window 356 PFD_SUPPORT_OPENGL | // Format must support OpenGL 357 PFD_DOUBLEBUFFER, // Must support double buffer 358 PFD_TYPE_RGBA, // Request an RGBA format 359 bits, // Select our color depth 360 0, 0, 0, 0, 0, 0, // Color bits ignored 361 0, // No alpha buffer 362 0, // shift bit ignored 363 0, // No accumulation buffer 364 0, 0, 0, 0, // Accumulation bits ignored 365 16, // 16Bits Z_Buffer (depth buffer) 366 0, // No stencil buffer 367 0, // No auxiliary buffer 368 PFD_MAIN_PLANE, // Main drawing layer 369 0, // Reserved 370 0, 0, 0 // Layer makes ignored 371 }; 372 373 if (!(hDC = GetDC(hWnd))) { // Did we get a device context 374 KillGLWindow(); // Reset the display 375 MessageBox(NULL, "Can‘t create a GL device context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 376 return FALSE; // Return FALSE 377 } 378 379 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { // Did window find a matching pixel format 380 KillGLWindow(); // Reset the display 381 MessageBox(NULL, "Can‘t find a suitable pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 382 return FALSE; // Return FALSE; 383 } 384 385 if (!SetPixelFormat(hDC, PixelFormat, &pfd)) { // Are we able to set the pixel format 386 KillGLWindow(); // Reset the display 387 MessageBox(NULL, "Can‘t set the pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 388 return FALSE; // Return FALSE; 389 } 390 391 if (!(hRC = wglCreateContext(hDC))) { // Are we able to rendering context 392 KillGLWindow(); // Reset the display 393 MessageBox(NULL, "Can‘t create a GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 394 return FALSE; // Return FASLE; 395 } 396 397 if (!wglMakeCurrent(hDC, hRC)) { // Try to activate the rendering context 398 KillGLWindow(); // Reset the display 399 MessageBox(NULL, "Can‘t activate the GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 400 return FALSE; // Return FALSE 401 } 402 403 /* 404 * ReSizeGLScene passing the screen width and height to set up our perspective OpenGL screen. 405 */ 406 ShowWindow(hWnd, SW_SHOW); // Show the window 407 SetForegroundWindow(hWnd); // slightly higher priority 408 SetFocus(hWnd); // Sets keyboard focus to the window 409 ReSizeGLScene(width, height); // Set up our perspective GL screen 410 411 /* 412 * we can set up lighting, textures, and anything else that needs to be setup in InitGL(). 413 */ 414 if (!InitGL()) { // Initialize our newly created GL window 415 KillGLWindow(); // Reset the display 416 MessageBox(NULL, "Initialize Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION); 417 return FALSE; // Return FALSE 418 } 419 return TRUE; 420 } 421 422 LRESULT CALLBACK WndProc(HWND hWnd, // Handle for this window 423 UINT uMsg, // Message for this window 424 WPARAM wParam, // Additional message information 425 LPARAM lParam) // Additional message information 426 { 427 switch (uMsg) { // Check for window message 428 case WM_ACTIVATE: { // Check minimization state 429 if (!HIWORD(wParam)) { 430 active = TRUE; // Program is active 431 } 432 else { 433 active = FALSE; // Program is no longer active 434 } 435 return 0; // Return to the message loop 436 } 437 case WM_SYSCOMMAND: { // Intercept system commands 438 switch (wParam) { // Check system calls 439 case SC_SCREENSAVE: // Screensaver trying to start 440 case SC_MONITORPOWER: // Monitor trying to enter powersave 441 return 0; // Prevent form happening 442 } 443 break; // Exit 444 } 445 case WM_CLOSE: { // Did we receive a close message 446 PostQuitMessage(0); // Send a quit message 447 return 0; 448 } 449 case WM_KEYDOWN: { // Is a key being held down 450 keys[wParam] = TRUE; // if so, mark it as TRUE 451 return 0; // Jump back 452 } 453 case WM_KEYUP: { // Has a key been released 454 keys[wParam] = FALSE; // if so, mark it as FALSE 455 return 0; // Jump back 456 } 457 case WM_SIZE: { // Resize the OpenGL window 458 ReSizeGLScene(LOWORD(lParam), HIWORD(lParam)); // LoWord = width HiWord = height 459 return 0; // Jump back 460 } 461 } 462 return DefWindowProc(hWnd, uMsg, wParam, lParam); // Pass all unhandled message to DefWindwProc 463 } 464 465 int WINAPI WinMain(HINSTANCE hInstance, // Instance 466 HINSTANCE hPrevInstance, // Previous instance 467 LPSTR lpCmdLine, // Command line parameters 468 int nCmdShow) // Window show state 469 { 470 MSG msg; // Window message structure 471 BOOL done = FALSE; // Bool variable to exit loop 472 // Ask the user which screen mode they prefer 473 if (MessageBox(NULL, "Would you like to run in fullscreen mode?", 474 "Start fullscreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) 475 { 476 fullscreen = FALSE; // Window mode 477 } 478 // Create our OpenGL window 479 if (!CreateGLWindow("Adding Color", 640, 480, 16, fullscreen)) { // (Modified) 480 return 0; // Quit if window was not create 481 } 482 483 while (!done) { // Loop that runs until donw = TRUE 484 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // Is there a message wating 485 if (msg.message == WM_QUIT) { // Havw we received a quit message 486 done = TRUE; // if so done = TRUE 487 } 488 else { // If not, deal with window message 489 TranslateMessage(&msg); // Translate message 490 DispatchMessage(&msg); // Dispatch message 491 } 492 } 493 else { 494 // Draw the scene. Watch for ESC key and quit message from DrawGLScene() 495 if (active) { // Program active 496 if (keys[VK_ESCAPE]) { // Was ESC pressed 497 done = TRUE; // ESC signalled a quit 498 } 499 else { // Not time to quit, update screen 500 DrawGLScene(); // Draw scene 501 SwapBuffers(hDC); // Swap buffers (double buffering) 502 } 503 } 504 505 /* 506 * It allows us to press the F1 key to switch from fullscreen mode to 507 * windowed mode or windowed mode to fullscreen mode. 508 */ 509 if (keys[VK_F1]) { // Is F1 being pressed 510 keys[VK_F1] = FALSE; // If so make key FASLE 511 KillGLWindow(); // Kill our current window 512 fullscreen = !fullscreen; // Toggle fullscreen / window mode 513 //Recreate our OpenGL window(modified) 514 if (!CreateGLWindow("Adding Color", 640, 480, 16, fullscreen)) { 515 return 0; // Quit if window was not create 516 } 517 } 518 } 519 } 520 // Shutdown 521 KillGLWindow(); // Kill the window 522 return (msg.wParam); // Exit the program 523 }
Thanks for Nehe‘s tutorials, this is his home.
标签:
原文地址:http://www.cnblogs.com/clairvoyant/p/5568008.html