• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
  • entries
    3
  • comments
    7
  • views
    5326

About this blog

Engine programming for games

Entries in this blog

EngineProgrammer
Hello ladies and gentlemen,


Welcome to my journal!
If some of you guys are following me to create your own game engine, you should have a window by now so let's continue. And if you are just watching what I'm coding, next I'll put all DirectX stuff into my engine.

It was hard to find to get, an almost full, initialization of DirectX but I've some decent pieces of code which I have put into my code.



bool Graphics::Initialize(Window* pWindow)
{
HRESULT result;
IDXGIFactory* pFactory = nullptr;
IDXGIAdapter* pAdapter = nullptr;
IDXGIOutput* pAdapterOutput = nullptr;
DXGI_MODE_DESC* pDisplayModeList = nullptr;
DXGI_ADAPTER_DESC adapterDesc;
D3D_FEATURE_LEVEL featureLevel;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_DESC depthDisableStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_RASTERIZER_DESC rasterDesc;
D3D11_BLEND_DESC blendStateDescription;
unsigned int numModes = 0, numerator = 0, denominator = 0;
float fieldOfView = 0.0f, screenAspect = 0.0f;

// Store the pointer of the window
m_pWindow = pWindow;

// Create a DirectX graphics interface factory
result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&pFactory);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDXGIFactory"));
}

// Use the factory to create an adapter for the primary graphics interface ( video card )
result = pFactory->EnumAdapters(0, &pAdapter);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set EnumAdapters factory"));
}

// Enumerate the primary adapted output ( monitor )
result = pAdapter->EnumOutputs(0, &pAdapterOutput);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set EnumOutputs adapter"));
}

// Get the numbder of modes that fit in the display the the adapter output ( monitor )
result = pAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set GetDisplayModeList adapter"));
}

// Create list to hold all possible display modes for this monitor/video card combinatior
pDisplayModeList = new DXGI_MODE_DESC[numModes];
if(!pDisplayModeList)
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("creating DisplayModeList"));
}

// Now fill the fisplay mode list structures
result = pAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, pDisplayModeList);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("GetDisplayModeList adapter"));
}

// Now go through all the display modes and find the one that mathces the screen width and height
// When a match is found store the numerator and denominator of the refresh rate for that monitor
for(int i=0; i<(int)numModes; ++i)
{
if(pDisplayModeList.Width == (unsigned int)m_pWindow->GetWindowWidth())
{
if(pDisplayModeList.Height == (unsigned int)m_pWindow->GetWindowHeight())
{
numerator = pDisplayModeList.RefreshRate.Numerator;
denominator = pDisplayModeList.RefreshRate.Denominator;
}
}
}

// Get the adapter ( video card ) description
result = pAdapter->GetDesc(&adapterDesc);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("GetDesc adapter"));
}

// Store the dedicated video card memory in megabytes
m_VideoCardMemory = (int)(adapterDesc.DedicatedSystemMemory/1024/1024);

// Store the video card name
m_VideoCardDescription = adapterDesc.Description;

// Release the display list, adapter output, adapter, factory
SafeDeleteArray(pDisplayModeList);
SafeRelease(pAdapterOutput);
SafeRelease(pAdapter);
SafeRelease(pFactory);

// Create a struct to hold information about the swap chain
DXGI_SWAP_CHAIN_DESC swapChainDesc;

// Clear out the struct for use
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

// Fill the swap chain description struct
swapChainDesc.BufferCount = 1; // 1 Back buffer
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Use 32-bit color
swapChainDesc.BufferDesc.Width = m_pWindow->GetWindowWidth(); // Set the back buffer width
swapChainDesc.BufferDesc.Height = m_pWindow->GetWindowHeight(); // Set the back buffer height
if(m_pWindow->GetVSync())
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // How the chain is to be used
swapChainDesc.OutputWindow = m_pWindow->GetHandleToWindow(); // The window to be used

