I'm trying to create an OpenGL context (Modern Version) using Windows functions.
Basically the code is just:
Create window class
Register the class
create a Window
choose PIXELFORMATDESCRIPTOR & set it
Create a legacy OpenGL context
Make context current
glewInit()
Create new window
Create a modern pixel format attrib array
Set the format
Create modern OpenGL context
Make context current
After this I try to draw a square (using a VAO & VBO).
The result is: the Windows window works, the glClear(GL_COLOR_BUFFER_BIT) works, but the square is not drawn (display() function).
If I use an OpenGL 2.0 context, it draws the square (using a VAO & VBO as before), so the problem must be on the init of OpenGL 3.2.
Where am I going wrong?
Here is the code:
#include <iostream>
#include <GL/glew.h>
#include <GL/wglew.h>
#include <windows.h>
#include <string>
using namespace std;
bool progRun = false;
void display(){
glUseProgram(shaderProg);
glBindVertexArray(vao[0]);
glDrawArrays(GL_QUADS, 0,4);
}
string errorStr = "none";
PIXELFORMATDESCRIPTOR pfd;
HGLRC hrc; // vars to init glew
HDC hdc;
HWND hwnd;
HGLRC hrc1; //vars for the real window
HDC hdc1;
HWND hwnd1;
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); // window event hadler prototype
//-------------------- INIT OPENGL
int initOpengl(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
//---- fake Window
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = (HBRUSH)( COLOR_WINDOW + 1 );
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "coco";
wcex.hIconSm = NULL;
if( !RegisterClassEx( &wcex ) )
{
errorStr = "RegisterClassEx";
return 0;
}
hwnd = CreateWindow(
"coco",
"dddd",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 500,
NULL,
NULL,
hInstance,
NULL
);
hdc = GetDC( hwnd );
memset( &pfd, 0, sizeof( PIXELFORMATDESCRIPTOR ) );
pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR );
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int nPixelFormat = ChoosePixelFormat( hdc, &pfd );
SetPixelFormat( hdc, nPixelFormat, &pfd );
hrc = wglCreateContext( hdc );
wglMakeCurrent( hdc, hrc );
glewExperimental = true;
glewInit();
//---------------For the real window
if( wglewIsSupported( "WGL_ARB_create_context" ) == 1 )
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hrc );
ReleaseDC( hwnd, hdc );
DestroyWindow( hwnd );
hwnd1 = CreateWindow(
"coco",
"ddddd",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 500,
NULL,
NULL,
hInstance,
NULL
);
hdc1 = GetDC( hwnd1 );
const int iPixelFormatAttribList[] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 8,
0 // End of attributes list
};
int attributes[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 3
, WGL_CONTEXT_MINOR_VERSION_ARB, 2
, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB
, 0
};
int nPixelFormat = 0;
UINT iNumFormats = 0;
wglChoosePixelFormatARB( hdc1, iPixelFormatAttribList, NULL, 1, &nPixelFormat, (UINT*)&iNumFormats );
SetPixelFormat( hdc1, nPixelFormat, &pfd );
hrc1 = wglCreateContextAttribsARB( hdc1, 0, attributes );
wglMakeCurrent( NULL, NULL );
wglMakeCurrent( hdc1, hrc1 );
}
else
{
errorStr = "WGL_ARB_create_context";
return 0;
}
return true;
}
// MAIN -----
int CALLBACK WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
initOpengl( hInstance, hPrevInstance, lpCmdLine, nCmdShow );
ShowWindow( hwnd1, SW_SHOW );
glClearColor( 1, 0, 0, 1 );
MSG msg;
progRun = true;
while( progRun )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
glClear( GL_COLOR_BUFFER_BIT );
glViewport( 0, 0, 500, 500 );
display();
SwapBuffers( hdc1 );
}
return 0;
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
return DefWindowProc( hWnd, message, wParam, lParam );
}
The problem is not in the context creation code alone, but in the combination of the used OpenGL version and the drawing code.
When requesting an OpenGL context as it is done in the question, there are several attributes that can be set. The relevant one here is the WGL_CONTEXT_PROFILE_MASK_ARB (which is not set). The extension description states:
The default value for WGL_CONTEXT_PROFILE_MASK_ARB is WGL_CONTEXT_CORE_PROFILE_BIT_ARB. [...] If the requested OpenGL version is less than 3.2,
WGL_CONTEXT_PROFILE_MASK_ARB is ignored and the functionality of the
context is determined solely by the requested version.
This means that the code in the question requests a OpenGL 3.2 Core Profile in the not working version a 3.1 (compatibility) profile in the other case.
In a core profile, the use of GL_QUADS as mode for glDrawArrays is deprecated and cannot be used. Due to this, the quad isn't rendered. Note, that you would have found the problem ways faster if you would check for OpenGL errors (glGetError) in your code since it would have reported a GL_INVALID_ENUM for the draw command.
There are two ways how the problem can be solved:
Stop drawing quads and draw triangles instead (GL_TRIANGLES). This is the recommended way.
Explicitly request a OpenGL 3.2 compatibility profile by adding a WGL_CONTEXT_PROFILE_MASK_ARB with the value WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB. But note, that this might cause problems in the future because mixing old OpenGL code with modern OpenGL can lead to problems.
Related
My goal is to create a basic tab control using the Win32 API that contains a canvas for rendering OpenGL. My tab contains a static control for rendering OpenGL. However, the only way I can get the canvas to appear in the GUI is to exclude the tab control (comment out the CREATE_TAB_PANE macro in my example to do this).
My example is given below:
// OpenGlTabWin32.cpp
// NOTE: canvas displays fine if TabPane creation is commented out
#include <windows.h>
#include <commctrl.h>
#include <gl/GL.h>
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "opengl32.lib")
#define CREATE_TAB_PANE
enum { IDC_TAB = 200, IDC_CANVAS = 201 };
static HWND TabPaneId;
static HWND CanvasId;
static WNDPROC CanvasWndProc;
static HGLRC CanvasRc;
static HDC CanvasDc;
////////////////////////////////////////////////////////////////////////////////
// WndProc
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam) {
switch (msg) {
case WM_CREATE:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// OpenGlCanvasProc
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK OpenGlCanvasProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam) {
if (msg == WM_PAINT) {
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
wglMakeCurrent(CanvasDc, CanvasRc);
SwapBuffers(CanvasDc);
return 0;
}
return CallWindowProc(CanvasWndProc, hwnd, msg, wParam, lParam);
}
////////////////////////////////////////////////////////////////////////////////
// CanvasInit
////////////////////////////////////////////////////////////////////////////////
static void CanvasInit() {
glClearColor(0.0, 0.0, 0.0, 0.0);
}
////////////////////////////////////////////////////////////////////////////////
// CanvasResize
////////////////////////////////////////////////////////////////////////////////
static void CanvasResize(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
////////////////////////////////////////////////////////////////////////////////
// CanvasDisplay
////////////////////////////////////////////////////////////////////////////////
static void CanvasDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3d(1, 0, 0);
glBegin(GL_LINE_STRIP);
glVertex2d(0.2, 0.2);
glVertex2d(0.8, 0.8);
glEnd();
SwapBuffers(CanvasDc);
}
////////////////////////////////////////////////////////////////////////////////
// WinMain
////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd) {
// Create window
const char *className = "OpenGlTab";
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = className;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wc)) {
exit(0);
}
HWND winId = CreateWindowEx(0,
className,
"Tab Pane w/ OpenGL",
WS_OVERLAPPEDWINDOW,
100, 100, 600, 400,
0,
0,
hInstance,
0);
if (!winId) {
exit(0);
}
ShowWindow(winId, nShowCmd);
UpdateWindow(winId);
#ifdef CREATE_TAB_PANE
// Create tab pane
TabPaneId = CreateWindow(WC_TABCONTROL,
0,
WS_CHILD | WS_VISIBLE,
10, 10, 566, 343,
winId,
HMENU(IDC_TAB),
hInstance,
0);
TCITEM tabItem = {0};
tabItem.mask = TCIF_TEXT;
tabItem.pszText = "Tab";
SendMessage(TabPaneId, TCM_INSERTITEM, 0, LPARAM(&tabItem));
#endif
// Create OpenGL canvas
int w = 200;
int h = 200;
CanvasId = CreateWindow("static",
"",
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
20, 100, w, h,
winId,
HMENU(IDC_CANVAS),
hInstance,
0);
CanvasWndProc = (WNDPROC)SetWindowLongPtr(CanvasId,
GWLP_WNDPROC,
(LONG_PTR)OpenGlCanvasProc);
CanvasDc = GetDC(CanvasId);
static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // version
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // color depth
0, 0, 0, 0, 0, 0,
0, 0,
0, 0, 0, 0, 0,
16, // depth buffer
0,
0,
0,
0,
0, 0, 0
};
int pixelFormat = ChoosePixelFormat(CanvasDc, &pfd);
SetPixelFormat(CanvasDc, pixelFormat, &pfd);
CanvasRc = wglCreateContext(CanvasDc);
// Render OpenGL canvas
wglMakeCurrent(CanvasDc, CanvasRc);
CanvasResize(w, h);
CanvasInit();
CanvasDisplay();
SwapBuffers(CanvasDc);
// Execute GUI
MSG msg;
while (GetMessage(&msg, 0, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
My updated example with changes per Chris:
// OpenGlTabWin32.cpp
// NOTE: canvas displays fine if TabPane creation is commented out
#include <windows.h>
#include <commctrl.h>
#include <gl/GL.h>
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "opengl32.lib")
#define CREATE_TAB_PANE
enum { IDC_TAB = 200, IDC_CANVAS = 201 };
static HWND TabPaneId;
static HWND CanvasId;
static WNDPROC CanvasWndProc;
static HGLRC CanvasRc;
////////////////////////////////////////////////////////////////////////////////
// WndProc
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam) {
switch (msg) {
case WM_CREATE:
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// CanvasInit
////////////////////////////////////////////////////////////////////////////////
static void CanvasInit() {
glClearColor(0.0, 0.0, 0.0, 0.0);
}
////////////////////////////////////////////////////////////////////////////////
// CanvasResize
////////////////////////////////////////////////////////////////////////////////
static void CanvasResize(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
////////////////////////////////////////////////////////////////////////////////
// CanvasDisplay
////////////////////////////////////////////////////////////////////////////////
static void CanvasDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3d(1, 0, 0);
glBegin(GL_LINE_STRIP);
glVertex2d(0.2, 0.2);
glVertex2d(0.8, 0.8);
glEnd();
}
////////////////////////////////////////////////////////////////////////////////
// OpenGlCanvasProc
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK OpenGlCanvasProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam) {
switch (msg) {
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
wglMakeCurrent(hdc, CanvasRc);
CanvasDisplay();
SwapBuffers(hdc);
wglMakeCurrent(NULL, NULL);
ReleaseDC(hwnd, hdc);
EndPaint(hwnd, &ps);
return 0;
}
case WM_SIZE:
{
HDC hdc = GetDC(hwnd);
wglMakeCurrent(hdc, CanvasRc);
CanvasResize(LOWORD(lParam), HIWORD(lParam));
wglMakeCurrent(NULL, NULL);
ReleaseDC(hwnd, hdc);
return 0;
}
}
return CallWindowProc(CanvasWndProc, hwnd, msg, wParam, lParam);
}
////////////////////////////////////////////////////////////////////////////////
// WinMain
////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd) {
// Create window
const char *className = "OpenGlTab";
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = className;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wc)) {
exit(0);
}
HWND winId = CreateWindowEx(0,
className,
"Tab Pane w/ OpenGL",
WS_OVERLAPPEDWINDOW,
100, 100, 600, 400,
0,
0,
hInstance,
0);
if (!winId) {
exit(0);
}
ShowWindow(winId, nShowCmd);
UpdateWindow(winId);
#ifdef CREATE_TAB_PANE
// Create tab pane
TabPaneId = CreateWindow(WC_TABCONTROL,
0,
WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS,
10, 10, 566, 343,
winId,
HMENU(IDC_TAB),
hInstance,
0);
TCITEM tabItem = {0};
tabItem.mask = TCIF_TEXT;
tabItem.pszText = "Tab";
SendMessage(TabPaneId, TCM_INSERTITEM, 0, LPARAM(&tabItem));
#endif
// Create OpenGL canvas
int w = 200;
int h = 200;
CanvasId = CreateWindow("static",
"",
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
20, 100, w, h,
winId,
HMENU(IDC_CANVAS),
hInstance,
0);
CanvasWndProc = (WNDPROC)SetWindowLongPtr(CanvasId,
GWLP_WNDPROC,
(LONG_PTR)OpenGlCanvasProc);
HDC hdc = GetDC(CanvasId);
static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // version
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // color depth
0, 0, 0, 0, 0, 0,
0, 0,
0, 0, 0, 0, 0,
16, // depth buffer
0,
0,
0,
0,
0, 0, 0
};
int pixelFormat = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, pixelFormat, &pfd);
CanvasRc = wglCreateContext(hdc);
// Render OpenGL canvas
wglMakeCurrent(hdc, CanvasRc);
CanvasResize(w, h);
CanvasInit();
CanvasDisplay();
SwapBuffers(hdc);
wglMakeCurrent(NULL, NULL);
ReleaseDC(CanvasId, hdc);
// Execute GUI
MSG msg;
while (GetMessage(&msg, 0, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
You have a number of things going on in this sample that are all possibly contributing:
The most immediate issue might simply be that the tab window is covering the canvas window and you are not actually painting anything in response to WM_PAINT. The tab control is going to paint over your canvas as soon as its invalidated as Windows usually lets child windows paint all over each other; so adding WS_CLIPSIBLINGS to the tab control might help.
You are grabbing an HDC to the static control and holding on to it after associating it with the current wgl context. You should not really do this unless you are using a window class with CS_OWNDC and especially not with one that probably has CS_PARENTDC (because then, as soon as the parent - or a different child - window paints, the DC is re-associated with a window that never had SetPixelFormat associated with it).
You are just making your opengl context current, and expecting it to be set later. This is fine - assuming you have a CS_OWNDC window with an HDC you can grab up front and keep around - and also assuming you never want to create a 2nd GL context for any reason.
So, when doing OpenGL in an application where you are not controlling the window class styles (or there might be more than one OpenGL context) you need to ensure that you always clear the current context and release the DC as soon as you are done with it.
For example, your CanvasWindowProc should look more like this:
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
wglMakeCurrent(glrc,hdc);
CanvasDisplay();
SwapBuffers();
wglMakeCurrent(NULL,NULL);
EndPaint(&ps);
}
return 0;
case WM_SIZE:
{
HDC hdc = GetDC(hwnd);
wglMakeCurrent(glrc,hdc);
CanvasResize(LOWORD(lParam),HIWORD(lParam));
wglMakeCurrent(NULL,NULL);
ReleaseDC(hwnd,hdc);
}
break;
Below is what I am using and working with:
Operating System - Windows 7 64Bit
IDE - Visual studio 2010 professional
Working on OpenGL with the basic lib files that are already present in visual studio i.e "opengl32.lib" "glu32.lib" and "gl.h" "glu.h"
Below is the code that I am trying to execute:
//
// GLSAMPLE.CPP
// by Blaine Hodge
//
// Includes
#include <windows.h>
#include <gl/gl.h>
#include <gl/GLU.h>
// Function Declarations
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC);
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC);
// WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int iCmdShow)
{
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL quit = FALSE;
float theta = 0.0f;
// register window class
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
wc.lpszMenuName = NULL;
wc.lpszClassName = "GLSample";
RegisterClass( &wc );
// create main window
hWnd = CreateWindow(
"GLSample", "OpenGL Sample",
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
0, 0, 256, 256,
NULL, NULL, hInstance, NULL );
// enable OpenGL for the window
EnableOpenGL( hWnd, &hDC, &hRC );
// program main loop
while ( !quit )
{
// check for messages
if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
// handle or dispatch messages
if ( msg.message == WM_QUIT )
{
quit = TRUE;
}
else
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
// OpenGL animation code goes here
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT );
glPushMatrix();
glRotatef( theta, 0.0f, 0.0f, 1.0f );
glBegin( GL_TRIANGLES );
glColor3f( 1.0f, 0.0f, 0.0f ); glVertex2f( 0.0f, 1.0f );
glColor3f( 0.0f, 1.0f, 0.0f ); glVertex2f( 0.87f, -0.5f );
glColor3f( 0.0f, 0.0f, 1.0f ); glVertex2f( -0.87f, -0.5f );
glEnd();
glPopMatrix();
SwapBuffers( hDC );
theta += 1.0f;
}
}
// shutdown OpenGL
DisableOpenGL( hWnd, hDC, hRC );
// destroy the window explicitly
DestroyWindow( hWnd );
return msg.wParam;
}
// Window Procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage( 0 );
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch ( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
}
// Enable OpenGL
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int format;
// get the device context (DC)
*hDC = GetDC( hWnd );
// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat( *hDC, &pfd );
SetPixelFormat( *hDC, format, &pfd );
// create and enable the render context (RC)
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );
}
// Disable OpenGL
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC( hWnd, hDC );
}
Below is the link for expected output:
http://www.nullterminator.net/glsample.gif
What I am getting on execution:
A blank black console screen.
Important notes:
Added opengl32.lib, glu32.lib in input section in project properties.
Drivers are updated
So can anyone tell me that what is wrong here. And one more thing that I have downloaded this code, not written it myself, here is the link for it http://www.nullterminator.net/opengl32.html
I see no projection/orthographic matrix in your code. You have to specify a camera for your scene. As the fixed function pipeline is deprecated i don't know the exact commands for this. I think its gluPerspecive.
See:
http://www.opengl.org/archives/resources/faq/technical/viewing.htm
I made an Edit Box in my window, but when I try to draw something with OpenGl in dissapears. What should I change?
Here is the code:
#include <windows.h>
#include <gl/gl.h>
#include <math.h>
#define IDC_MAIN_EDIT 102
HWND hEdit;
// Function Declarations
HMENU men;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC);
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC);
// WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int iCmdShow)
{
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL quit = FALSE;
float theta = 0.0f;
// register window class
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
wc.lpszMenuName = NULL;
wc.lpszClassName = "GLSample";
RegisterClass( &wc );
// create main window
hWnd = CreateWindow(
"GLSample", "OpenGL Sample",
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
0, 0, 800, 800,
NULL, NULL, hInstance, NULL );
// enable OpenGL for the window
EnableOpenGL( hWnd, &hDC, &hRC );
// program main loop
while ( !quit )
{
// check for messages
if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
// handle or dispatch messages
if ( msg.message == WM_QUIT )
{
quit = TRUE;
}
else
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
// OpenGL animation code goes here
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef( theta, 0.0f, 0.0f, 1.0f );
glBegin( GL_TRIANGLES );
glColor3f( 1.0f, 0.0f, 0.0f ); glVertex2f( 0.0f, 0.25f );
glColor3f( 0.0f, 1.0f, 0.0f ); glVertex2f( 0.21f, -0.12f );
glColor3f( 0.0f, 0.0f, 1.0f ); glVertex2f( -0.21f, -0.12f );
glEnd();
glPopMatrix();
SwapBuffers( hDC );
theta += 1.0f;
}
}
// shutdown OpenGL
DisableOpenGL( hWnd, hDC, hRC );
// destroy the window explicitly
DestroyWindow( hWnd );
return msg.wParam;
}
// Window Procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
hEdit=CreateWindowEx(WS_EX_CLIENTEDGE,
"EDIT",
"",
WS_CHILD|WS_VISIBLE|
ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL,
50,
20,
60,
30,
hWnd,
(HMENU)IDC_MAIN_EDIT,
GetModuleHandle(NULL),
NULL);
HGDIOBJ hfDefault=GetStockObject(DEFAULT_GUI_FONT);
SendMessage(hEdit,
WM_SETFONT,
(WPARAM)hfDefault,
MAKELPARAM(FALSE,0));
SendMessage(hEdit,
WM_SETTEXT,
NULL,
(LPARAM)"Length");
return 0;
}
case WM_CLOSE:
PostQuitMessage( 0 );
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch ( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
}
// Enable OpenGL
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int format;
// get the device context (DC)
*hDC = GetDC( hWnd );
// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat( *hDC, &pfd );
SetPixelFormat( *hDC, format, &pfd );
// create and enable the render context (RC)
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );
}
// Disable OpenGL
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC( hWnd, hDC );
}
The answer is very simple - I just changed the parametrs of function CreateWindow to
hWnd = CreateWindow(
"GLSample", "OpenGL Sample",
WS_SYSMENU|WS_VISIBLE|WS_MINIMIZEBOX|WS_OVERLAPPED|WS_BORDER|WS_CAPTION|
WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0, 0, 800, 800,
NULL, NULL, hInstance, NULL );
this and voila- it all works^_^
It could be overwriting your painting in the default WM_ERASEBKGND code. One way to fix it is to move your OpenGL code to WM_PAINT handler, and then invalidate your window each time you want the animation to advance.
Ok, so I am running Visual Basic 2010 Express and I tried to run Tutorial # 2 in the Direct X SDK; however, the program won't compile for some reason, although in the tutorial I am reading now it said that I only needed the Direct X SDK and Visual Basic 2010 Express. I opened Tutorial02_2010.sln, and tried to compile it. Here's the code of the main file:
//--------------------------------------------------------------------------------------
// File: Tutorial02.cpp
//
// This application displays a triangle using Direct3D 10
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include <d3d10.h>
#include <d3dx10.h>
#include "resource.h"
//--------------------------------------------------------------------------------------
// Structures
//--------------------------------------------------------------------------------------
struct SimpleVertex
{
D3DXVECTOR3 Pos;
};
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE g_hInst = NULL;
HWND g_hWnd = NULL;
D3D10_DRIVER_TYPE g_driverType = D3D10_DRIVER_TYPE_NULL;
ID3D10Device* g_pd3dDevice = NULL;
IDXGISwapChain* g_pSwapChain = NULL;
ID3D10RenderTargetView* g_pRenderTargetView = NULL;
ID3D10Effect* g_pEffect = NULL;
ID3D10EffectTechnique* g_pTechnique = NULL;
ID3D10InputLayout* g_pVertexLayout = NULL;
ID3D10Buffer* g_pVertexBuffer = NULL;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
void Render();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
UNREFERENCED_PARAMETER( hPrevInstance );
UNREFERENCED_PARAMETER( lpCmdLine );
if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
return 0;
if( FAILED( InitDevice() ) )
{
CleanupDevice();
return 0;
}
// Main message loop
MSG msg = {0};
while( WM_QUIT != msg.message )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
Render();
}
}
CleanupDevice();
return ( int )msg.wParam;
}
//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon( hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"TutorialWindowClass";
wcex.hIconSm = LoadIcon( wcex.hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
if( !RegisterClassEx( &wcex ) )
return E_FAIL;
// Create window
g_hInst = hInstance;
RECT rc = { 0, 0, 640, 480 };
AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
g_hWnd = CreateWindow( L"TutorialWindowClass", L"Direct3D 10 Tutorial 2: Rendering a Triangle",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance,
NULL );
if( !g_hWnd )
return E_FAIL;
ShowWindow( g_hWnd, nCmdShow );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect( g_hWnd, &rc );
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif
D3D10_DRIVER_TYPE driverTypes[] =
{
D3D10_DRIVER_TYPE_HARDWARE,
D3D10_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = sizeof( driverTypes ) / sizeof( driverTypes[0] );
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory( &sd, sizeof( sd ) );
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
{
g_driverType = driverTypes[driverTypeIndex];
hr = D3D10CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags,
D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice );
if( SUCCEEDED( hr ) )
break;
}
if( FAILED( hr ) )
return hr;
// Create a render target view
ID3D10Texture2D* pBuffer;
hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBuffer );
if( FAILED( hr ) )
return hr;
hr = g_pd3dDevice->CreateRenderTargetView( pBuffer, NULL, &g_pRenderTargetView );
pBuffer->Release();
if( FAILED( hr ) )
return hr;
g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );
// Setup the viewport
D3D10_VIEWPORT vp;
vp.Width = width;
vp.Height = height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_pd3dDevice->RSSetViewports( 1, &vp );
// Create the effect
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif
hr = D3DX10CreateEffectFromFile( L"Tutorial02.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0,
g_pd3dDevice, NULL, NULL, &g_pEffect, NULL, NULL );
if( FAILED( hr ) )
{
MessageBox( NULL,
L"The FX file cannot be located. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
return hr;
}
// Obtain the technique
g_pTechnique = g_pEffect->GetTechniqueByName( "Render" );
// Define the input layout
D3D10_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof( layout ) / sizeof( layout[0] );
// Create the input layout
D3D10_PASS_DESC PassDesc;
g_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
hr = g_pd3dDevice->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pVertexLayout );
if( FAILED( hr ) )
return hr;
// Set the input layout
g_pd3dDevice->IASetInputLayout( g_pVertexLayout );
// Create vertex buffer
SimpleVertex vertices[] =
{
D3DXVECTOR3( 0.0f, 0.5f, 0.5f ),
D3DXVECTOR3( 0.5f, -0.5f, 0.5f ),
D3DXVECTOR3( -0.5f, -0.5f, 0.5f ),
};
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DEFAULT;
bd.ByteWidth = sizeof( SimpleVertex ) * 3;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = vertices;
hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer );
if( FAILED( hr ) )
return hr;
// Set vertex buffer
UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
g_pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );
// Set primitive topology
g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
if( g_pd3dDevice ) g_pd3dDevice->ClearState();
if( g_pVertexBuffer ) g_pVertexBuffer->Release();
if( g_pVertexLayout ) g_pVertexLayout->Release();
if( g_pEffect ) g_pEffect->Release();
if( g_pRenderTargetView ) g_pRenderTargetView->Release();
if( g_pSwapChain ) g_pSwapChain->Release();
if( g_pd3dDevice ) g_pd3dDevice->Release();
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
switch( message )
{
case WM_PAINT:
hdc = BeginPaint( hWnd, &ps );
EndPaint( hWnd, &ps );
break;
case WM_DESTROY:
PostQuitMessage( 0 );
break;
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
return 0;
}
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
// Clear the back buffer
float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red,green,blue,alpha
g_pd3dDevice->ClearRenderTargetView( g_pRenderTargetView, ClearColor );
// Render a triangle
D3D10_TECHNIQUE_DESC techDesc;
g_pTechnique->GetDesc( &techDesc );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
g_pTechnique->GetPassByIndex( p )->Apply( 0 );
g_pd3dDevice->Draw( 3, 0 );
}
// Present the information rendered to the back buffer to the front buffer (the screen)
g_pSwapChain->Present( 0, 0 );
}
Do I need to install anything else, like a library or something and do I just need to follow the same steps I had to take for the Direct x lib files?
http://www.rastertek.com/dx11tut01.html
Install visual studio Express C++.
Install the Windows SDK for windows 7.
After recreating a new project for that copy+pasted code, point the project properties to the windows sdk, as well as the direct X sdk. This includes both include folders, and lib folders. If you don't know how to do that, Go check out the "how do i" videos on msdn.com for visual studio 2010.
Compile.
I got a very similar error with Visual Studio 2013 Express:
LINK : fatal error LNK1181: cannot open input file 'winmm.lib'
For me, it turned out I'd installed 'Visual Studio 2013 Express for Windows', when I actually needed 'Visual Studio 2013 Express for Windows Desktop'.
Installing 'Visual Studio 2013 Express for Windows Desktop' cured the error for me.
I am currently learning DirectX so I am a starter and I am stuck at one code. I am studying from a book and I have written this code. It should draw a bitmap on the window but its giving me a blank screen. Moreover when I click esc button it gives an error but if I move or stretch the window before pressing esc, it doesnt give an error. Any help appreciated. I am using Visual Studio 2010 and C++. I have one assumption that the error might be at D3DXCreateSurfaceFromFile. Here is the code;
//Header files to include
#include <d3d9.h>
#include <time.h>
#include <d3dx9.h>
//Application title
#define APPTITLE L"Load_Bitmap"
//Screen Resolution
#define WIDTH 640
#define HEIGHT 480
//Forward Declarations
LRESULT WINAPI WinProc( HWND, UINT, WPARAM, LPARAM);
ATOM MyRegisterClass( HINSTANCE);
int GameInit(HWND);
void GameRun(HWND);
void GameEnd(HWND);
//Direct3d objects
LPDIRECT3D9 d3d = NULL;
LPDIRECT3DDEVICE9 d3ddev = NULL;
LPDIRECT3DSURFACE9 backbuffer = NULL;
LPDIRECT3DSURFACE9 surface = NULL;
//Macros to read the keyboard asynchronously
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEY_UP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
//Window Event Callback Function
LRESULT WINAPI WinProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
GameEnd( hWnd);
PostQuitMessage(0);
return 0;
}
return DefWindowProc( hWnd, msg, wParam, lParam);
}
//Helper function to set up the window properties
ATOM MyRegisterClass( HINSTANCE hInstance)
{
WNDCLASSEX wc;
wc.cbSize = sizeof( WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = APPTITLE;
wc.hIconSm = NULL;
//Set up the window with the class info
return RegisterClassEx(&wc);
}
//Entry point for a windows program
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstancem, LPSTR lpCmdLine, int nCmdShow)
{
//Declare variables
MSG msg;
//Register the class
MyRegisterClass( hInstance);
//Initialize Application
HWND hWnd;
//Create new Window
hWnd = CreateWindow( APPTITLE, APPTITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstance, NULL);
if( !hWnd)
return FALSE;
//Display the Window
ShowWindow( hWnd, nCmdShow);
UpdateWindow( hWnd);
//Initialize the Game
if( !GameInit( hWnd))
return FALSE;
//Main Message Loop
int done = 0;
while(!done)
{
if(PeekMessage( &msg, hWnd, 0, 0, PM_REMOVE))
{
//Look for quit message
if( msg.message == WM_QUIT)
done = 1;
//Decode and pass messages on to WndProc
TranslateMessage( &msg);
DispatchMessage( &msg);
}
else
//Process game loop( else prevents running after window is closed)
GameRun(hWnd);
}
return msg.wParam;
}
int GameInit( HWND hWnd)
{
HRESULT result;
//Initialize Direct3d
d3d = Direct3DCreate9(D3D_SDK_VERSION);
if( d3d == NULL)
{
MessageBox( hWnd, L"Error initializing Direct3d", L"Error", MB_OK);
return 0;
}
//Set Direct3D presentation parameters
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferWidth = WIDTH;
d3dpp.BackBufferHeight = HEIGHT;
d3dpp.hDeviceWindow = hWnd;
//Create Direct3D device
d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
if( d3ddev == NULL)
{
MessageBox( hWnd, L"Error creating Direct3d device", L"Error", MB_OK);
return 0;
}
//Set Random number seed
//srand( time(NULL));
//Clear the backbuffer to black
d3ddev->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0,0,0), 1.0f, 0);
//Create pointer to the back buffer
d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);
//Create surface
result = d3ddev->CreateOffscreenPlainSurface( 640, 480, D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT, &surface, NULL);
if( result != D3D_OK)
return 1;
//load surface from file
result = D3DXLoadSurfaceFromFile(
surface, NULL, NULL, L"c.bmp", NULL, D3DX_DEFAULT, 0, NULL);
//Make sure file was loaded okay
if( result != D3D_OK)
return 1;
d3ddev->StretchRect( surface, NULL, backbuffer, NULL, D3DTEXF_NONE);
//Return okay
return 1;
}
void GameRun(HWND hWnd)
{
//Make Sure the Direct3d device is valid
if( d3ddev == NULL)
return;
//Start Rendering
if( d3ddev->BeginScene())
{
//Create pointer to the back buffer
d3ddev->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);
//Draw surface to the backbuffer
d3ddev->StretchRect( surface, NULL, backbuffer, NULL, D3DTEXF_NONE);
//StopRendering
d3ddev->EndScene();
}
//Display the back buffer on the screen
d3ddev->Present( NULL, NULL, NULL, NULL);
//Check for escape key( to exit program)
if( KEY_DOWN(VK_ESCAPE))
PostMessage(hWnd, WM_DESTROY, 0, 0);
}
void GameEnd(HWND hWnd)
{
//free the surface
if( surface != NULL)
surface->Release();
//Release the Direct3D device
if( d3ddev != NULL)
d3ddev->Release();
if( d3d != NULL)
d3d->Release();
}
Post WM_QUIT instead of WM_DESTROY when you check the escape key. As it stands now the message-loop will never quit since it depends on WM_QUIT being posted, and it will keep calling GameRun even after the surfaces are deleted.