Sign in to follow this  

OpenGL Creating a DirectX 9.0 window class in C++

Recommended Posts

MartinSmith160    146
Hi All

I have read through Advanced2D development by J Harbour in which you create a 2D directX 9.0 game engine. The engine is based around a single window.

I was planning on doing it the following way but im not sure its the correct approach:

[*]Write a window class that has all the parameters to allow creation of different types and styles of window
[*]Each window will have its own D3D device
[*]Each window will be registered with windows
[*]Each window will have its own rendering portion, so each sprite on its draw command will pass in it's D3D device (like a GC in openGL)

This is what I plan to do but im not sure about handling the rendering properly. I also can never know how many windows a user could create so I am going to add them to a vector and then iterate over each whilst processing. I haven't really thought about sound yet.

My question is, is there anything blindingly I have missed out or really need to think about before I start this.

Thanks guys,

All the best,

Share this post

Link to post
Share on other sites
turch    590
That's more or less the approach I use. One note though, you need one unique D3D device per [i]fullscreen [/i]window. If you have multiple non-fullscreen windows, they should share a device. I have a window request a device from a device manager type class at window creation. If it is the first window, a device is created, otherwise the window is given an already created device.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Thanks turch. Yea each window will have its own device because I want to be able to run both windows in full screen. I'm going to be running my games on a multi monitor system. Thanks for the advice. I guess I will start planning.


Share this post

Link to post
Share on other sites
MartinSmith160    146
Hi Turch,

Just a quick question, I currently on have one LPD3DXSPRITE which is use as a sprite handler and that is used to draw all the sprites. When I create my sprite handler I have to pass it the LPDIRECT3DDEVICE9

eg D3DXCreateSprite(this->p_device, &this->p_sprite_handler);

My question is, do I now need to create a LPD3DXSPRITE for every window similar to making one LPDIRECT3DDEVICE9 for each window.


Share this post

Link to post
Share on other sites
mhagain    13430
LPD3DXSPRITE is really nothing more than a regular vertex and index buffer together with some variables, cobbled together into what looks like a D3D interface. So based on that, you can see that the same rules apply for creating sprites as for creatng any other resource - the Create* call is specific to a device and the resource is specific to the device that created it.

Note that D3D9Ex allows for sharing of resources between more than one device, but it's only available on Vista or higher, and comes with a bunch of other restrictions regarding usage and memory pools. I'm not certain if the LPD3DXSPRITE interface exposes this capability for the resources it creates, though.

Share this post

Link to post
Share on other sites
turch    590
Yes you do, and you will also need to duplicate any other device bound objects if you want to use them in either window - vertex buffers, textures, etc will all need to be duplicated.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Hi Guys

Thanks for you advice. I am having a a few issues with my window creation though. I have created a window wrapper class. I thought it was working because the windows create, are the correct dimensions and positions correctly. BUT when I call CreateWindowEX() it returns a NULL HWND.

Here is my Create function which sets up the window:

[source lang="cpp"]bool ST_Window::Create(HINSTANCE instance, int cmnd)
bool returnStatus = true;
appInstance = instance;
cmndLineArgs = cmnd;

wincl.hInstance = appInstance;
wincl.lpszClassName = title;
wincl.lpfnWndProc = WindowProc; = CS_HREDRAW | CS_VREDRAW;
wincl.cbSize = sizeof(WNDCLASSEX);
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL;
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
wincl.hbrBackground = NULL;

/* Register the first windows class, and if it fails quit the program
returning a 1 so that we know where it failed*/
if (!RegisterClassEx (&wincl))
return 1;

hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
title, /* Classname */
title, /* Title Text */
WS_OVERLAPPEDWINDOW, /* default window */
xPos, /* X position */
yPos, /* Y position */
width, /* The programs width */
height, /* and height in pixels */
0, /* The window is a child-window to desktop */
0, /* No menu */
appInstance, /* Program Instance handler */
0 /* No Window Creation data */

DWORD error = GetLastError();

returnStatus = false;

return returnStatus;

Also here is my windows procedure, each object will have this but its a static function:

[source lang="java"]LRESULT CALLBACK ST_Window::WindowProc(HWND p_hwnd, UINT message, WPARAM wParam, LPARAM lParam)
switch (message) /* handle the messages */
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
default: /* for messages that we don't deal with */
return DefWindowProc (p_hwnd, message, wParam, lParam);

//return 0;

Its really strange because the windows create but no handle is returned. Also I call GetLastError() and it returns 0. I cant setup up and DirectX without the HWNDs so im screwed. Any help would be awesome.

