Чтение онлайн

на главную - закладки

Жанры

DirectX 8. Начинаем работу с DirectX Graphics

Поздняков Константин

Шрифт:

D3DXMATRIX Position;

D3DXMatrixTranslation(&Position, 50.0f, 0.0f, 0.0f);

g_pd3dDevice->SetTransform(D3DTS_WORLD, &Position);

This creates a matrix that moves the panel 50 pixels in the X direction and tells the device to apply that transform. This could be wrapped into a function like MoveTo(X, Y), which I won't actually give the code for. Earlier I said to remember the fact that the vertex code specified the vertices around the origin. Because we did that, translating (moving) the position moves the center of the panel. If you are more comfortable with moving the upper left or some other corner, change the way the vertices are specified. You could also create different coordinate systems by correcting the parameters sent to the MoveTo function. For example, our viewport currently goes from —100 to +100. If I wanted to use MoveTo as if it were going from 0 to 200, I could simply correct for it in my call to D3DXMatrixTranslation by subtracting 100 from the X position. There are many ways to quickly change this to meet your specific needs, but this will provide a good basis for experimentation.

Other Matrix Operations

There are many other matrix operations that will affect the panel. Perhaps the most interesting are scaling and rotation. There are D3DX functions for creating these matrices as well. I'll leave the experimenting up to you, but here are a few hints. Rotation about the Z-axis will create rotation on the screen. Rotating about X and Y will look like you are shrinking Y and X. Also, the way you apply multiple operations is through multiplication and then sending the resulting matrix to the device:

D3DXMATRIX M = M1 * M2 * M3 * M4;

g_pd3dDevice->SetTransform(D3DTS_WORLD, &M);

But, remember that the product of matrix multiplication is dependent on the order of the operands. For instance, Rotation * Position will move the panel and then rotate it. Position * Rotation will cause an orbiting effect. If you string together several matrices and get unexpected results, look closely at the order.

As you become more comfortable, you may want to experiment with things like the texture matrix, which will allow you to transform the texture coordinates. You could also move the view matrix to affect your coordinate system. One thing to remember: locks are very costly, always look to things like matrices before locking your vertex buffers.

Wrapping Up

Looking at all the code listed here, this is really a long, drawn out way to do a blit, but the nice thing is that most of this can be wrapped into tidy functions or classes that make all this a one time cost for long term benefit. Please remember that this is presented in a very bare bones, unoptimized way. There are many ways to package this to get maximum benefit. This method should be the optimal way to create 2D applications on current and coming hardware and also will pay off in terms of the effects that you can implement very easily on top of it. This approach will also help you blend 2D with 3D because, aside from some matrices, the two are the same. The code was easily adapted from 2D work that I did in OpenGL, so you could even write abstract wrappers around the approach to support both APIs. My hope is that this will get people started using DX8 for 2D work. Perhaps in future articles I will talk about more tricks and effects.

DirectDraw The Easy Way

by Johnny Watson

This article describes how to setup DirectDraw displays and surfaces with minimal effort using the common libs included in the DirectX SDK. This can be particularly helpful for those who want a quick way of doing things, while still maintining control of their application's basic framework. Please note the fact that these classes abstract quite a few things, and I highly recommend peering into their functions at some point to see how things are done on a lower level.

Setting it Up

For this article, I'm assuming you have Microsoft Visual C++, and the DirectX 8.1 SDK. If not, please adapt to portions of this article accordingly. Anyway, start up Visual C++, and create a new Win32 Application project. Then go into your DirectX SDK's samples\multimedia\common\include directory, and copy dxutil.h and ddutil.h to your project folder. Then go to samples\multimedia\common\src, and do the same with dxutil.cpp, and ddutil.cpp. Add the four files to your project, and link to the following libraries: dxguid.lib, ddraw.lib, winmm.lib. Now, you create a new C++ source file document, and add it to your project as well. This will be the file we'll work with throughout the tutorial.

The Code

Now that we've got that out of the way, we can get down and dirty with some actual code! Let's start off with this:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>

#include "dxutil.h"

#include "ddutil.h"

Standard procedure here. We #define WIN32_LEAN_AND_MEAN, so all that icky MFC stuff doesn't bloat our program (just a good practice if you aren't using MFC). Then we include dxutil.h, and ddutil.h, the two centerpieces of this article. They provide shortcut classes to make programming with DirectX in general less taxing.

