Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: Seyro97 en 27 Septiembre 2014, 00:56 am



Título: Comprensión del OpenGL + Win32
Publicado por: Seyro97 en 27 Septiembre 2014, 00:56 am
Comprensión del OpenGL + API Win32

Hola a tod@s! Soy nuevo en este foro. Soy un chico al que le gusta mucho programar,  y ahora le gustaría más que nada saber como programar con gráficos! Mi duda o petición es ver si me podéis explicar el Hello World del OpenGL + API Win32.

La situación es que yo se la estructura básica de una aplicación Win32, y tambien los fundamentos del OpenGL, pero no se como unir las dos cosas.

Este es el Hello World:

Código
  1. #include <windows.h>
  2. #include <gl/gl.h>
  3.  
  4. LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
  5. void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);
  6. void DisableOpenGL(HWND, HDC, HGLRC);
  7.  
  8.  
  9. int WINAPI WinMain(HINSTANCE hInstance,
  10.                    HINSTANCE hPrevInstance,
  11.                    LPSTR lpCmdLine,
  12.                    int nCmdShow)
  13. {
  14.    WNDCLASSEX wcex;
  15.    HWND hwnd;
  16.    HDC hDC;
  17.    HGLRC hRC;
  18.    MSG msg;
  19.    BOOL bQuit = FALSE;
  20.    float theta = 0.0f;
  21.  
  22.    /* register window class */
  23.    wcex.cbSize = sizeof(WNDCLASSEX);
  24.    wcex.style = CS_OWNDC;
  25.    wcex.lpfnWndProc = WindowProc;
  26.    wcex.cbClsExtra = 0;
  27.    wcex.cbWndExtra = 0;
  28.    wcex.hInstance = hInstance;
  29.    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  30.    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
  31.    wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
  32.    wcex.lpszMenuName = NULL;
  33.    wcex.lpszClassName = "GLSample";
  34.    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);;
  35.  
  36.  
  37.    if (!RegisterClassEx(&wcex))
  38.        return 0;
  39.  
  40.    /* create main window */
  41.    hwnd = CreateWindowEx(0,
  42.                            "GLSample",
  43.                            "OpenGL Sample",
  44.                            WS_OVERLAPPEDWINDOW,
  45.                            CW_USEDEFAULT,
  46.                            CW_USEDEFAULT,
  47.                            256,
  48.                            256,
  49.                            NULL,
  50.                            NULL,
  51.                            hInstance,
  52.                            NULL);
  53.  
  54.    ShowWindow(hwnd, nCmdShow);
  55.  
  56.    /* enable OpenGL for the window */
  57.    EnableOpenGL(hwnd, &hDC, &hRC);
  58.  
  59.    /* program main loop */
  60.    while (!bQuit)
  61.    {
  62.        /* check for messages */
  63.        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
  64.        {
  65.            /* handle or dispatch messages */
  66.            if (msg.message == WM_QUIT)
  67.            {
  68.                bQuit = TRUE;
  69.            }
  70.            else
  71.            {
  72.                TranslateMessage(&msg);
  73.                DispatchMessage(&msg);
  74.            }
  75.        }
  76.        else
  77.        {
  78.            /* OpenGL animation code goes here */
  79.  
  80.            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  81.            glClear(GL_COLOR_BUFFER_BIT);
  82.  
  83.            glPushMatrix();
  84.            glRotatef(theta, 0.0f, 0.0f, 1.0f);
  85.  
  86.            glBegin(GL_TRIANGLES);
  87.  
  88.                glColor3f(1.0f, 0.0f, 0.0f);    glVertex2f(0.0f, 1.0f);
  89.                glColor3f(0.0f, 1.0f, 0.0f);    glVertex2f(0.87f, -0.5f);
  90.                glColor3f(0.0f, 0.0f, 1.0f);    glVertex2f(-0.87f, -0.5f);
  91.  
  92.            glEnd();
  93.  
  94.            glPopMatrix();
  95.  
  96.            SwapBuffers(hDC);
  97.  
  98.            theta += 1.0f;
  99.            Sleep (1);
  100.        }
  101.    }
  102.  
  103.    /* shutdown OpenGL */
  104.    DisableOpenGL(hwnd, hDC, hRC);
  105.  
  106.    /* destroy the window explicitly */
  107.    DestroyWindow(hwnd);
  108.  
  109.    return msg.wParam;
  110. }
  111.  
  112. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
  113. {
  114.    switch (uMsg)
  115.    {
  116.        case WM_CLOSE:
  117.            PostQuitMessage(0);
  118.        break;
  119.  
  120.        case WM_DESTROY:
  121.            return 0;
  122.  
  123.        case WM_KEYDOWN:
  124.        {
  125.            switch (wParam)
  126.            {
  127.                case VK_ESCAPE:
  128.                    PostQuitMessage(0);
  129.                    break;
  130.            }
  131.        }
  132.        break;
  133.  
  134.        default:
  135.            return DefWindowProc(hwnd, uMsg, wParam, lParam);
  136.    }
  137.  
  138.    return 0;
  139. }
  140.  
  141. void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
  142. {
  143.    PIXELFORMATDESCRIPTOR pfd;
  144.  
  145.    int iFormat;
  146.  
  147.    /* get the device context (DC) */
  148.    *hDC = GetDC(hwnd);
  149.  
  150.    /* set the pixel format for the DC */
  151.    ZeroMemory(&pfd, sizeof(pfd));
  152.  
  153.    pfd.nSize = sizeof(pfd);
  154.    pfd.nVersion = 1;
  155.    pfd.dwFlags = PFD_DRAW_TO_WINDOW |
  156.                    PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  157.    pfd.iPixelType = PFD_TYPE_RGBA;
  158.    pfd.cColorBits = 24;
  159.    pfd.cDepthBits = 16;
  160.    pfd.iLayerType = PFD_MAIN_PLANE;
  161.  
  162.    iFormat = ChoosePixelFormat(*hDC, &pfd);
  163.  
  164.    SetPixelFormat(*hDC, iFormat, &pfd);
  165.  
  166.    /* create and enable the render context (RC) */
  167.    *hRC = wglCreateContext(*hDC);
  168.  
  169.    wglMakeCurrent(*hDC, *hRC);
  170. }
  171.  
  172. void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)
  173. {
  174.    wglMakeCurrent(NULL, NULL);
  175.    wglDeleteContext(hRC);
  176.    ReleaseDC(hwnd, hDC);
  177. }
  178.  
