DirectX 9.0c Game Development Journal of RPG Programming Self-learning log 16:drawing with DirectX Graphics (drawing with DirectX graphic) (10–12 section)

Source: Internet
Author: User


This article by Harry _ Spider-Man original, reproduced please indicate the source! If you have any questions, please contact [email protected]

This time we continue to tell Jim Adams old brother's RPG Programming book Second edition of Chapter 10th: particles (particles), section 11th: Depth Sorting and z-buffering (deep sort and Z-cache), and section 12th: Working with Viewports (using viewports). The two sections are not much, so put it in one issue.

Original translation:

===============================================================================

2.10 particles ( particle)

The Big Bang, the smoke traces, and even the tiny Martians following a hurdling(unaware of the Why did translation) Magic Missile's tail are a masterpiece of special effects called particles (particles). Particles follow the same technology as Billboard technology and are equally simple to use. To use particles, you create polygons that are mapped by smoke, flames, Mars, or any graphics you want to use. At the right time, you enable alpha blending (optional) and draw the particles so that they face the point of view (using Billboard technology). The final result is an abstract picture of a mixture of objects that you can use to produce some cool effects.

One of the cool things about particles is that they can actually be of any size, because you can create a scaling matrix that combines with the world transformation matrix of a particle polygon. This means that you only need to use a polygon to draw all of your particles, unless the particle's texture changes, and in this case the number of polygons should match the number of textures.

It's time to create a particle image. You can start with a circle, which is solid (opaque) in the center position, and becomes more transparent as it approaches the edge (2.22).



Now, create 4 vertices to use two polygons (for optimization, use a triangle band). The coordinates of the vertices represent the default dimensions of a particle, which you will zoom in later. (Feel the logic of this sentence is wrong Ah!) PS: My translation is no problem. each particle can have different properties, including its color (by using a material).

Then you use this structure (which structure?) ), with a vertex cache containing two polygons (used to create a square) to render the polygon to a three-to-four device. Before being drawn, each particle is placed through its own world matrix (of course, using Billboard technology). You combine the world transformation matrix with the scaling matrix transformation of each particle. Then you set a material (using the Idirect3ddevice9::setmaterial function) to change the color of the particle, and after the group you draw the particle.

Here's an example of creating a particle vertex cache and drawing it to a device:

g_pd3ddevice = pre-initialized DeviceObject//define a custom vertex structure and descriptortypedef struct {floatx,  Y, Z;     Local coordinates Floatu, V; Texture coordinates} Svertex; #define VERTEXFVF (d3dfvf_xyz | D3DFVF_TEX1)//particle vertex buffer and Textureidirect3dvertexbuffer9 *g_pparticlevb =null;idirect3dtexture9 *g_pP Articletexture = NULL;    BOOL setupparticle () {byte*ptr; Svertexverts[4] = {{ -1.0f, 1.0f, 0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f, 1.0f, 0.0f}, { -1.0f, -1.0f, 0.     0f, 0.0f, 1.0f}, {1.0f, -1.0f, 0.0f, 1.0f, 1.0f}};                                           Create particle vertex buffer and stuff in data if (FAILED (G_pd3ddevice->createvertexbuffer ( sizeof (Svertex) *4,0, VERTEXFVF, D3dpool_managed,&g_pparticlevb,     NULL)) return FALSE;     if (FAILED (G_pparticlevb->lock (0,0, (void**) &ptr, 0)) return FALSE; memcpy (ptr,verts, sizeof (Verts));        G_pparticlevb->unlock ();                                                     Get particle Texture d3dxcreatetexturefromfile (g_pd3ddevice, "particle.bmp",    &g_pparticletexture); Returntrue;}
 
BOOL drawparticle (float x, float y, Floatz, float scale) {D3dxmatrix matworld, matview, mattransposed;    D3dxmatrix Mattrans, Matscale;     D3DMATERIAL9 D3DM;    Set render states (alpha blending and attributes) G_pd3ddevice->setrenderstate (d3drs_alphablendenable,true); G_pd3ddevice->setrenderstate (D3drs_srcblend, d3dblend_s    Rcalpha);     G_pd3ddevice->setrenderstate (D3drs_destblend,d3dblend_one);     Turn on ambient lighting g_pd3ddevice->setrenderstate (D3DRS_AMBIENT,0XFFFFFFFF);                                                  Set stream source to particle vertex buffer G_pd3ddevice->setstreamsource (0,g_pparticlevb, 0,     sizeof (Svertex));     Set vertex shader to particle type G_PD3DDEVICE->SETFVF (VERTEXFVF);     Set Texture g_pd3ddevice->settexture (0,g_pparticletexture);    Set the particle color zeromemory (&d3dm,sizeof (D3DMATERIAL9)); D3DM. Diffuse.R= D3DM.    AMBIENT.R = 1.0f; D3DM. Diffuse.g= D3DM.    AMBIENT.G = 1.0f; D3DM. Diffuse.b= D3DM.    ambient.b = 0.0f; D3DM. Diffuse.a= D3DM.    AMBIENT.A = 1.0f;     G_pd3ddevice->setmaterial (&D3DM);     Build Scaling Matrix d3dxmatrixscaling (&matscale,scale, scale, scale);     Build translation Matrix d3dxmatrixtranslation (&mattrans,x, y, z);    Build the Billboard Matrix G_pd3ddevice->gettransform (D3dts_view,&matview);     D3dxmatrixtranspose (&mattransposed,&matview); Combine matrices to form World Translation Matrix D3DXMatrixMultiply (&matworld,&matscale, &mattransposed    );     D3DXMatrixMultiply (&matworld,&matworld, &mattrans);     Set World Transformation G_pd3ddevice->settransform (D3dts_world,&matworld);     Draw particle g_pd3ddevice->drawprimitive (d3dpt_trianglestrip,0, 2);     Turn off alpha blending g_pd3ddevice->setrenderstate (d3drs_alphablendenable,false); return TRUE;}