//globals

bool g_bActive = false;

CDisplay *g_pDisplay = NULL;

CSurface *g_pText = NULL;

//function prototypes

bool InitDD(HWND);

void CleanUp;

void GameLoop;

Pretty self explanatory. Our first global, g_bActive, is a flag to let our application know whether or not it's okay to run the game. If we didn't have this flag, our application could potentially attempt to draw something onto our DirectDraw surface after it's been destroyed. While this is usually a problem at the end of the program where it isn't that big of a deal, it generates an illegal operation error, and we don't want that, now do we? g_pDisplay is our display object. CDisplay is the main class in ddutil. It holds our front and back buffers, as well as functionality for accessing them, drawing surfaces onto them, creating surfaces, etc. g_pText is our text surface. We will draw text onto this surface (as you've probably figured out), and blit it onto our screen. Note how both objects are pointers, and are initialized to NULL.

Now for the function prototypes. InitDD simply initializes DirectDraw. Thanks to the DDraw Common Files, this is a fairly simple procedure (but we'll get to that later). CleanUp calls the destructor to our g_pDisplay object, which essentially shuts down DDraw, and cleans up all of our surfaces. GameLoop is obviously where you'd put your game.

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

 switch(uMsg) {

 case WM_CREATE:

InitDD(hWnd);

g_bActive=true;

break;

 case WM_CLOSE:

g_bActive=false;

CleanUp;

DestroyWindow(hWnd);

break;

 case WM_DESTROY:

PostQuitMessage(0);

break;

 case WM_MOVE:

g_pDisplay->UpdateBounds;

break;

Поделиться:
Популярные книги

Печать Пожирателя

Соломенный Илья
1. Пожиратель
Фантастика:
попаданцы
аниме
сказочная фантастика
фэнтези
5.00
рейтинг книги
Печать Пожирателя

Привет из Загса. Милый, ты не потерял кольцо?

Лисавчук Елена
Любовные романы:
современные любовные романы
5.00
рейтинг книги
Привет из Загса. Милый, ты не потерял кольцо?

Мастер 2

Чащин Валерий
2. Мастер
Фантастика:
фэнтези
городское фэнтези
попаданцы
технофэнтези
4.50
рейтинг книги
Мастер 2

Нечто чудесное

Макнот Джудит
2. Романтическая серия
Любовные романы:
исторические любовные романы
9.43
рейтинг книги
Нечто чудесное

Клан

Русич Антон
2. Долгий путь домой
Фантастика:
боевая фантастика
космическая фантастика
5.60
рейтинг книги
Клан

Имя нам Легион. Том 3

Дорничев Дмитрий
3. Меж двух миров
Фантастика:
боевая фантастика
рпг
аниме
5.00
рейтинг книги
Имя нам Легион. Том 3

Запасная дочь

Зика Натаэль
Фантастика:
фэнтези
6.40
рейтинг книги
Запасная дочь

Убивать чтобы жить 7

Бор Жорж
7. УЧЖ
Фантастика:
героическая фантастика
космическая фантастика
рпг
5.00
рейтинг книги
Убивать чтобы жить 7

У врага за пазухой

Коваленко Марья Сергеевна
5. Оголенные чувства
Любовные романы:
остросюжетные любовные романы
эро литература
5.00
рейтинг книги
У врага за пазухой

Кодекс Охотника. Книга XXI

Винокуров Юрий
21. Кодекс Охотника
Фантастика:
фэнтези
попаданцы
аниме
5.00
рейтинг книги
Кодекс Охотника. Книга XXI

Генерал Скала и ученица

Суббота Светлана
2. Генерал Скала и Лидия
Любовные романы:
любовно-фантастические романы
6.30
рейтинг книги
Генерал Скала и ученица

Оцифрованный. Том 1

Дорничев Дмитрий
1. Линкор Михаил
Фантастика:
боевая фантастика
попаданцы
аниме
5.00
рейтинг книги
Оцифрованный. Том 1

Его маленькая большая женщина

Резник Юлия
Любовные романы:
современные любовные романы
эро литература
8.78
рейтинг книги
Его маленькая большая женщина

Хуррит

Рави Ивар
Фантастика:
героическая фантастика
попаданцы
альтернативная история
5.00
рейтинг книги
Хуррит