// Turn multisampling off
swapChainDesc.SampleDesc.Count = 1; // How many multisamples
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Windowed = !m_pWindow->GetFullscreen(); // Windowed/Fullscreen mode
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;

// Set the feature level to DirectX 11
featureLevel = D3D_FEATURE_LEVEL_11_0;
// Create a device, device context and swap chain using the information in the swapChainDesc struct
D3D11CreateDeviceAndSwapChain( NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
0,
&featureLevel,
1,
D3D11_SDK_VERSION,
&swapChainDesc,
&m_pSwapChain,
&m_pDevice,
NULL,
&m_pDeviceContext );

// Get the adress of the back buffer
ID3D11Texture2D* pBackBuffer;
m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

// Use the back buffer address to create the render target
m_pDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView);

// Set the render target as the back buffer
m_pDeviceContext->OMSetRenderTargets(1, &m_pBackBuffer, NULL);

// Release back buffer
pBackBuffer->Release();

// Initialize the description of the depth buffer
ZeroMemory( &depthBufferDesc, sizeof(depthBufferDesc) );

// Set up the description of the depth buffer
depthBufferDesc.Width = m_pWindow->GetWindowWidth();
depthBufferDesc.Height = m_pWindow->GetWindowHeight();
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;

// create the texture for the depth buffer using the filled out description
result = m_pDevice->CreateTexture2D(&depthBufferDesc, NULL, &m_pDepthStencilBuffer);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateTexture2D depthBufferDesc"));
}
// Initialize the description of the stencil state
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

// Set up the description of the stencil state
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

// Create the depth stencil state
result = m_pDevice->CreateDepthStencilState(&depthStencilDesc, &m_pDepthStencilState);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilState depthStencilDesc"));
}

// Set the depth stencil state
m_pDeviceContext->OMSetDepthStencilState(m_pDepthStencilState, 1);

// Initialize the depth stencil view
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;

// Create the depth stencil view
result = m_pDevice->CreateDepthStencilView(m_pDepthStencilBuffer, &depthStencilViewDesc, &m_pDepthStencilView);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilView m_pDepthStencilBuffer"));
}

// Bind the render target view and depth stencil buffer to the output render pipeline
m_pDeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView);
// Setup the raster description which will determine how and what polygons will be drawn
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;

result = m_pDevice->CreateRasterizerState(&rasterDesc, &m_pRasterState);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateRasterizerState rasterDesc"));
}

// Now set the rasterizer state
m_pDeviceContext->RSSetState(m_pRasterState);

// Set the viewport for rendering
D3D11_VIEWPORT viewPort;
ZeroMemory(&viewPort, sizeof(D3D11_VIEWPORT));
viewPort.MinDepth = 0.0f;
viewPort.MaxDepth = 1.0f;
viewPort.TopLeftX = 0;
viewPort.TopLeftY = 0;
viewPort.Width = (float)m_pWindow->GetWindowWidth();
viewPort.Height = (float)m_pWindow->GetWindowHeight();
m_pDeviceContext->RSSetViewports(1, &viewPort);

// Setup Projection matrix
fieldOfView = (float)D3DX_PI/4.0f;
screenAspect = (float)m_pWindow->GetWindowWidth()/(float)m_pWindow->GetWindowHeight();

// Create the projection matrix for 3D rendering
D3DXMatrixPerspectiveFovLH(&m_ProjectionMatrix, fieldOfView, screenAspect, SCREEN_NEAR, SCREEN_DEPTH);

// Initialize the world matrix to identity matrix
D3DXMatrixIdentity(&m_WorldMatrix);

// Create an orthographic projection matrix for 2D rendering
D3DXMatrixOrthoLH(&m_OrthoMatrix, (float)m_pWindow->GetWindowWidth(), (float)m_pWindow->GetWindowHeight(), SCREEN_NEAR, SCREEN_DEPTH);

