Выбрать главу

 MyVert v[3];

 v[0].x =-0.5f;  v[0].y =-0.5f;  v[0].z = 0.5f;

 v[1].x =-0.5f;  v[1].y = 0.5f;  v[1].z = 0.5f;

 v[2].x = 0.5f;  v[2].y = 0.5f;  v[2].z = 0.5f;

 v[0].Color = D3DCOLOR_XRGB(255,0,0); // красный

 v[1].Color = D3DCOLOR_XRGB(0,255,0); // зеленый

 v[2].Color = D3DCOLOR_XRGB(0,0,255); // синий

 // Закрашиваем экран синим цветом

 DWORD dwBlue = D3DCOLOR_XRGB(0,0,128);

 pDevice->Clear(0, NULL, D3DCLEAR_TARGET, dwBlue, 1.0f, 0);

 pDevice->BeginScene();

  // Поскольку мы не используем освещение для треугольника,

  // отключаем его

  pDevice->SetRenderState(D3DRS_LIGHTING, FALSE);

  // Просчет объектов всегда между BeginScene и EndScene

  pDevice->SetVertexShader(D3DFVF_MYVERT);

  pDevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 1, v, sizeof(MyVert));

 pDevice->EndScene();

 pDevice->Present(0, 0, 0, 0);

}

Если наше приложение больше ничего не будет выводить на экран, то некоторую часть кода из функции Render() можно вынести за её пределы, а именно, инициализацию массива v, выключение освещения и установку типа просчитываемых вершин.

Ниже приведён код, который больше относится к windows-программированию. Создаётся главное окно приложения и ведётся обработка сообщений:

// функция обрабатывающая сообщения главного окна приложения

LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {

 switch (msg) {

 case WM_DESTROY:

  PostQuitMessage(0);

  return 0;

 }

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

}

INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT) {

 WNDCLASSEX wc = {

  sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,

  GetModuleHandle(0), 0, 0, 0, 0, "FirstDX_cl", 0

 };

 RegisterClassEx(&wc);

 // Создание главного окна приложения

 HWND hWnd = CreateWindow("FirstDX_cl", "FirstDX",

  WS_OVERLAPPEDWINDOW, 100, 100, 160, 160,

  GetDesktopWindow(), NULL, wc.hInstance, NULL);

 if (Init(hWnd)) {

  ShowWindow (hWnd, SW_SHOWDEFAULT);

  UpdateWindow(hWnd);

  MSG msg;

  ZeroMemory(&msg, sizeof(msg));

  while (msg.message != WM_QUIT) {

   if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {

    TranslateMessage(&msg);

    DispatchMessage(&msg);

   } else Render();

  }

 }

 ReleaseAll();

 UnregisterClass("FirstDX_cl", wc.hInstance);

 return 0;

}

Функция Render() вызывается всегда, когда не приходят какие-либо сообщения, то есть перерисовка кадра происходит практически постоянно. Функции Init() и ReleaseAll() описаны в предыдущей части урока.

Теперь есть всё, чтобы вы смогли скомпилировать и запустить наш пример. Не забудьте добавить библиотеку d3d8.lib в ваш проект, чтобы линковщик смог найти реализации функций Direct3D.

Поведал: Ваткин.

GameDev.net 

2D Rendering in DirectX 8

by Kelly Dempski Background

I have been reading alot of questions lately related to DirectX 8 and the exclusion of DirectDraw from the new API. Many people have fallen back to DX7. I can understand people using DX7 if they have alot of experience with that API, but many of the questions seem to be coming from people who are just learning DX, and they are stuck learning an old API. People have argued that many people don't have 3D hardware, and therefore D3D would be a bad alternative for DirectDraw. I don't believe this is true - 2D rendering in D3D requires very little vertex manipulation, and everything else boils down to fillrate. In short, 2D rendering in D3D on 2D hardware should have pretty much the same performance as DirectDraw, assuming decent fillrate. The advantage is that the programmer can learn the newest API, and performance on newer hardware should be very good. This article will present a framework for 2D rendering in DX8 to ease the transition from DirectDraw to Direct3D. In each section, you may see things that you don't like ("I'm a 2D programmer, I don't care about vertices!"). Rest assured, if you implement this simple framework once, you'll never think about these things again.

Getting Started

Assuming you have the DX8 SDK, there are a couple tutorials that present how to create a D3D device and set up a render loop, so I don't want to spend alot of time on that. For the purposes of this article, I'll talk about the tutorial found in [DX8SDK]\samples\Multimedia\Direct3D\Tutorials\Tut01_CreateDevice, although you can add it to anything. To that sample, I'll add the following functions:

void PostInitialize(float WindowWidth, float WindowHeight) — this function is called by the app after everything else is set up. You've created your device and initialized everything. If you're following along with the Tutorial code, WinMain looks like this:

if (SUCCEEDED(InitD3D(hWnd))) {

 PostInitialize(200.0f, 200.0f);

 // This is my added line. The values of

 // 200.0f were chosen based on the sizes

 // used in the call to CreateWindow.

 ShowWindow(hWnd, SW_SHOWDEFAULT);

 …

void Render2D() — This function is called each time you want to render your scene. Again, the Render function of the Tutorial now looks like this:

VOID Render() {

 if (NULL == g_pd3dDevice) return;

 // Clear the backbuffer to a blue color

 g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0);

 // Begin the scene

 g_pd3dDevice->BeginScene();

 Render2D(); //My added line…

 // End the scene

 g_pd3dDevice->EndScene();

 // Present the backbuffer contents to the display

 g_pd3dDevice->Present(NULL, NULL, NULL, NULL);

}

OK, that's our shell of an application. Now for the good stuff…

Setting Up for 2D drawing in D3D

NOTE: This is where we start talking about some of the nasty math involved with D3D. Don't be alarmed - if you want to, you can choose to ignore most of the detailsЕ Most Direct3D drawing is controlled by three matrices: the projection matrix, the world matrix, and the view matrix. The first one we'll talk about is the projection matrix. You can think of the projection matrix as defining the properties of the lens of your camera. In 3D applications, it defines things like perspective, etc. But, we don't want perspective - we are talking about 2D!! So, we can talk about orthogonal projections. To make a long story very short, this allows us to draw in 2D without all the added properties of 3D drawing. To create an orthogonal matrix, we need to call D3DXMatrixOrthoLH and this will create a matrix for us. The other matrices (view and world) define the position of the camera and the position of the world (or an object in the world). For our 2D drawing, we don't need to move the camera, and we don't want to move the world for now, so we'll use an identity matrix, which basically sets the camera and world in a default position. We can create identity matrices with D3DXMatrixIdentity. To use the D3DX functions, we need to add: