tags:

views:

32

answers:

2

So I have a x8r8g8b8 formatted IDirect3DSurface9 that contains the contents of the back buffer. When I call LockRect on it I get access to a struct containing pBits, a pointer to the pixels I assume, and and integer Pitch (which I am very unclear about its purpose).

How to read the individual pixels?

Visual Studio 2008 C++

A: 

The locked area is stored in a D3DLOCKED_RECT. I haven't ever used this but the documentation says it is the "Number of bytes in one row of the surface". Actually people would normally call this "stride" (some terms explained in the MSDN).

For example, if one pixel has 4 bytes (8 bits for each component of XRGB), and the texture width is 7, the image is usually stored as 8*4 bytes instead of 7*4 bytes because the memory can be accessed faster if the data is DWORD-aligned.

So, in order to read pixel [x, y] you would have to read

uint8_t *pixels = rect.pBits;
uint32_t *mypixel = (uint32_t*)&pixels[rect.Pitch*y + 4*x];

where 4 is the size of a pixel. *myPixel would be the content of the pixel in my example.

AndiDog
and access the components of the pixel it would be:uint32_t x = mypixel[0];uint32_t r = mypixel[1];uint32_t g = mypixel[2];uint32_t b = mypixel[3];Correct?
Mr Bell
and I am guessing the x component is just padding and in this particular format is garbage?
Mr Bell
The X in XRGB is just for 32-bit alignment (faster). And access to the components would be `uint8_t *components = (uint8_t*)mypixel;` and then `X = components[0]; R = components[1]` and so on...
AndiDog
This is probably a newb question but where does uint8_t, uint32_t come from? I tried using them and the compiler doesnt know what they are
Mr Bell
They're defined in `stdint.h`. I prefer them because the standard types (int, long, char) don't have a fixed size. See http://linux.die.net/man/3/uint8_t
AndiDog
A: 

Yep, you would access the individual RGB components of the pixel like that.

The first byte of the pixel is not used, but it is more efficient to use 4 Bytes per pixel, so that each pixel is aligned on a 32Bit boundary (that's also, why there's the pitch).

In your example, the x is not used, but note that there are lso other pixel formats, for example ARGB, which stores the alpha value (transparency) in the first byte. Sometimes the colors are also reversed (BGR instead of RGB). If you're unsure what byte corresponds to what color, a good trick is to create a texture which is entirely red, green or blue and then check which of the 4 bytes has the value 255.

humbagumba