18
DirectX 9 Laboratory guideline 1 / 18 Table of Content 0 Document History.................................................................................................................... 1 1 References ............................................................................................................................... 3 2 Visual Studio setup Windows 10 ............................................................................................ 3 2.1 Install DirectX 9 SDK 2010................................................................................................. 3 2.2 Project setup inside Visual Studio 2017 (or higher) ............................................................ 3 3 Surfaces ................................................................................................................................... 5 3.1 Creating surfaces ............................................................................................................... 5 3.2 Load image from file to surface .......................................................................................... 5 3.3 Copying Surfaces............................................................................................................... 5 3.4 Exercises ........................................................................................................................... 6 4 Direct3D transform matrices / Vertex Buffer / Index Buffer .................................................. 6 4.1 FVF Flexible vertex format .............................................................................................. 6 4.2 Vertex Buffer ...................................................................................................................... 6 4.2.1 Declare/Create ........................................................................................................... 6 4.2.2 Accesing the contents ................................................................................................ 7 4.2.3 Rendering ................................................................................................................... 7 4.3 Index buffer ....................................................................................................................... 8 4.3.1 Declare/Create ........................................................................................................... 8 4.3.2 Accesing the content .................................................................................................. 9 4.3.3 Rendering ................................................................................................................... 9 4.4 Transforms....................................................................................................................... 10 4.4.1 World transform ........................................................................................................ 10 4.4.2 View transform ......................................................................................................... 10 4.4.3 Projection transform ................................................................................................. 11 4.5 Exercises ......................................................................................................................... 12 5 Texture.Lights.Sprite............................................................................................................. 13 5.1 Texture ............................................................................................................................ 13 5.2 Lights ............................................................................................................................... 14 5.3 Sprite ............................................................................................................................... 16 5.4 Exercises ......................................................................................................................... 16 6 Meshes ................................................................................................................................... 16 6.1 Exercises ......................................................................................................................... 18 7 Camera ................................................................................................................................... 18 7.1 Exercise ........................................................................................................................... 18 8 Direct Input & Direct play ...................................................................................................... 18 0 Document History Removed windows 7 history Updated for Windows 10 / VS 2017 or VS 2019 Various changes inside the theory

DirectX 9 Lab Manual - Google Sites: Sign-in

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Laboratory guideline

1 / 18

Table of Content

0 Document History.................................................................................................................... 1 1 References ............................................................................................................................... 3 2 Visual Studio setup Windows 10 ............................................................................................ 3

2.1 Install DirectX 9 SDK 2010 ................................................................................................. 3 2.2 Project setup inside Visual Studio 2017 (or higher) ............................................................ 3

3 Surfaces ................................................................................................................................... 5 3.1 Creating surfaces ............................................................................................................... 5 3.2 Load image from file to surface .......................................................................................... 5 3.3 Copying Surfaces ............................................................................................................... 5 3.4 Exercises ........................................................................................................................... 6

4 Direct3D transform matrices / Vertex Buffer / Index Buffer .................................................. 6 4.1 FVF – Flexible vertex format .............................................................................................. 6 4.2 Vertex Buffer ...................................................................................................................... 6

4.2.1 Declare/Create ........................................................................................................... 6 4.2.2 Accesing the contents ................................................................................................ 7 4.2.3 Rendering ................................................................................................................... 7

4.3 Index buffer ....................................................................................................................... 8 4.3.1 Declare/Create ........................................................................................................... 8 4.3.2 Accesing the content .................................................................................................. 9 4.3.3 Rendering ................................................................................................................... 9

4.4 Transforms ....................................................................................................................... 10 4.4.1 World transform ........................................................................................................ 10 4.4.2 View transform ......................................................................................................... 10 4.4.3 Projection transform ................................................................................................. 11

4.5 Exercises ......................................................................................................................... 12 5 Texture.Lights.Sprite ............................................................................................................. 13