Lo que no entiendo es: Las funciones Enable y disable OpenGL, las estructuras HDC y HRC. Espero que me puedan ayudar! Si no sabéis todo, o no queréis explicar mucho, por favor, explicarme cualquier cosa que sepáis, y así yo podré aprender mucho más!

MUCHAS GRACIAS, ESPERO PODER AYUDAR Y SER AYUDADO TODO LO QUE PUEDA :D


Título: Re: Comprensión del OpenGL + Win32
Publicado por: BloodSharp en 27 Septiembre 2014, 05:08 am
Lo que no entiendo es: Las funciones Enable y disable OpenGL, las estructuras HDC y HRC. Espero que me puedan ayudar! Si no sabéis todo, o no queréis explicar mucho, por favor, explicarme cualquier cosa que sepáis, y así yo podré aprender mucho más!

MUCHAS GRACIAS, ESPERO PODER AYUDAR Y SER AYUDADO TODO LO QUE PUEDA :D

Citar
hdc
Handle to a device context. Subsequent OpenGL calls made by the calling thread are drawn on the device identified by hdc.
hglrc
Handle to an OpenGL rendering context that the function sets as the calling thread's rendering context.
If hglrc is NULL, the function makes the calling thread's current rendering context no longer current, and releases the device context that is used by the rendering context. In this case, hdc is ignored.

Por simplificartelo un poco digamos que cada ventana de Windows tiene algo llamado "contexto de dispositivo" el cuál es diferente para cada ventana de Windows y dicho contexto es para indicarle que todo lo que dibujes sobre ese contexto va a estar a ser dibujado cuando la ventana tenga "su turno" para dibujar en su "espacio dentro de la pantalla".
Ahora el contexto de opengl es lo mismo pero primero debe relacionarse a una ventana y el contexto del opengl debe estar dentro del mismo "hilo de ejecución" que recibe los mensajes de dibujados de la ventana.
Todo eso Windows lo hace para tener un orden específico a la hora de dibujar cosas en la pantalla...

EDIT: cuando quieras poner algún código en el foro utiliza el botón geshi la próxima vez, sinó algún moderador te va a borrar el mensaje :P


B#


Título: Re: Comprensión del OpenGL + Win32
Publicado por: Seyro97 en 27 Septiembre 2014, 15:34 pm
Muchas gracias, amigo! Me he fijado en otros hilos de lo que tu dices, pero no sabia como se añadía xD. Tu explicación me ha gustado, ahora solo me falta lo de inicializar y desactivar el OpenGL!