#include <d3d9.h>

LPDIRECT3D9                         g_pD3D      = NULL;
LPDIRECT3DDEVICE9             g_pD3DDevice  = NULL;

HRESULT InitialiseD3D(HWND hWnd)
{
  //首先创建主要的D3D对象.如果创建成功我们将会得到一个指向IDirect3D8接口的指针
  g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
  if(g_pD3D == NULL)
  {
    return E_FAIL;
  }

  //获取当前的显示模式
  D3DDISPLAYMODE d3ddm;
  if(FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
  {
    return E_FAIL;
  }

  //创建一个结构来放置我们设备的设置信息
  D3DPRESENT_PARAMETERS d3dpp;
  ZeroMemory(&d3dpp, sizeof(d3dpp));

  //设置该结构体属性值
  //我们想让我们的程序窗口化,并且设置了后缓冲的格式以匹配我们当前的显示模式
  d3dpp.Windowed      = TRUE;
  d3dpp.SwapEffect    = D3DSWAPEFFECT_COPY;
  d3dpp.PresentationInterval=D3DPRESENT_INTERVAL_DEFAULT;
  d3dpp.BackBufferFormat  = d3ddm.Format;

  //创建一个Direct3D设备
  if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
    D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice)))
  {
    return E_FAIL;
  }

  return S_OK;
}

void Render()
{
  if(g_pD3DDevice == NULL)
  {
    return;
  }

  //清除后缓冲为绿色
  g_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 255, 0), 1.0f, 0);

  //开始场景
  g_pD3DDevice->BeginScene();

  //我们的游戏对象的渲染放到这里

  //结束场景
  g_pD3DDevice->EndScene();

  //翻动前后缓冲以便后缓冲中渲染的一切能够显示在屏幕(前缓冲)上。
  g_pD3DDevice->Present(NULL, NULL, NULL, NULL);
}

void CleanUp()
{
  if(g_pD3DDevice != NULL)
  {
    g_pD3DDevice->Release();
    g_pD3DDevice = NULL;
  }

  if(g_pD3D != NULL)
  {
    g_pD3D->Release();
    g_pD3D = NULL;
  }
}

void GameLoop()
{
  //进入游戏循环
  MSG msg;
  BOOL fMessage;

  PeekMessage(&msg, NULL, 0U, 0U, PM_NOREMOVE);

  while(msg.message != WM_QUIT)
  {
    fMessage = PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE);

    if(fMessage)
    {
      //处理消息
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    else
    {
      //没有要处理的消息,所以渲染当前场景
      Render();
    }

  }
}

//窗口消息处理
LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch(msg)
  {
  case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
    break;
  case WM_KEYUP:
    switch (wParam)
    {
    case VK_ESCAPE:
      //用户已经按了ESC键,所以退出
      DestroyWindow(hWnd);
      return 0;
      break;
    }
    break;

  }

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

//应用程序入口点
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT)
{
  //注册窗口类
  WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WinProc, 0L, 0L,
    GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
    "DX Project 1", NULL};
  RegisterClassEx(&wc);

  //创建应用程序的窗口
  HWND hWnd = CreateWindow("DX Project 1", "www.andypike.com: Tutorial 1",
    WS_OVERLAPPEDWINDOW, 50, 50, 500, 500,
    GetDesktopWindow(), NULL, wc.hInstance, NULL);

  //初始化 Direct3D
  if(SUCCEEDED(InitialiseD3D(hWnd)))
  {
    //显示我们的窗体
    ShowWindow(hWnd, SW_SHOWDEFAULT);
    UpdateWindow(hWnd);

    //启动游戏运行:进入游戏循环
    GameLoop();
  }

  CleanUp();

  UnregisterClass("DX Project 1", wc.hInstance);

  return 0;
}