These two functions show how to create a vertex cache and texture for the particles and draw the actual particles. The code for a complete particle sample is rather verbose. I just want to show you how to manipulate a single particle.

If you want a complete sample application that shows the use of particles at a higher level, consult the particle item in the book's CD-ROM (under the \bookode\chap02\particle directory). (Don't worry, I'll send out the source code and the updated code.) )

===============================================================================

Now is the time to give the code! But sadly, I don't really understand the logic of this program, it looks quite complicated. In addition, I did not actually make any essential changes to this code. Here's what the program does when it runs:



Here is the address of the code download:

Particle code

===============================================================================

2.11 Depth sortingand z-buffering ( deep sort and z - cache )

When you render a polygon mesh object into a scene, objects farther away from the observer need to be blocked by nearby objects, which quickly becomes apparent. This is called deep sort (depth sorting) and is implemented in two ways.

The first method is called the painter's algorithm (painter ' s algorithm). This method decomposes the objects into their own polygons and sorts them from back to front, then draws them in this order (2.23). Drawing with this method ensures that a polygon is always drawn in front of the polygon behind it.



The second method of deep sorting is also the most used method for graphics hardware devices, called the z - cache method (Z-buffer). This method works on a pixel basis, and each pixel has a Z-value (distance from the observer)(in fact, the distance from the Observer along the z - axis).

When each pixel is drawn, the renderer first checks to see if a pixel with a smaller Z-value is already there. If not, then the pixel will be drawn, and if so, then the pixel will be skipped. You can see this concept in Figure 2.23.

Most accelerated graphics cards have a built-in Z-cache, so the Z-cache method is the way we choose to sort in depth. The simplest way to use the Z-cache in your application is to initialize it when you create your device object and set the Display method (presentation methods).

You do this: first use the appropriate D3dformat settings to select the Z-cache precision (16-bit, 24-bit, or 32-bit). Then you'll find a lot of settings for the z-cache, but I'll only consider both D3DFMT_D16 (16-bit) and D3DFMT_D32 (32-bit).

You use different precision for two reasons-consider storage space (storage) and consider quality (quality). In terms of storage space, the 32-bit z-cache consumes much more space than the 16-bit z-cache, so try to use the 16-bit z-cache where possible.

In terms of quality, using a 16-bit z-cache for objects that are particularly close to each other can sometimes cause the wrong pixels to be drawn because of the lack of precision. Instead of using a 32-bit z-cache, you can solve the problem of precision, but pay the cost of double memory. But you don't have to worry: in a fast-response (fast-action) game world, speed and optimization are more important, so always use the 16-bit Z-cache!

Back to the creation of the display (presentation), in your application you can add the following two lines to enable the Z-cache:

D3DP. EnableAutoDepthStencil = TRUE;D3DP. Autodepthstencilformat = d3dfmt_d16;//or d3dfmt_d32

