All blog entries, ordered from most recent. Entry count: 1198.
# Introduction to XNA Math
Tue
04
May 2010
I've recently shared my XNA Math Cheat Sheet Today I'd like to post some more information about XNA Math. It is a new C++ math library for gamedev distributed with DirectX SDK, intended to replace math support from D3DX. Its online documentation can be found here: XNA Math Library Reference and the offline one is in DXSDK\Documentation\DirectX9\directx_sdk.chm file. It's worth noticing that the documentation in recent DX SDK versions is split across two separate CHM files. windows_graphics.chm describes only graphics programming (Direct3D 9, 10 and 11, D3DX, DXGI, HLSL language, effects format, DDS format, X format etc.), while directx_sdk.chm is about all other stuff (DirectSetup, DXUT, XNA Math, XAudio2, XInput etc.).
XNA Math is different from old D3DX and I'm afraid also harder to use. But I believe it's better. It's your decision whether you start to use it or not, because it's completely separate library that can be used with DirectX 11, 10, 9 or without anyone of them. On the other hand, you can still link with old D3DX while coding in new DirectX 11, so it's all your choice.
By the way, I don't know why is this library called "XNA Math". It looks like it has nothing to do with the XNA technology. XNA is a .NET library with its own vector and matrix classes while XNA Math is pure native C++ library distributed with DirectX SDK. It looks like a misnomer.
Beginning with XNA Math is simple. You just #include <xnamath.h> and that's all. There is even no need to link with any LIB file - all code is inline in this header or INL files included by it (which sum up to 26530 lines :) It provides support for vectors (up to 4D), matrices (up to 4x4), colors, planes and quaternions - all made of 32-bit floats, just as we all use in gamedev.
But design ideas of this API are totally different from D3DX. There is now one main data type called XMVECTOR - a vector of 4 floats. When the library uses SSE (which is the default on PC), this type is simply a typedef to __m128 (if you know what I mean). So it must be always aligned to 16-byte boundary. As a consequence, it's safe to cast this type to any other one interpreted as a vector of floats (like float[4] or D3DVECTOR), but not the other way around (because the pointer you cast might not be property aligned). This single type is used in all computations and interpreted as a 2D, 3D or 4D vector, plane, quaternion, part of 4x4 matrix or even a vector of unsigned integers, depending on the context. It may also feel strange at the beginning that this not-so-small object is usually passed and returned by value, not by reference.
Old DirectX versions used a D3DVECTOR and D3DMATRIX structures, which were extended by inheritance in D3DX library as D3DXVECTOR and D3DXMATRIX - structures with lots of overloaded operators and methods to operate on. The idea behind new DirectX 11 is that the graphics API is not dependent on any particular math library - it only uses float* or even void* and it's you job to use some library that would help you with math computations (like D3DX or XNA Math).
If you ever coded in SSE or other vector instruction set, you might know the concept of loading and storing. Here is an example that sets and gets vector as well as its components in many different ways.
XMVECTOR v = XMVectorZero(); // v is now (0, 0, 0, 0) v = XMVectorSplatOne(); // v is now (1, 1, 1, 1) v = XMVectorReplicate(5.f); // v is now (5, 5, 5, 5) v = XMVectorSet(1.f, 2.f, 3.f, 4.f); // v is now (1, 2, 3, 4) v = XMVectorSetX(v, 10.f); // v is now (10, 2, 3, 4) std::cout << XMVectorGetW(v); // Prints 4
There are lots of structures defined in XNA Math that represent different ways vectors can be stored and packet in the memory. Many of them are very weird, but there is good reason for their existence - they are CPU equivalents for some of DXGI_FORMAT-s available in DirectX 10/11. For example, the XMUDECN4 type, representing DXGI_FORMAT_R10G10B10A2_UNORM, is defined as follows:
union {
struct { UINT x : 10; UINT y : 10; UINT z : 10; UINT w : 2; };
UINT v;
};
It is a 32-bit value that stores 4D vector in 10+10+10+2 bit format, where float values 0.0 .. 1.0 are mapped to integers 0..1023 for x, y, z components and 0..3 for w component (just a bit smaller precision, nothing more ;) XNA Math provides us with functions to load and store XMVECTOR from/to all these strange types, so you can just do something like this:
XMVECTOR v = XMVectorSet(0.f, 1.f, 0.5f, 0.5f); XMUDECN4 packedV; XMStoreUDecN4(&packedV, v); // packedV is 0x5ffffc00 XMVECTOR v2 = XMLoadUDecN4(&packedV); // v2 is (0, 1, 0.499511, 0.333333)
XNA Math contains lots of functions that we all know from old good D3DX. (The only missing thing are SH* functions for spherical harmonics, but well - I have never used them anyway :) For example, a function for normalizing 3D vector now has a signature:
XMVECTOR XMVector3Normalize(XMVECTOR V)
XNA Math also supports matrices. XMMATRIX type is a 4x4 matrix. It contains 4 XMVECTOR-s inside. Functions for manipulating matrices include XMMatrixTranslation, XMMatrixRotationRollPitchYaw, XMMatrixPerspectiveFovLH and so on. You can also do computations on 3D planes if only you agree to treat (x, y, z, w) vectors as (A, B, C, D) factors of plane equation. Same applies to colors - functions like XMColorAdjustSaturation also operate on XMVECTOR, but treat its components as (R, G, B, A) values.
XNA Math wouldn't be complete without some basic functions, constants and macros for scalars, such as XM_PI, XMMax, XMScalarSin. Functions with -Est suffix (from "estimated") are faster but less precise versions, e.g. XMScalarSinEst.
If you want to make full use of the performance of vector arithmetic, you should also use swizzling, permutation and comparison functionality. Swizzling is about permutation of components of a vector. It's elegant and intuitive in languages designed with gamedev in mind (like HLSL), where you just write:
float4 v2 = v1.xyxy;
In C++ with XNA Math, same operation can be written as:
XMVECTOR v2 = XMVectorSwizzle(v1, 0, 1, 0, 1);
When it comes to comparisons, functions with -R suffix return additional UINT value, which is a bitfield designed to be tested with special functions. For example:
XMVECTOR v1 = XMVectorSet(0.0f, 1.0f, 0.5f, 0.5f); XMVECTOR v2 = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f); UINT cr; XMVECTORU32 res; res.v = XMVectorGreaterR(&cr, v1, v2); // res contains (0, 0xffffffff, 0, 0) std::cout << XMComparisonAnyTrue(cr); // Prints 1.
Comments | #math #directx Share
# HLSL syntax highlighting for jEdit
Sat
01
May 2010
Some time ago I've created a syntax highlighting mode of HLSL language (the shader language of DirectX) for jEdit - my favourite text editor. It is now included in the official jEdit distribution. But it wasn't updated for a long time, since Shader Model 2. Now I've created a new version that supports all the features of new DirectX shaders and effects up to these from DirectX 11 (Shader Model 5), including ones from the upcoming June 2010 version.
So if you don't use jEdit, just keep in mind that there is probably no other text editor (which I would know about) with a coloring scheme for shader language. (I know AMD RenderMonkey and NVIDIA Fx Composer do that, but these are big shader IDE-s, not just text editors.) And if you do, here is how to install it. Download the file:
Place it in your jEdit's "modes" subdirectory, e.g.: "C:\Program Files (x86)\jEdit 4.3.1\modes" and replace the existing one. That's all. You can double-click on the right part of the status bar in jEdit to open the Buffer Options window and select Edit mode = "hlsl".
But it's better to associate this coloring scheme with some file extensions. To do that, open file: "C:\Program Files (x86)\jEdit 4.3.1\modes\catalog", comment out the "javafx" mode as it owns the "fx" file extension by defalt:
<!--<MODE NAME="javafx" FILE="javafx.xml"
FILE_NAME_GLOB="*.fx" />-->
Then find and alter the entry about "hlsl" mode to associate it with whatever file extension you use for your shaders, like the example:
<MODE NAME="hlsl" FILE="hlsl.xml"
FILE_NAME_GLOB="*.{fx,hlsl}" />
If you edit this file inside jEdit, you don't even have to restart it - new rules are applied automatically.
You may ask why not just use the C++ coloring scheme for shader code? Of course you can do it, the syntax is similar because all the tokens, like strings, numbers and identifiers look the same way. But my coloring schemes give separate colors for language elements such as: semantics (like c:COLOR0), component indexing (like v.xyzz), atomic types (like float), object types (like Texture2D or RWStructuredBuffer) and intrinsic functions (like sin, cos, InterlockedCompareExchange).
Comments | #tools #rendering #directx Share
# DXGI Format Cheatsheet
Thu
29
Apr 2010
Today I've prepared another small, single page cheat sheet related to DirectX 11:
DXGI_Format_Cheatsheet.pdf
DXGI_Format_Cheatsheet.odt
I've also solved my problem with Visual C++ 2010 Express that crashed every compilation on my computer. I've submitted this bug to Microsoft Connect, expecting that it may be because I have a 64-bit Windows 7 or because I also have Visual Studio 2008 Professional installed. But with the help from Microsoft I've figured out that it was just because of the AMD CodeAnalyst profiler. Uninstalling this program helped me so my VC2010 doesn't crash any more :D
Comments | #visual studio #directx #rendering Share
# XNA Math Cheat Sheet
Wed
28
Apr 2010
Today I've prepared a...
XNA Math Cheatsheet (PDF)
XNA Math Cheatsheet (ODT)
I'll post more information about the XNA Math Library tomorrow.
(NEW) Updated links to version 1.1 for DX SDK June 2010.
Comments | #math #directx Share
# My First Triangle in DirectX 11
Tue
27
Apr 2010
Now as I have my new graphics card I've started learning Direct3D 11. I've been doing much coding in DirectX 9 before. I also looked at the DirectX 10 API but gained not much practical experience in it. I'm very excited about how the new API looks like and the possibilities it creates. The library interface looks better organized, more object-oriented and clear. It makes extensive use of descriptors - same concept I liked so much in PhysX.
But at the same time I must admit it's more difficult to get started than it was in DirectX 9. You have to create more objects to setup basic framework that could render anything. The so called Fixed Function Pipeline doesn't exist anymore, so you HAVE to write shaders to render anything. Better organization of all data forces you to pass shader constants in buffers instead one-by-one, fill descriptors, create and use state objects (like ID3D11DepthStencilState) instead of changing render states one-by-one, create views for resources (like ID3D11ShaderResourceView for ID3D11Texture2D) instead of using them directly, compile shaders from HLSL source to bytecode and then create the shader object with separate call etc.
There are also big changes in math support. They didn't provide new D3DX Math with DX11. You can still use the old one, but now it's recommended to make use of new, portable (to Xbox 360) and highly optimized XNA Math library. It's pretty but can be difficult for beginners. For example, now there is one universal type - XMVECTOR - that can represent a vector, color, plane, quaternion and more. It must be always aligned to 16 bytes (because it uses SSE). I suppose it's not easy to understand concepts like vector loading, storing or swizzling, which can be new for many DirectX programmers.
Where do learn DirectX 11 from? It looks like there are not many valuable sources online yet. The directx11tutorials.com website looks interesting, but it's just a blog with few pieces of code and the author tries to wrap everything into his own classes from the start, which makes no sense for me. The most valuable source of knowledge is the original documentation installed with DX SDK. It's far from being extensive because the chapter about DirectX 11 describes only new features, not everything about using DirectX like the documentation for version 9, but for somebody who already knows some graphics programming it should be OK.
What I want to show today is my first "Hello World" triangle made in Direct3D 11 and code that renders it. You can download whole source with project for Visual C++ 2008 from here: Dx11Test.zip. See also the code online: Dx11Test.cpp.
To code in DX11, you just need DirectX SDK - same as for DirectX 9 and 10, because it contains SDK for all of them. Programs that use DirectX 11 can run on Windows 7 as well as Vista, but not on XP. It's surprising that newest-generation graphics card is not needed - you can use DX11 API to code in different "feature levels" from D3D_FEATURE_LEVEL_9_1 to D3D_FEATURE_LEVEL_11_0, so you can write your code so it will run even on GPUs that support only Shader Model 2!
Comments | #directx #rendering Share
# Radeon HD 5770
Sun
25
Apr 2010
I'm not a hardware specialist, so every time I want to buy something, I do a quick research to see what's currently available in stores, what's already a standard and what's an expensive novelty. Next I imagine in my mind a power(price) function and find its inflection point to see what product is most reasonable to buy ;)
I've been fan of Intel and NVIDIA, but I must admit that now my PC is dominated by AMD. Some time ago I wanted to buy a 4-core CPU. It turned out that Intel i7 processors are very expensive and that's how I've bought AMD Phenom II.
Now it's the same with graphics cards. I thought it's a good time to buy one with DirectX 11 support. I've been waiting for some time for these new cards from NVIDIA 4xx series, but now as they are available in stores I see they are very expensive, while I can have a GPU with DX11 support from AMD for about 600 PLN. My choice is Radeon HD 5770. It is not the most powerful card available (it actually has its power cut by half comparing to its higher versions), so I can see it's the speed what costs most. While for me the capabilities are more improtant. I just wanted a card with DX11 support. Of course AMD cards don't have CUDA technology, but well, it's vendor specific anyway while DX11 has Compute Shaders.
BTW, anyone wants to buy GeForce 8800 GT? :)
Comments | #hardware #shopping Share
# My Impressions about SQLite
Tue
20
Apr 2010
SQLite is a very strange library. It's a database engine that can store lots of data in a relational database and exposes API based on SQL language. On the other hand though, it's not a huge application that has to be installed in the system, work in the background and you have to connect to it via network interface, like MySQL or PostreSQL do. It's actually a lightweight library written in C that can be linked with your program and uses specified file as the database. It's fascinating that such a small library (there is even a preprocessed source version as a single 3.75 megabyte C file!) supports much of the SQL language.
The API of the SQLite library is similar to any other SQL-based database access API for any programming language. I've played with it a bit and here is my small sample code:
#include <sqlite3.h>
int main()
{
sqlite3 *db;
sqlite3_open_v2("D:\\tmp\\test.db", &db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
sqlite3_exec(db, "begin", NULL, NULL, NULL);
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, "insert into table1 (id) values (?)",
-1, &stmt, NULL);
for (int i = 0; i < 10; i++)
{
sqlite3_reset(stmt);
sqlite3_bind_int(stmt, 1, i);
sqlite3_step(stmt);
}
sqlite3_exec(db, "commit", NULL, NULL, NULL);
sqlite3_finalize(stmt);
sqlite3_close(db);
}
It's hard for me to think of any application for such a strange library. It offers too much when you just want to design your file format and too few if you need a fully-featured database, like for a web server. So why did I decide to get to know this library? It's all because of an interesting gamedev tool called Echo Chamber. It's a free data mining program that can visualize data from SQLite database files as many different kinds of plots, even 3D ones. So when you integrate logging some numeric data from your engine into an SQLite database you can easily do performance analysis with it.
Comments | #tools #libraries #sql Share
# Tower Offence - Compo Entry from IGK-7'2010
Thu
15
Apr 2010
I've published the game we made at IGK-7'2010 conference for Compo. It was created by our 4-person team during 8 hours. It's a small PC game from "Tower Defence" genre but with a hero directly controller by player who have to approach a place to create a tower and can also shoot by itself.
Screenshot: