I have been attempting to work with SDL and openGL for a project Im working on, and to enable easy testing, I would like to be able to draw in 2D to the screen and the only way I have found to allow me to do this is SDL surfaces to create and draw BMP images. This is fine as being able to save the image will be a nice feature later on but if there is another better way to do this with openGL or some other method, please say :).
This is the code I am currently using:
int w = 255;
int h = 255;
SDL_Surface* surface = SDL_CreateRGBSurface(0,w,h,32,0,0,0,0);
SDL_LockSurface(surface);
int bpp = surface->format->BitsPerPixel;
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
Uint32 *p = (Uint32 *)surface->pixels + (i * surface->pitch) + (j * bpp);
*p = SDL_MapRGB(surface->format,i,j,i);
}
}
SDL_UnlockSurface(surface);
SDL_SaveBMP(surface, "Test.bmp");
This is just a basic test thing to allow me to get to terms with how to do this, Im sure I have some issues with memory handling here but Im not sure when if at all to delete *p. The issue that I am having the biggest problem with though is where I use SDL_MapRGB. the program crashes when it hits this with a SIGSEGV segmentation fault and I cant figure out what I am doing wrong.
You do not free the memory pointed by p
.
But after use, you have to free the surface
as
SDL_FreeSurface(surface);
Also, bpp
is in bits. You have to divide it by 8
to get it in bytes.
And, to do arithmetic in bytes, you have to use
Uint32 *p = (Uint32 *)((Uint8 *)surface->pixels + (i * surface->pitch) + (j * bpp));