Now you can continue with your initialization routines. When you are ready to use the Z-cache for rendering (it doesn ' t kick on automatically, I guess "it doesn't work automatically" ), you must set the appropriate rendering state:

g_pd3ddevice = pre-initialized DeviceObject//To turn on Z-buffer, Use:g_pd3ddevice->setrenderstate (D3DRS_ZENABLE , d3dzb_true); To turn off Z-buffer, Use:g_pd3ddevice->setrenderstate (D3drs_zenable,d3dzb_false);


Attention

===============================================================================

While it seems logical to keep the Z-cache open, it can be a bit faster to turn it off when you don't need it. When you draw a graphic onto the screen, such as a button, you need complete control over where to draw something, so turn the Z-cache on or off when you feel it is appropriate.

===============================================================================

If you have already tried the new Z-cache feature, you may have found something unusual. For example, the screen does not update after a few frames, or objects that are too far away are cropped. This is because you must clear the Z-cache before each frame, and you need to re-tune your projection matrix to achieve the distance setting.

To clear the Z-cache before each frame, rewrite the call to your Idirect3ddevice9::clear function as follows:

G_pd3ddevice->clear (0, NULL,                                                      d3dclear_target| D3dclear_zbuffer,                              D3dcolor_rgba (0.0f,0.0f, 0.0f, 0.0f), 1.0f, 0);

Note the previously added d3dclear_zbuffer tag. This tag tells the purge function that it has to clear the Z-cache to the given value (the fifth parameter, which is 1.0f). This value can be changed from 0.0 (the minimum z-cache depth) to 1.0 (the maximum z-cache depth).

Using the value 1.0 tells the purge function to set all the depth values to their maximum values. Use 0.5 If you want to erase the Z-cache by half of the maximum value. The only question is, what does the maximum mean?

The Z-cache represents the distance from the Observer point (in fact, the longitudinal distance), so when the rendering is performed, objects farther away than the largest observation distances (and those that are too close) are not drawn. When you call (through D3DX) a function that creates a projection matrix, you set the minimum and maximum viewing distance, as shown in the following code:

Set a min distance of 1.0 and a Max Of1000.0d3dxmatrixperspectivefovlh (&MATRIXPROJ,D3DX_PI/4,                                           1.0f,1.0f, 1000. 0f);

The last two values you want to adjust are the minimum and maximum distances, respectively. Experiment with these values to see which values are best for you, and as long as you remember, the greater the distance between the minimum and maximum distances, the worse the z-cache quality. In general, set the minimum distance to 1.0 and the maximum distance to 1,000, 2,000, or 5,000.

===============================================================================

The book's accompanying CD-ROM on this topic gives a program called ZBuffer. But I made a big change in it, turning it into two squares with transparent textures rotating around different axes (so use the previous Alpha test knowledge). Here's what the program does when it runs:



There are two partially transparent, PNG-formatted pictures. Because the picture buckle is relatively sloppy, so looks not very good, everybody many magnanimous ha!

Here is the code, which contains the original code and My Code:

ZBuffer Code

===============================================================================

2.12 Working withviewports ( with viewport )

Sometimes, you want to render a graphic to a part of the display, just like a small window in the main application window. The main viewport (the main viewport) generally covers the entire display, but when you need it, you can change the viewport size to cover a sub-area of the screen (like rendering to a radar, car rearview mirror, or any other "on-screen" screen).

To set up a viewport, you first populate a D3DVIEWPORT9 structure with the coordinates and dimensions of the new viewport you want to use:

typedef struct _D3DVIEWPORT9 {  DWORD X;      Left X coordinate of viewport  DWORD Y;      Top Y coordinate of viewport  DWORD Width;  Width of viewport  DWORD height;//Height of viewport  float MinZ;   0.0  float MaxZ;   1.0} D3dviewport9;

After you set the structure with the appropriate data, you call the function Id3ddevice9::setviewport function to tell Direct3D to use it, as shown in the following code:

Pd3ddevice = pre-initialized//Create a viewportd3dviewport9 D3DVP = {0,0, +, +, 0.0f,1.0f}; Set the new Viewportpd3ddevice->setviewport (&D3DVP);

Starting here (after calling SetViewport), all the graphics are rendered into the viewport window you defined. After you run out of this new viewport, you rebuild the old viewport. To get the old viewport settings so that they can be rebuilt later, you call the Id3ddevice9::getviewport function as follows:

Pd3ddevice = pre-initialized device D3dviewport9 oldviewport;  Get Old viewport Settingspd3ddevice->getdevice (&oldviewport),//Get old viewport//... change viewport settings As needed//Restore old Viewportpd3ddevice->setdevice (&oldviewport);

===============================================================================

Well, we finally translated the contents! The contents of this section are not difficult, but the first particles are still worth taking the time to study!

Now we have finished the 2nd chapter of the more than half content! The rest is basically the grid model, and this is the more advanced technology. You may ask: Why is the 2nd chapter so long? What time is it going to be? Wouldn't it be more difficult to follow the chapters? Don't worry, you know, in fact, Jim Adams old brother in this 2nd chapter of the People Frank D. Luna spent several chapters on the content to tell the things! If you do not talk about the HLSL language, basically this 2nd chapter of the content covers the "dragon book" the first version of all the content! Isn't it cool?!

But here is a bit of haste, so some places do not understand is natural, we have a lot of reference to "dragon book" second Edition ha!

In addition, although I did not look closely at the following, but can be very responsible to tell you, the later chapters (at least I will tell the chapters) of the content of this chapter is not difficult! This reminds me of a famous saying: The development of the game is a very difficult thing, but it will be with your development progress and become more and more easy! This is what Allen Sherrod, the author of Ultimate Game programming with DirectX, said.


DirectX 9.0c Game Development Journal of RPG Programming Self-learning log 16:drawing with DirectX Graphics (drawing with DirectX graphic) (10–12 section)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.