2
\$\begingroup\$

I'm trying to write a software rasterizer and I'm in the step to texture a triangle. I'm trying to get a pixel from an SDL_Surface which is an image, 100x60 at 24 bits of color depth.

I got a read access violation exception. For instance I try to say

Uint32 * pixels = (Uint32 *)texture->pixels;

then

int pixel = pixels[5900];

It gives an access violation. However the calculated pixels count is correct

int pixel_count  = (texture->pitch / texture->format->BytesPerPixel) * texture->h;

Is this wrong? How can I access the pixels of this surface?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It sounds like you're reading off the end of the 24-bit data, because you're treating it as if it was 32-bit.

That is I suspect texture->pitch is 300 and texture->format->BytesPerPixel is 3. sizeof(Uint32) is of course 4.

The simplest solution is to use a 32-bit image.

\$\endgroup\$
3
  • \$\begingroup\$ Thanks so much!, but I was thinking about how would I work out a solution If I want to use a 24bit image ? I should encode the resultant pixel to a 32bit pixel ? also why I read the end of the 24bit data ? isn't 5900 is still in the range of 100*60 W*H ? \$\endgroup\$
    – Tolba
    Jan 6, 2014 at 0:04
  • \$\begingroup\$ Your surface array is 24bit*60*100 = 18000 byte long. You access the 32bit*5900 = 23600th byte, which is out of bounds. \$\endgroup\$
    – Luis W
    Jan 6, 2014 at 0:22
  • \$\begingroup\$ @LuisW Thanks. The problem original with the casting. \$\endgroup\$
    – Tolba
    Jan 6, 2014 at 0:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .