#include <Windows.h>
 
#include <thread>
 
#include <d3d9.h>
#pragma comment (lib, "d3d9.lib")
 
 
namespace Window {
	LPCSTR Title = "DX9 Blue Window";
	LPCSTR ClassName = "DirectX9Window";
 
	WNDCLASS Class = {};
	HWND Handle = {};
 
	LRESULT CALLBACK Procedure(HWND, UINT, WPARAM, LPARAM );
}
 
namespace DirectX {
	LPDIRECT3D9 Interface = {};
	LPDIRECT3DDEVICE9 Device = {};
	D3DPRESENT_PARAMETERS Presenter = {};
 
	INT Run = 1;
	VOID Procedure();
}
 
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, INT) {
	Window::Class = { CS_VREDRAW | CS_HREDRAW, Window::Procedure, 
		0, 0, hInstance, LoadIcon(nullptr, IDI_APPLICATION), 
		LoadCursor(nullptr, IDC_ARROW), 
		(HBRUSH)COLOR_WINDOW, nullptr,	Window::ClassName };
	RegisterClass(&Window::Class);
	Window::Handle = CreateWindow(Window::Class.lpszClassName, 
		Window::Title, WS_OVERLAPPEDWINDOW, 
		50, 50, 1024, 768, nullptr, nullptr, hInstance, nullptr);
	ShowWindow(Window::Handle, 1);
	UpdateWindow(Window::Handle);
	DirectX::Interface = Direct3DCreate9(D3D_SDK_VERSION);
	DirectX::Presenter.Windowed = TRUE;
	DirectX::Presenter.SwapEffect = D3DSWAPEFFECT_DISCARD;
	DirectX::Presenter.hDeviceWindow = Window::Handle;
	DirectX::Interface->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		Window::Handle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
		&DirectX::Presenter, &DirectX::Device);
 
	MSG msg = { };
 
	std::thread Renderer (DirectX::Procedure);
 
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
 
	DirectX::Run = 0;
 
	Renderer.join();
 
	return 1;
}
 
 
LRESULT CALLBACK Window::Procedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	if (msg == WM_DESTROY) { 
		PostQuitMessage(0); 
		return 0; 
	}
 
	return DefWindowProc(hWnd, msg, wParam, lParam);
}
 
VOID DirectX::Procedure() {
	while(DirectX::Run) { 
		DirectX::Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);
		DirectX::Device->BeginScene();
		/* ... Scene ... */
		DirectX::Device->EndScene();
		DirectX::Device->Present(NULL, NULL, NULL, NULL);
	}
}