5.1 Texture ............................................................................................................................ 13 5.2 Lights ............................................................................................................................... 14 5.3 Sprite ............................................................................................................................... 16 5.4 Exercises ......................................................................................................................... 16

6 Meshes ................................................................................................................................... 16 6.1 Exercises ......................................................................................................................... 18

7 Camera ................................................................................................................................... 18 7.1 Exercise ........................................................................................................................... 18

8 Direct Input & Direct play ...................................................................................................... 18

0 Document History

Removed windows 7 history Updated for Windows 10 / VS 2017 or VS 2019 Various changes inside the theory

Page 2: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

2 / 18

Page 3: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

3 / 18

1 References

https://msdn.microsoft.com/en-us/library/windows/desktop/bb219838(v=vs.85).aspx

Advanced 3D game programming with DirectX 9.0 by Peter Walsh.

Beginning DirectX 9 by Wendy Jones

Directx9 Graphics The Definitive Guide To Direct 3d by Alan Thorn

Game institute: http://www.amazon.com/Graphics-Programming-With-Directx-Module/dp/B004B0PK9Q / https://www.gameinstitute.com/

http://www.directxtutorial.com/LessonList.aspx?listid=9

https://msdn.microsoft.com/en-us/library/windows/desktop/bb173380(v=vs.85).aspx

2 Visual Studio setup Windows 10

Prerequisites: - OS : Windows 10 (x86 or x64)

- Visual Studio: 2017 or 2019 installed at least with C++ Component

2.1 Install DirectX 9 SDK 2010

Download the DirectX 9 SDK from here and install it: https://www.microsoft.com/en-us/download/details.aspx?id=6812

2.2 Project setup inside Visual Studio 2017 (or higher)

Additional for all projects ensure the following settings are done: - Under project properties -> VC ++ Directories -> Include – You should have a line similar to the

following one C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include

- Under project properties -> VC ++ Directories -> Lib – You should have a line similar to the following

one C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86

Page 4: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

4 / 18

- - Under project properties -> Linker -> All Options -> Additional Dependencies - You should have a

line only to the following ones

d3dx9.lib d3d9.lib dxguid.lib d3dxof.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ole32.lib winmm.lib Strmiids.lib Quartz.lib

- Under project properties -> Linker -> All Options -> Image has Safe Execution Exception Handles -

You should have a line similar to the following one No (/SAFESEH:NO)

Page 5: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

5 / 18

3 Surfaces

2D images in Direct3D are wrapped by objects called surfaces. Internally, a surface is just a structure that manages image data as a contiguous block of memory. Surfaces can be loaded from files or resources. Surfaces can be copied to and from one another. Probably to use some functions you will need to specify the appropriate include. For e.g. to use D3DXLoadSurfaceFromFile, you will need to include “D3dx9tex.h”

3.1 Creating surfaces

HRESULT IDirect3DDevice9::CreateOffscreenPlainSurface( UINT Width, UINT Height, D3DFORMAT Format, DWORD Pool, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle ); Example: IDirect3DSurface9 *Surface = NULL; d3dDevice->CreateOffscreenPlainSurface(120, 120, D3DFMT_X8R8G8B8, D3DPOOL_SYSTEMMEM, &Surface, NULL);

3.2 Load image from file to surface

HRESULT D3DXLoadSurfaceFromFile( _In_ IDirect3DSurface9* pDestSurface, _In_ const PALETTEENTRY *pDestPalette, _In_ const RECT *pDestRect, _In_ LPCTSTR pSrcFile, _In_ const RECT *pSrcRect, _In_ DWORD Filter, _In_ D3DCOLOR ColorKey, _Inout_ D3DXIMAGE_INFO *pSrcInfo ); E.g. D3DXLoadSurfaceFromFile(Surface, NULL, NULL, PathToBMPFile, NULL,D3DX_FILTER_NONE, 0, NULL);

3.3 Copying Surfaces