Thanks so much guys,

All the best,

Share this post

Link to post
Share on other sites
turch    590
I ran that function in a default windows project and it returned a HWND. Post more code so we can see what's going on around it.

Are you sure the window that is created, is created by that code? You don't call [url=""]ShowWindow[/url] anywhere, and if you just create the window without calling that it won't actually show up.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Hi Turch

Thats the create function of my window wrapper class. I have a winmain that calls ShowWindow() after its created. The window does show up so thats not the problem.

Here is my winmain code:

[source lang="cpp"]#pragma once

#include "ST_Window.h"

int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)

MSG messages; /* Here messages to the application are saved. This is shared in this example */

ST_Window window1("Window1", 0,0,800,600);
ST_Window window2("Window2", 1000,0,800,600);



while (PeekMessage (&messages, NULL, 0, 0, PM_REMOVE))
/* Translates Messages from GetMessage Function */
/* Dipatches Messages */


return messages.wParam;

I dont need to use the windows messaging so I dont mind that messages are shared between windows with the static WinProc. Its really strange, sometimes I get a HWND ok (Normally after a rebuild) but then after that i just get [unused] = ??? as the value.

I cant tell how great full I am for you help, im really stuck on this at the minute.

All the best,

Share this post

Link to post
Share on other sites
turch    590
ShowWindow takes a HWND, so if the window shows up you must be passing a valid HWND. Where do you try to return the HWND that doesn't work? Post that code.

Also, post the [color="#000000"]ST_Window[/color] constructor and ShowThisWindow functions.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Hi Turch

Im getting the HWND later when I want to create the directX device for the window. Basically I pass the window into the device manager and it creates a device and gives it to the window. I took that code out to make it cleaner to read. That code isnt working yet either but I thought it was due to having an invalid HWND. Could it be that the debugger is just showing me the wrong value?

Here is the ST_Window constructors:

[source lang="cpp"]ST_Window::ST_Window()
appInstance = 0;
hwnd = 0;
title = "DefaultWindow";
xPos = 0;
yPos = 0;
width = 800;
height = 600;
isFullScreen = false;
cmndLineArgs = 0;

window_device = 0;
window_backbuffer = 0;
window_sprite_handler = 0;
window_ambient_color = D3DCOLOR_RGBA(255,255,255,0);
[source lang="cpp"]ST_Window::ST_Window(char *title, int x, int y, int width, int height)
appInstance = 0;
hwnd = 0;
this->title = title;
xPos = x;
yPos = y;
this->width = width;
this->height = height;
isFullScreen = false;
cmndLineArgs = 0;

window_device = 0;
window_backbuffer = 0;
window_sprite_handler = 0;
window_ambient_color = D3DCOLOR_XRGB(255,255,255);

Here is the ShowThisWindow() function ( It basically just calls the windows functions but uses the stored HWND)

[source lang="cpp"]bool ST_Window::ShowThisWindow()
return ShowWindow(hwnd, cmndLineArgs);

Here is My DeviceManager class code:

[source lang="cpp"]#include "ST_DeviceManager.h"

deviceCount = 0;
this->d3d = NULL;

for(int i = 0; i < devices.size(); i++)


void ST_DeviceManager::CreateDevice(ST_Window &targetWindow)
if (this->d3d == NULL)
this->d3d = Direct3DCreate9(D3D_SDK_VERSION);

RECT clientWindowRect;

//get system desktop color depth
LPDIRECT3DSURFACE9 newbackbuffer;
LPD3DXSPRITE new_sprite_handler;

this->d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dm);

//set configuration options for Direct3D
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = targetWindow.IsFullScreen();
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
d3dpp.BackBufferFormat = dm.Format;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferWidth = clientWindowRect.right;
d3dpp.BackBufferHeight = clientWindowRect.bottom;
d3dpp.hDeviceWindow = targetWindow.GetHWND();

//create Direct3D device


newDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &newbackbuffer);

newDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
newDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
newDevice->SetRenderState(D3DRS_LIGHTING, true);


memset(&mat, 0, sizeof(mat));
mat.Diffuse.r = mat.Ambient.r = 1.0f;
mat.Diffuse.g = mat.Ambient.g = 1.0f;
mat.Diffuse.b = mat.Ambient.b = 1.0f;
mat.Diffuse.a = mat.Ambient.a = 1.0f;


newDevice = 0;
newbackbuffer = 0;
new_sprite_handler = 0;

