Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DirectX set color of single pixel

Tags:

directx

I read in another thread, that I can read a single pixel with Texture.Lock / Unlock, but I need to write the pixels back to the texture after reading them, this is my code so far

unsigned int readPixel(LPDIRECT3DTEXTURE9 pTexture, UINT x, UINT y)
{
    D3DLOCKED_RECT rect;
    ZeroMemory(&rect, sizeof(D3DLOCKED_RECT));
    pTexture->LockRect(0, &rect, NULL, D3DLOCK_READONLY);
    unsigned char *bits = (unsigned char *)rect.pBits;
    unsigned int pixel = (unsigned int)&bits[rect.Pitch * y + 4 * x];
    pTexture->UnlockRect(0);
    return pixel;
}

So my questions are:

- How to write the pixels back to the texture?  
- How to get the ARGB values from this unsigned int? 

((BYTE)x >> 8/16/24) didnt work for me (the returned value from the function was 688)

like image 863
Alex Kruger Avatar asked Mar 19 '11 18:03

Alex Kruger


1 Answers

1) One way is to use a memcpy:

memcpy( &bits[rect.Pitch * y + 4 * x]), &pixel, 4 );

2) There are a number of different ways. The simplest is to define a struct as follows:

struct ARGB
{
    char b;
    char g;
    char r;
    char a;
};

Then change your pixel loading code to the following:

ARGB pixel;
memcpy( &pixel, &bits[rect.Pitch * y + 4 * x]), 4 );

char red = pixel.r;

You can also obtain all the values using masks and shifts. e.g

unsigned char a = (intPixel >> 24);
unsigned char r = (intPixel >> 16) & 0xff;
unsigned char g = (intPixel >>  8) & 0xff;
unsigned char b = (intPixel)       & 0xff;
like image 76
Goz Avatar answered Dec 31 '22 19:12

Goz