Getting the back buffer: HRESULT GetBackBuffer( UINT iSwapChain, // An unsigned integer specifying the swap chain. Default 0 UINT iBackBuffer, //Index of the back buffer object to return. Default 0 D3DBACKBUFFER_TYPE Type,//Should be D3DBACKBUFFER_TYPE_MONO IDirect3DSurface9 **ppBackBuffer //Return value – the address of the backBUffer ); Updating the surface: HRESULT UpdateSurface( IDirect3DSurface9 *pSourceSurface, //source surface const RECT *pSourceRect, // Pointer to a rectangle on the source surface. Specifying NULL for this parameter

causes the entire surface to be copied

IDirect3DSurface9 *pDestinationSurface,//Destination sourface const POINT *pDestPoint//Pointer to the upper left corner of the destination rectangle. Specifying NULL for this parameter causes the

entire surface to be copied. );

Page 6: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

6 / 18

IDirect3DSurface9 *BackBuffer = NULL; d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &BackBuffer); d3dDevice->UpdateSurface(SourceSurface, NULL, BackBuffer, NULL);

3.4 Exercises

I. Load BMP and display it. (Careful if the size of BMP is greater than size of window it will not be

displayed.

II. Create a puzzle game by copying parts and updating parts from surfaces.

4 Direct3D transform matrices / Vertex Buffer / Index Buffer

4.1 FVF – Flexible vertex format

Create a STRUCT that contains the desired attributes for the vertex. Attributes can vary inside a custom vertex. They have to be defined still in an order. struct CUSTOMVERTEX { FLOAT x,y,z; DWORD color; }; struct CUSTOMVERTEX2 { D3DXVECTOR3 position; //Equivalent to having Float X,Y,Z D3DXVECTOR3 normal; DWORD color; FLOAT tu, tv; // Texture coordinates }; CUSTOMVERTEX g_Vertices[] = { { -1.0f,-1.0f, 0.0f, 0xffffff00, }, { 1.0f,-1.0f, 0.0f, 0xffffff00, }, { 0.0f, 1.0f, 0.0f, 0xffffff00, }, }; // Custom flexible vertex format (FVF) describing the custom vertex structure (CUSTOMVERTEX2) #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_NORMAL |D3DFVF_DIFFUSE | D3DFVF_TEX1)

4.2 Vertex Buffer

Area of memory which contains information about vertices

4.2.1 Declare/Create

Declare variable of type IDirect3DVertexBuffer9 (or LPDIRECT3DVERTEXBUFFER9). // Create a vertex buffer. Allocate enough memory in the default memory pool to hold //three CUSTOMVERTEX structures LPDIRECT3DVERTEXBUFFER9 vertexBuffer = null; HRESULT CreateVertexBuffer( [in] UINT Length, [in] DWORD Usage, [in] DWORD FVF, [in] D3DPOOL Pool, [out, retval] IDirect3DVertexBuffer9 **ppVertexBuffer,

Page 7: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

7 / 18

[in] HANDLE *pSharedHandle );

4.2.2 Accesing the contents

You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new vertex data or to read any data it already contains. The IDirect3DVertexBuffer9::Lock method accepts four parameters:

- The first, OffsetToLock, is the offset into the vertex data.

- The second parameter is the size, measured in bytes, of the vertex data.

- The third parameter accepted is the address of a pointer that points to the vertex data, if the call

succeeds.

- The last parameter, Flags, tells the system how the memory should be locked. Specify constants for

the Flags parameter according to the way the vertex data will be accessed.

Make sure the value chosen for D3DUSAGE matches the value chosen for D3DLOCK. For example, if you are creating a vertex buffer with write access only, it doesn't make sense to try to read the data by specifying D3DLOCK_READONLY. Wisely using these flags allows the driver to lock the memory and provide the best performance, given the requested access type. VOID* pVertices; vertexBuffer->Lock(0, sizeof(g_Vertices), (void**)&pVertices, 0) memcpy(pVertices, g_Vertices, sizeof(g_Vertices)); vertexBuffer->Unlock();

4.2.3 Rendering

The first parameter of IDirect3DDevice9::SetStreamSource tells Direct3D the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the offset from the beginning of the stream to the beginning of the vertex data, in bytes. The fourth parameter is the stride of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the stride of the component. d3dDevice->SetStreamSource(0, vertexBuffer, 0, sizeof(CUSTOMVERTEX));

The next step is to inform Direct3D which vertex shader to use by calling the IDirect3DDevice9::SetVertexShader method. The following sample code sets an FVF code for the vertex shader. This informs Direct3D of the types of vertices it is dealing with. d3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);

