Accessing pixels of a surface in SDL

Started by
4 comments, last by rip-off 10 years, 3 months ago

I'm trying to write a software rasterizer and I'm in the step to texture a triangle.

I'm trying for example to get a pixel from an SDL_Surface which is an image, 100*60, 24bits.

I got a read access violation exception, so I tried to verify the pixels from the surface as:

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;

Advertisement
Have you checked if pixels is a null pointer?
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

Have you locked the surface?

Note: you can use the WSIWYG editor or manually insert [[size="1"]code][[size="1"]/code] tags to insert source code in a manner that is easier for us to manage.

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.

http://sdl.beuc.net/sdl.wiki/Pixel_Access

Copy and paste those functions into your code. They work and also take care of surface locking and format conversion. If you understand how they work, you could use similar code for more efficient scenario-specific applications.


They work and also take care of surface locking and format conversion.

The functions certainly work, but they do not take care of surface locking. Generally, you don't want to lock a surface at the level of an individual pixel, as locking could involve copying the surface data from video to system memory. If you want to access a surface's pixels, lock it once and bulk update the pixels, before unlocking it.

See this note from the linked page:


You must lock the surface using SDL_LockSurface before using them. Note that pixel manipulations are very inefficient on hardware surfaces.

This topic is closed to new replies.

Advertisement