// Clear the memory
ZeroMemory(&depthDisableStencilDesc, sizeof(depthDisableStencilDesc));
// Set up the description of the stencil state
depthDisableStencilDesc.DepthEnable = false;
depthDisableStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisableStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisableStencilDesc.StencilEnable = true;
depthDisableStencilDesc.StencilReadMask = 0xFF;
depthDisableStencilDesc.StencilWriteMask = 0xFF;
depthDisableStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisableStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisableStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisableStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisableStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisableStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisableStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisableStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

// Create the depth stencil state
result = m_pDevice->CreateDepthStencilState(&depthDisableStencilDesc, &m_pDepthDisableStencilState);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilState depthDisableStencilDesc"));
}
ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;

result = m_pDevice->CreateBlendState(&blendStateDescription, &m_AlphaEnableBlendingState);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateBlendState blendStateDescription"));
}
blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
result = m_pDevice->CreateBlendState(&blendStateDescription, &m_AlphaDisableBlendingState);
if(FAILED(result))
{
return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateBlendState blendStateDescription"));
}
return true;
}


As I've said in the previous entry my Application creates the core(window, system, graphics), so you should be able to initialize these graphics all by yourself. ;)

But when you have all initialization ready don't run it yet! don't fly when you can't walk. Else you would forget that you also need to deallocate what you have allocated! ;)


void Graphics::Shutdown()
{
if(m_pSwapChain != nullptr)
{
m_pSwapChain->SetFullscreenState(false, NULL);
}

SafeRelease(m_AlphaDisableBlendingState);
SafeRelease(m_AlphaEnableBlendingState);
SafeRelease(m_pDepthDisableStencilState);
SafeRelease(m_pDepthStencilBuffer);
SafeRelease(m_pDepthStencilState);
SafeRelease(m_pRenderTargetView);
SafeRelease(m_pRasterState);
SafeRelease(m_pBackBuffer);
SafeRelease(m_pDeviceContext);
SafeRelease(m_pDevice);
SafeRelease(m_pSwapChain);
}


SafeRelease is a template, I love clear readable code!:
template
inline void SafeRelease(T &pObject)
{
if(pObject != nullptr){
pObject->Release();
pObject = nullptr;
}
}


This took a very long time to get and understand all that code. I think I've deserved a break! ^^

By the way my window class you saw last entry is buggy.
In case you didn't read the reply there: I was casting the HWND to my Window* so I could call the method 'HandleEvents(...) in the WndProc function. But as soon I changed a data member in the HandleEvents method the application wouldn't start anymore. So needed to change this and this is what I've made:

if(msg == WM_CREATE) { SetWindowLong(hWnd, GWL_USERDATA, (LONG)((LPCREATESTRUCT)lParam)->lpCreateParams); }
else
{
Window* pWindow = (Window*)GetWindowLong(hWnd, GWL_USERDATA);
if(pWindow) { return pWindow->HandleEvents(hWnd, msg, wParam, lParam); }
}

return DefWindowProc(hWnd, msg, wParam, lParam);


So that was it for the graphics class. I hope you guys enjoy the code! If you want to see more follow my blog to keep in touch. And following this blog also means people are interested in these codes.smile.png

So next entry will be my system class. But that won't be for today! First I'm going to enjoy my break ^^
So thank you ladies and gentlemen and see you in the next entry!
EngineProgrammer
Hello ladies and gentlemen,


Welcome to my journal!
So part 1 of writing an engine. I hope you guys are all so excited as me! laugh.png ( I know you do )

Before I step into DirectX graphics I first want to create a window.
For people who haven't learned DirectX yet, for popping up a window you don't need any DirectX libs.
DirectX will just need the handle and instance of the window and will turn everything to a 3D space.

By the way, didn't mentioned it before, I'm using Unicode!
Example:

#ifdef _UNICODE
#define tstring wstring
#else
#define tstring string
#endif