After setting the stream source and vertex shader, any draw methods will use the vertex buffer. The code example below shows how to render vertices from a vertex buffer with the IDirect3DDevice9::DrawPrimitive method. HRESULT DrawPrimitive( [in] D3DPRIMITIVETYPE PrimitiveType, [in] UINT StartVertex, [in] UINT PrimitiveCount ); d3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

DrawPrimitive - Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams. It has 3 parameters:

- Primitive type

typedef enum D3DPRIMITIVETYPE {

Page 8: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

8 / 18

D3DPT_POINTLIST = 1, //Renders the vertices as a collection of isolated points. //This value is unsupported for indexed primitives. D3DPT_LINELIST = 2, //Renders the vertices as a list of isolated straight line segments. D3DPT_LINESTRIP = 3,//Renders the vertices as a single polyline. D3DPT_TRIANGLELIST = 4,//Renders the specified vertices as a sequence of isolated triangles. //Each group of three vertices defines a separate triangle. D3DPT_TRIANGLESTRIP = 5,//Renders the vertices as a triangle strip. D3DPT_TRIANGLEFAN = 6,//Renders the vertices as a triangle fan. D3DPT_FORCE_DWORD = 0x7fffffff } D3DPRIMITIVETYPE, *LPD3DPRIMITIVETYPE;

- StartVertex - Index of the first vertex to load. Beginning at StartVertex the correct number of

vertices will be read out of the vertex buffer.

- PrimitiveCount - Number of primitives to render

4.3 Index buffer

Index buffer are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used to render primitives using the IDirect3DDevice9::DrawIndexedPrimitive method. An index buffer 'indexes' into the vertex buffer so each unique vertex needs to be stored only once in the vertex buffer. The following diagram shows an indexed approach to the earlier drawing scenario.

The index buffer stores VB Index values, which reference a particular vertex within the vertex buffer. A vertex buffer can be thought of as an array of vertices, so the VB Index is simply the index into the vertex buffer for the target vertex. Similarly, an IB Index is an index into the index buffer. This can get very confusing very quickly if you're not careful, so make sure you're clear on the vocabulary being used: VB Index values index into the vertex buffer, IB Index values index into the index buffer, and the index buffer itself stores VB Index values.

4.3.1 Declare/Create

Declare variable of type IDirect3DIndexBuffer9 (or LPDIRECT3DINDEXBUFFER9). HRESULT CreateIndexBuffer( [in] UINT Length, [in] DWORD Usage, [in] D3DFORMAT Format, [in] D3DPOOL Pool, [out, retval] IDirect3DIndexBuffer9 **ppIndexBuffer, [in] HANDLE *pSharedHandle );

Length [in]

Type: UINT

Size of the index buffer, in bytes.

Usage [in]

Type: DWORD

Page 9: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

9 / 18

Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination

of one or more D3DUSAGE constants. It is good practice to match the usage parameter in

CreateIndexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information,

see Remarks.

Format [in]

Type: D3DFORMAT

Member of the D3DFORMAT enumerated type, describing the format of the index buffer. For

more information, see Remarks. The valid settings are the following: D3DFMT_INDEX16 Indices are 16 bits each. D3DFMT_INDEX32 Indices are 32 bits each.

Pool [in]

Type: D3DPOOL

Member of the D3DPOOL enumerated type, describing a valid memory class into which to place

the resource.

ppIndexBuffer [out, retval]

Type: IDirect3DIndexBuffer9**

Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the created index

buffer resource.

pSharedHandle [in]

Type: HANDLE*

This parameter can be used in Direct3D 9 for Windows Vista to share resources; set it

to NULL to not share a resource. This parameter is not used in Direct3D 9 for operating systems

earlier than Windows Vista; set it to NULL.

4.3.2 Accesing the content

The same principle as in the vertex buffer. The only differences is that now we fill with a list of short the index buffer.

4.3.3 Rendering

Because we use now index buffer we must draw using DrawIndexPrimitive. Also we must tell the DirectX that it must use the specific index buffer: HRESULT SetIndices( [in] IDirect3DIndexBuffer9 *pIndexData ); HRESULT DrawIndexedPrimitive( [in] D3DPRIMITIVETYPE Type, [in] INT BaseVertexIndex, [in] UINT MinIndex, [in] UINT NumVertices, [in] UINT StartIndex, [in] UINT PrimitiveCount );

direct3Device9->SetIndices(indexBuffer); direct3Device9->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, 3, 0, 1);