Its very simplistic at this stage, I just wanted to get it working fundamentally. The DeviceManager::CreateDevice() is called after the window is created.

Sorry to bombard you with code. Basically if I call the CreateDevice() function my screen flashes black and the app locks up so I know something is majorly wrong but I thought its was not having a valid HWND. I stepped through the code for the CreateDevice() function and it locks up after this->d3d->CreateDevice() is called.

Thanks again for your help dude.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Holy Shit, I made such a stupid error.

check line 41 of the [color=#000000][font=Consolas,]ST_DeviceManager::CreateDevice(ST_Window &targetWindow) code. I set [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed [/font][/color][color=#000000][font=Consolas,]depending on the windows fulscreen status. As of now the isFullscreen variable is aslways false. so d3dpp.windowed was set to false making it try to go fullscreen but its not setup for it. I changed it to be [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed = !targetWindow.IsFullScreen(); and [/font][/color][color=#000000][font=Consolas,]The windows open and the devices are created correctly.[/font][/color]

[color=#000000][font=Consolas,]The HWND issue still confuses me though. The createDevice function works outs the correct window client area by getting the HWND from the window, but when I look at it in the debugger it still just says unused = ??? [/font][/color]

[color=#000000][font=Consolas,]Very strange.[/font][/color]

[color=#000000][font=Consolas,]Thank you so much for your help and im sorry if its seems like I wasted your time.[/font][/color]

[color=#000000][font=Consolas,]All the best,[/font][/color]

Share this post

Link to post
Share on other sites
turch    590
Hah, I actually made the same error when I was testing it a second ago... I set windowed to false thinking it was "fullscreen" - don't worry, the most frustrating and time consuming bugs are the ones where you make a stupid mistake. You gloss over the mistake because you can't [i]possibly [/i]make a mistake so simple [img][/img]

Look into [url=""]rubber duck debugging[/url] - whenever I'm searching for a bug and I just can't find it, I call in another dev and start explaining the code to them. They don't do anything or participate or even listen, but the act of explaining it that way forces you to consider those details you overlook because they are so obvious ( if (condition = true) ).

As for the HWND issue, make sure you are compiling and running the debug configuration, not release. If you try debugging a release build, you usually get incorrect data / variable unused / not found / etc. because the compiler doesn't insert debug information and mangles the code quite a bit for optimizations, and thus it can't find the variable.

And just a few more random thoughts:

consider wrapping all your raw directx pointers like so
typedef CComPtr<IDirect3D9> D3DPtr;
typedef CComPtr<IDirect3DDevice9> D3DDevicePtr;

That way, you don't have to call remember when you need to call Release, it will save you tons of time looking for memory leaks. You just use D3DPtr in place of LPDIRECT3D9

You might want to create only one D3DDevice for all (non-fullscreen) windows. Almost everything (textures, vertex buffers, shaders) is device-bound, so if you want to use one texture in two devices, you have to create it twice and keep track of which one belongs to which device. I use something similar to this (pseudocode):

if (devicemanager.device == null)
m_device = devicemanager.CreateDevice()
m_device = devicemanager.device

If you want multiple fullscreen windows, however, you have to use multiple devices. But most of the time all you really need multiple windows for is a level editor or other tools, and don't need them to run in fullscreen.

Share this post

Link to post
Share on other sites
MartinSmith160    146
Thanks Turch

I am running in debug mode for sure. The thing is sometimes it shows the HWND value and sometimes it dosent. BUT it always has a hex value. if it was NULL I would assume the hex value would be like 0x000000 or summin but it has an actual value so maybe its so large that the debugger cant show it. I might be speaking bollocks but it was just a thought.

Thats great advice for the debugging and the DirectX pointers aswell so thanks, I will definitely use that.As far as fullscreen goes, I will always be running two windows both in fullscreen because the games I aim to develop are for a multi monitor platform.

Thanks for all you help dude, you have really helped.

Share this post

Link to post
Share on other sites
Khatharr    8812
The debugger recognizes the types of variables and displays them accordingly. There's no variable type that's too large for it. NULL is == (void*)0, so if the debugger says 0x00000000 for a pointer then that's a NULL. You can trust it on this kind of thing. ;)

Share this post

Link to post
Share on other sites
MartinSmith160    146
Hi Khatharr

Thanks for the input, would you know of a reason then that when I look at my HWND values in the debugger its says 0x000109ba {unused = 0} but the handle still works.

All the best,

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
  • Popular Now