So.. Writing a game engine. How should I start? How should I write? How will my structure look like?
Don't worry already got the idea! cool.png

The plan is that my WinMain function creates an Application, which handles the core and game.
This is how it looks like:

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PTSTR pCmdLine, int nCmdShow)
{
// Terminate if heap is corrupted
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

// Avoid warnings of unused parameters
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(pCmdLine);

// Allocate the application
Application* pApplication = new Application();

// Initialize and run the application
if(pApplication->Initialize(hInstance))
{
pApplication->Run();
}

// Shutdown and deallocate the application
SafeDeleteCore(pApplication);
return TRUE;
}


So I'm Initializing the Application, running if succeeded, and shutting down.
And for those who wonder what "SafeDeleteCore" is:

template
inline void SafeDeleteCore(T &pObject)
{
if(pObject != nullptr){
pObject->Shutdown();
delete pObject;
pObject = nullptr;
}
}


My application has 4 data members:
core: Window*, System*, Graphics*
game: Game*

I think you all know what to do with those data members when you have 3 methods... So not going to show such simple code....
Ok maybe a bit.. Because all of you are so lovely tongue.png
This is the Run method:

void Application::Run()
{
// GameStart
m_pGame->GameStart();


MSG msg = {0};
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// GameUpdate
m_pGame->GameUpdate();

// GameRender
m_pGame->GameRender();

Sleep(1);
}
}

// GameEnd
m_pGame->GameEnd();
}


So we got the WinMain, Application.... That was it I think?
Yes everything is done, we have written our engine. Now we can create games like Starcraft!!

Or is it? ph34r.png
No there is more!!!! *screaming* *crying* *beating up the kid next door*

We still need that window on our screen! or maybe if you stare long enough it will magically appear.. You can give it a shot.
So for the window class. A window class needs to store some information about the window so you can easily change something on your screen.

class Window
{
public:
/////////////////////////////////////////////////////
// Constructor(s) & Destructor
/////////////////////////////////////////////////////
Window();
virtual ~Window();

/////////////////////////////////////////////////////
// Public Methods
/////////////////////////////////////////////////////
bool Initialize(HINSTANCE hInstance);
void Shutdown();
void ShowWindow();

LRESULT CALLBACK HandleEvents(HWND, UINT, WPARAM, LPARAM);

private:
HWND m_hMainWnd;
HINSTANCE m_hInstance;
tstring m_sWindowTitle;
int m_iWindowWidth;
int m_iWindowHeight;
bool m_bFullscreen;
};

static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);



The Window.cpp is the largest piece of code I have at the moment. Here it comes!

bool Window::Initialize(HINSTANCE hInstance)
{
// Store the instance of the application
m_hInstance = hInstance;

// Setup the window class with default settings
WNDCLASSEX wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = m_hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wndclass.hIconSm = wndclass.hIcon;
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255,255,255));
wndclass.lpszMenuName = m_sWindowTitle.c_str();
wndclass.lpszClassName = m_sWindowTitle.c_str();
wndclass.cbSize = sizeof(WNDCLASSEX);

// Register the window class
if(!RegisterClassEx(&wndclass)) {
return false;
}

// Create new screen settings if fullscreen
int posX = 0, posY = 0;
if(m_bFullscreen)
{
DEVMODE dmScreenSettings;
memset(&dmScreenSettings, 0,sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)m_iWindowWidth;
dmScreenSettings.dmPelsHeight = (unsigned long)m_iWindowHeight;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
}
else
{
posX = (GetSystemMetrics(SM_CXSCREEN) - m_iWindowWidth) /2;
posY = (GetSystemMetrics(SM_CYSCREEN) - m_iWindowHeight) /2;
}

// Create the window with the screen settings and get the handle to it
m_hMainWnd = CreateWindowEx(WS_EX_APPWINDOW, m_sWindowTitle.c_str(), m_sWindowTitle.c_str(),
WS_CAPTION | WS_POPUPWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP | WS_MINIMIZEBOX,
posX, posY, m_iWindowWidth, m_iWindowHeight,
NULL, NULL, m_hInstance, NULL );