Where parameters for DrawIndexPrimitive are: - D3DPRIMITIVETYPE

- BaseVertexIndex - Offset from the start of the vertex buffer to the first vertex

- MinIndex - Minimum vertex index for vertices used during this call.

Page 10: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

10 / 18

- NumVertices - Number of vertices used during this call

- StartIndex - Index of the first index to use when accesssing the vertex buffer

- PrimitiveCount - Number of primitives to render

4.4 Transforms

4.4.1 World transform

A world transform changes coordinates from model space, where vertices are defined relative to a model's local origin, to World Space, where vertices are defined relative to an origin common to all the objects in a scene // For our world matrix, we will just leave it as the identity D3DXMATRIX g_Transform; D3DXMatrixIdentity(&g_Transform); direct3Device9->SetTransform( D3DTS_WORLD, &g_Transform );

4.4.2 View transform

Setting the view transformation can be considered to be similar to setting up a virtual camera. All a programmer does with this is feed the camera position, direction and rotation into a single matrix. There is no need to multiply matrices here like there was in world transformation. There is only one matrix, and one function to build that matrix. Let's say we want to have the player view an object located at the world's origin (0, 0, 0). We want the player to be viewing the object from the coordinates (100, 100, 100). To do this we need to build a matrix containing this data. We build this matrix using a function called D3DXMatrixLookAtLH(). Here is the prototype: D3DXMATRIX* D3DXMATRIXLookAtLH(D3DXMATRIX* pOut, CONST D3DXVECTOR3* pEye, CONST D3DXVECTOR3* pAt, CONST D3DXVECTOR3* pUp); Let's go over these, because they are not all self-explanatory. CONST D3DXVECTOR3* pEye this parameter is a pointer to a vector which contains the exact position of the camera. Considering our example above, we want to fill this struct with (100, 100, 100). CONST D3DXVECTOR3* pAt this vector contains the exact location the camera should look at. Our example is looking at (0, 0, 0), so we will fill this struct with those values. CONST D3DXVECTOR3* pUp This vector contains the direction of "up" for the camera. In other words, what direction will the top of the screen be. Usually, game programmers use the y-axis as the "up" direction. To set the camera this way, you simply need to fill this struct with (0, 1, 0), or 1.0f on the y-axis and 0.0f on the other two. Ok, let's take a look at how this appears in real code:

Page 11: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

11 / 18

D3DXMATRIX matView; // the view transform matrix D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(100.0f, 100.0f, 100.0f), // the camera position &D3DXVECTOR3(0.0f, 0.0f, 0.0f), // the look-at position &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // the up direction d3ddev->SetTransform(D3DTS_VIEW, &matView); // set the view transform to matView

So here we created a matrix, filled it using D3DXMatrixLookAtLH() function, and used it to set the transform.

