程式語言 - Visual C++ 6.0 - Microsoft Fundation Class (MFC) - OpenGL 1.0 - Draw Triangle



參考資訊:
https://github.com/gamedev-net/nehe-opengl

main.cpp

#include <afxwin.h>
#include <math.h>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "res.h"

class CMyDlg : public CDialog {
public:
    CMyDlg();

    enum { IDD = IDD_MAIN_DIALOG };

protected:
    HDC hDC;
    HGLRC hRC;

    virtual BOOL OnInitDialog();

    afx_msg void OnPaint();
    afx_msg void OnDestroy();

    DECLARE_MESSAGE_MAP()
};

CMyDlg::CMyDlg() : CDialog(CMyDlg::IDD), hDC(NULL), hRC(NULL) {
}

BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
    ON_WM_PAINT()
    ON_WM_DESTROY()
END_MESSAGE_MAP()

BOOL CMyDlg::OnInitDialog() {
    PIXELFORMATDESCRIPTOR pfd = { 0 };

    CDialog::OnInitDialog();

    hDC = ::GetDC(m_hWnd);
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 16;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;

    int fmt = ChoosePixelFormat(hDC, &pfd);
    SetPixelFormat(hDC, fmt, &pfd);
    hRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hRC);

    CRect rc;
    GetClientRect(&rc);

    float aspect = (float)rc.Width() / rc.Height();
    glViewport(0, 0, rc.Width(), rc.Height());
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-aspect, aspect, -1.0, 1.0, -1.0, 1.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    return TRUE;
}

void CMyDlg::OnPaint() {
    CPaintDC dc(this);

    glBegin(GL_TRIANGLES);
        glVertex3f(0.0f, 0.5f, 0.0f);
        glVertex3f(-0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
    glEnd();

    SwapBuffers(hDC);
}

void CMyDlg::OnDestroy() {
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hRC);
    ::ReleaseDC(m_hWnd, hDC);

    CDialog::OnDestroy();
}

class CMyApp : public CWinApp {
public:
    BOOL InitInstance();
};

CMyApp theApp;

BOOL CMyApp::InitInstance() {
    CMyDlg dlg;

    m_pMainWnd = &dlg;
    dlg.DoModal();

    return FALSE;
}

main.rc

#include "res.h"
#include "afxres.h"

IDD_MAIN_DIALOG DIALOGEX  0, 0, 160, 120 
STYLE DS_MODALFRAME | WS_VISIBLE
EXSTYLE WS_EX_APPWINDOW
CAPTION "main"
FONT 8, "MS Sans Serif"
BEGIN
END

res.h

#define IDD_MAIN_DIALOG 101

編譯、執行

$ myx86 nmake -f main.mak