if(!m_hMainWnd) {
return false;
}

// Set window as main focus ~ sets higher priority to this thread
SetForegroundWindow(m_hMainWnd);
SetFocus(m_hMainWnd);

return true;
}
void Window::Shutdown()
{
// Show the mouse cursor ~ just in case the mouse was hidden in run-time
ShowCursor(true);

// Fix the display settings if leaving full screen mode
if(m_bFullscreen) {
ChangeDisplaySettings(NULL, 0);
}

// Remove the window
DestroyWindow(m_hMainWnd);
m_hMainWnd = NULL;

// Remove the application's instance
UnregisterClass(m_sWindowTitle.c_str(), m_hInstance);
m_hInstance = NULL;
}
void Window::ShowWindow()
{
::ShowWindow(m_hMainWnd, SW_SHOW);
::UpdateWindow(m_hMainWnd);
}
LRESULT CALLBACK Window::HandleEvents(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, msg, wParam, lParam);
}


////////////////////////////////////////////////////////////////////////////////
// Window Procedure
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
}

return ((Window*)GetWindow(hWnd, 0))->HandleEvents(hWnd, msg, wParam, lParam);
}


So now we should have a nice window appeared on our screen. If not, initialize you data members!
I initialized my data members on a default size 640*480 and title: Default Window

While I was re-programming my framework I found something cool but strange at the same time..

return ((Window*)GetWindow(hWnd, 0))->HandleEvents(hWnd, msg, wParam, lParam);


This should crash normally but it doesn't. blink.png
I never allocated that window, or received a pointer of an existing pointer and still. The HandleEvents() method can be called.
I'm sure I'm opening many eyes right now... Yes have a clear look at the code! tongue.png
I thought if was the SetFocus(); method at the start but they make no difference at all. Also you can leave out the "static" keyword. Still doesn't crash.

So this is creating new possibilities I think? You don't need a singleton anymore to call the HandleEvents. Or a static global pointer of your own class. Everything can be done now through this method.



So thank you for your time ladies and gentlemen!! Now I'm going to write the system and graphics class for the next entry. So be sure to have a look! wink.png You can also follow this blog to make it easier. And so I also know people are interested.
EngineProgrammer
Hello ladies and gentlemen,

Welcome to my journal!
I would like to introduce myself before I get started. My name is Jonathan, student of Digital Arts & Entertainment.
I joined this forum about 2 weeks ago. I've been studying C++ for about 2 years now. And I think I'm ready to go to the next level.
In this journal I'll be writing a game engine and thereafter I'll write a game with that engine.
My engine will be supported by DirectX 11 and other supportive libraries.

If you have any questions or suggestions about my coding, feel free to comment!
For the questions , the answer will be given in the next entry through (Q: A:)
For the suggestions, my response will be given in the next entry through (S: A:)

I've been looking around for some tutorials, information about DirectX, engine structures and I happily share the links with you guys. wink.png
Win32: http://msdn.microsoft.com/en-us/library/bb384843.aspx
Win32 tips&tricks http://www.catch22.net/tuts/win32-tips-tricks#FillArea
Optimizing: http://en.wikibooks.org/wiki/Optimizing_C%2B%2B/Code_optimization/Run-time_support
Game engine structure: http://lspiroengine.com/?p=351
Game engine structure: http://www.ttoprpg.com/gedisc.htm#gecodestruct
DirectX: http://channel9.msdn.com/coding4fun/articles/Beginning-Game-Development-Part-II-Introduction-to-DirectX
DirectX: http://www.directxtutorial.com/Tutorial11/tutorials.aspx
DirectX: http://www.rastertek.com/tutindex.html

In this entry I'm not going to post any code though. This is just the opening for a nice journal. rolleyes.gif
Sign in to follow this  
Followers 0