4.4.3 Projection transform

If view transformation can be considered the camera setup, then projection transformation can be thought of as the camera lens. It is probably the most complex type of transformation. It is simple in code (as it only needs one matrix, set by a single function), but it has a lot of factors which control it. However, to make it simpler, I'm going to go over some light theory first. The Field of View (fov) The field of view is similar the zoom of a camera. When a camera zooms in, it simply decreases the angle of light that is allowed in, as shown here.

In 3D graphics, the field of view is defined by setting the amount of radians allowed (vertically). The normal amount for this is 0.78539 (which is pi/4 radians, or 45 degrees) View-Plane Clipping Clipping is where Direct3D cuts out parts of an image that are unnecessary to draw. For example, if you have a large 3D environment which is too large to see the edge of (either because of fog or the horizon), then clipping can be used to cut out the parts of the image that are not going to be displayed anyway (the stuff that's beyond the fog). Direct3D accomplishes this by asking for two view-planes. A view-plane is a set distance from the camera. Direct3D asks for two view-planes, and only draws the graphics that are shown in between. This is illustrated here.

Page 12: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

12 / 18

Setting Up the Projection Matrix Setting up the Projection Matrix uses a function called D3DXMatrixPerspectiveFovLH(). It's quite a name, and its parameters are also numerous, although simple. D3DXMATRIX* D3DXMatrixPerspectiveFovLH(D3DXMATRIX* pOut, FLOAT fovy, FLOAT Aspect, FLOAT zn, FLOAT zf);

D3DXMATRIX* pOut, This is the pointer to the matrix. FLOAT fovy, As discussed before, we need to set the field of view. This is typically set to 45 degrees (0.78539 radians). This can be changed depending on what amount of zoom you want in your game. FLOAT Aspect, The aspect ratio is the ratio between the width of your screen and the height of your screen, in pixels. This is easy, because we have already defined them clearly (if you have come all the way through this tutorial). All you need to do is fill this value with: (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT. We convert each to a FLOAT in order to maintain accuracy in the division. Not doing this would make the result an integer, which will stretch the rendered image slightly. FLOAT zn, This parameter defines the nearer view-plane. This should usually be set to 1.0, although later on we will find uses for other values. Putting it less that 1.0 will create a bug in the next lesson. FLOAT zf This parameter defines the farther view-plane. This should be set to the farthest distance you want your user to see, usually beyond the horizon, or where fog cuts everything out. We'll set it to 100.0 for now. D3DXMatrixPerspectiveFovLH(&matProjection, D3DXToRadian(45), // the horizontal field of view (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio 1.0f, // the near view-plane 100.0f); // the far view-plane d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection); // set the projection transform

4.5 Exercises

- Run application with the triangle

- Rotate triangle (try using the all 3 axes). You can use UINT iTime = timeGetTime() % 1000;

FLOAT fAngle = iTime * (2.0f * D3DX_PI) / 1000.0f;

o D3DXMatrixRotationX

o D3DXMatrixRotationY

o D3DXMatrixRotationZ

- Create a rectangle using only vertex buffer

- Create a rectangle using index buffer

- Create a parallelepiped and square pyramid using index buffer. Rotate them in opposite direction.

- Create a circle

- Create a cone

Page 13: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

13 / 18

5 Texture.Lights.Sprite

5.1 Texture

Direct3D textures are bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3D primitives that form a hill. The result is a realistic-looking hillside. You can also use texturing to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor. Most textures, like bitmaps, are a two-dimensional array of color values. Cubic environment map textures are an exception. For details, see Cubic Environment Mapping (Direct3D 9). The individual color values are called a texture element, or texel. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively in the following illustration. Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations. Mapping Texels to Screen Space Direct3D maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering (Direct3D 9). Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D applications specify texture coordinates in terms of u,v values, much like 2D Cartesian coordinates are specified in terms of x,y coordinates. Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes (Direct3D 9). A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

Page 14: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

14 / 18

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering (Direct3D 9). HRESULT SetSamplerState( DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value ); Parameters: Sampler The sampler stage index. For more info about sampler stage, see Sampling Stage Registers in vs_3_0 (DirectX HLSL). Type D3DSAMPLERSTATETYPE This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.

D3DSAMP_MINFILTER Controls the filtering to use for shrinking the texture. D3DSAMP_MIPFILTER Controls the filtering to use for mipmap filtering.

Value Type: DWORD State value to set. The meaning of this value is determined by the Type parameter.

Sample: g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC);

5.2 Lights

Materials A material is a description of how surfaces reflect light, and which colors are involved. In other words, you won't necessarily see this color. You will only see it when you shine a light on it. Of course, a good 3D game always has lights shining on its objects, so materials are usually taken into consideration. Let me use a couple of pictures to explain what a material is exactly. Let's say we have a white square. Let's give it a white material and illuminate it with a white light.

A Pure White Square Just what we had before, a white square. The surface is exactly as it would have been without using lighting. However, let's now give the square a red material, while keeping the white light.

Page 15: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

15 / 18

A Pure Red Square Now we have a red square. What happened here? Well, the red material made the surface of the square entirely red. Only red light was reflect off, and so the surface appeared red. If we shined a completely blue light on this square, nothing would show up at all (because no blue reflects off). However, if we added some blue and some green into the material, we would get a much more controllable color, as well as a much more realistic one.

A Reddish Square This may look somewhat different to the pure red square, but by itself it's still quite red. Now what happens if we add a bluish light to the square. (A bluish light, not a blue light.)

Purple Square Purple! Actaully it's still reddish, but any reddish surface with a bluish light on it appears purple. Realistic. The moral of this little demonstration is to not have materials or lights that have only one primary color. Use white (or gray) as much as possible. I know we aren't up to the point of putting any color into lights or materials, but keep that in mind. Fiddling with materials and lights is a bit like mixing paint in a room with funky lights. All kinds of things can happen. The paint will even sometimes go black, even though it's really a bright yellow (pure yellow paint mixed with a pure blue light). Normal

Each face in a mesh has a perpendicular unit normal vector, as shown in the following illustration. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Direct3D, only the front of a face is visible. A front face is one in which vertices are defined in clockwise order.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration.

Page 16: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

16 / 18

5.3 Sprite

To read from Chapter 5 from „DirectX 9 Graphics: The Definitive Guide to Direct3D Alan Thorn“

5.4 Exercises

- Run both applications

- For the lighting application stop the cylinder from rotating

- For the lighting application stop the light from rotating

- Based on the first laboratory (or any other) draw the following

o Create a rectangle + texture + lightning

o Create a cube + texture + lightning

o Create a circle + texture + lightning + rotate on the X axis

o Create a cone + texture + lightning + rotate on the Y axis

o Create a cube and apply on each side a separate texture

- Using ID3DXSprite display texture 2d. Also rotate it after.

6 Meshes

For more information please also check Chapters 6-7+9 from“ DirectX 9 Graphics: The Definitive Guide to Direct3D Alan Thorn“ Meshes contain the vertex buffers and all the information needed to render a mesh, including poly counts and UV coordinates. This means that you’ll just load it once and stop editing individual vertices. This also means that you’ll be able to make models in external software and import much more complex geometry for your application, such that would be practically impossible to create with pure code. The default mesh file used by DirectX is the .x file format. In the code we will be using LPD3DXMESH interface pointers. Below it is presented the sample code to load a mesh. In case you have an x file containing several meshes you should use instead the D3DXLoadMeshFromXof function. HRESULT D3DXLoadMeshFromX( _In_ LPCTSTR pFilename, _In_ DWORD Options, _In_ LPDIRECT3DDEVICE9 pD3DDevice, _Out_ LPD3DXBUFFER *ppAdjacency, _Out_ LPD3DXBUFFER *ppMaterials, _Out_ LPD3DXBUFFER *ppEffectInstances, _Out_ DWORD *pNumMaterials, _Out_ LPD3DXMESH *ppMesh ); Parameters (Source MSDN): pFilename [in] Type: LPCTSTR Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.

Page 17: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

17 / 18

Options [in] Type: DWORD Combination of one or more flags from the D3DXMESH enumeration, which specifies creation options for the mesh. pD3DDevice [in] Type: LPDIRECT3DDEVICE9 Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh. ppAdjacency [out] Type: LPD3DXBUFFER* Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer. ppMaterials [out] Type: LPD3DXBUFFER* Pointer to a buffer containing materials data. The buffer contains an array of D3DXMATERIAL structures, containing information from the DirectX file. For more information about accessing the buffer, see ID3DXBuffer. ppEffectInstances [out] Type: LPD3DXBUFFER* Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer. pNumMaterials [out] Type: DWORD* Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns. ppMesh [out] Type: LPD3DXMESH* Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

If the above function is processed successfully, the next step is to load the texture for each sub-set inside the

mesh. We are also going to store the information about the sub-set material. The total number of

texture/materials is returned in the pNumMaterials variable. So allocating memory for them is simple. The

code to do this follows (where g_dwNumMaterials represents the returned number of materials). g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];

