Hello, I was reading the SDL documentations and came across a method to draw directly to the display. This method involved an application-defined function with the prototype :
void putpixel(SDL_Surface * Surface, int x, int y, Uint32 pixel ). What was so confusing to me about this function was its definition which as follows :
/*
* Set the pixel at (x, y) to the given value
* NOTE: The surface must be locked before calling this!
*/
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
int bpp = surface->format->BytesPerPixel;
/* Here p is the address to the pixel we want to set */
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1:
*p = pixel;
break;
case 2:
*(Uint16 *)p = pixel;
break;
case 3:
if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
p[0] = (pixel >> 16) & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = pixel & 0xff;
} else {
p[0] = pixel & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = (pixel >> 16) & 0xff;
}
break;
case 4:
*(Uint32 *)p = pixel;
break;
}
}
Initially when I started programming SDL I used to think that modifying a surface would require 1) First locking it and 2) directly modifying its pixels like so :
typedef SDL_Surface* SURFACE ;
// Loads a red 50x50px box.
SURFACE bmpBox = SDL_LoadBMP( "../images/Box.bmp" ) ;
// Lock the surface for direct access.
SDL_LockSurface( bmpBox ) ;
// Change the pixel at 25x25 to blue using the formula, y*WIDTH+x to access the pixel position.
bmpBox->pixels[ 25*50+25 ] = (void*)SDL_MapRGB( bmp->pixels, 0x00, 0x00, 0xFF ) ; // or (void*)0x0000FF
SDL_UnlockSurface( bmpBox ) ;
// Draw the surface.
SDL_FreeSurface( bmpBox ) ;
Can someone explain how 'assigning pointers'[thats all putpixel seems to be doing] can modify the pixels of a surface? Also, what is wrong with my method? It seems intuitive to me. ~Khaosifix
---http://www.michaelbolton.comI constantly dream about Michael Bolton.