g_pMeshTextures = new LPDIRECT3DTEXTURE9[g_dwNumMaterials]; After that we need to access the first element inside the D3DXMaterial (Different from the material structure needed for lights): D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer(); A D3DXMaterial is a structure which contains basically 2 informations:

- D3DMATERIAL9 – material information for the current sub-set - LPSTR – path to the texture for the current sub-set

After we’ve filled in the above two arrays for materials and meshes (g_pMeshMaterials + g_pMeshTextures), we only need to display the mesh. This we are going to do inside the Render function – and we are going to call mesh->DrawSubset(i) – where i is between 0 and pNumMaterials. HRESULT D3DXComputeBoundingBox( _In_ const D3DXVECTOR3 *pFirstPosition, _In_ DWORD NumVertices, _In_ DWORD dwStride, _Out_ D3DXVECTOR3 *pMin, _Out_ D3DXVECTOR3 *pMax ); HRESULT D3DXComputeBoundingSphere( _In_ const D3DXVECTOR3 *pFirstPosition, _In_ DWORD NumVertices, _In_ DWORD dwStride, _Out_ D3DXVECTOR3 *pCenter, _Out_ FLOAT *pRadius );

Page 18: DirectX 9 Lab Manual - Google Sites: Sign-in

DirectX 9 Lab DirectX 9 Laboratory guideline(2020)

18 / 18

LPDIRECT3DVERTEXBUFFER9 VertexBuffer = NULL; D3DXVECTOR3* Vertices = NULL; D3DXVECTOR3 LowerLeftCorner; D3DXVECTOR3 UpperRightCorner; DWORD FVFVertexSize = D3DXGetFVFVertexSize(g_pMesh->GetFVF()); g_pMesh->GetVertexBuffer(&VertexBuffer); VertexBuffer->Lock(0,0, (VOID**) &Vertices, D3DLOCK_DISCARD); D3DXComputeBoundingBox(Vertices,g_pMesh->GetNumVertices(),FVFVertexSize,&LowerLeftCorner,&UpperRightCorner);

6.1 Exercises

- Clone the mesh

- Display the original + cloned mesh (one mesh will be translated)

- Display 3rd mesh without cloning

- For the first mesh – take randomly 3 points in the meshes vertex buffer and change them

7 Camera

7.1 Exercise

- use the class “camera” in order to rotate arround the tiger. Try different methods of the camera class. - use the class “frustum” to check if 2 (or more) meshes are occupying the same visualization volume. Change background if meshes are occupying same area.Also at each „render”step one of the meshe translate it.

8 Direct Input & Direct play

TBD