HELP ! (fwd)

The question was
"How do I change pixels from one color to pixels of another color?"

Here’s the answer:

Forwarded message: -------------------Date: Thu, 8 Oct 1998 13:41:29 -0700
From: @slouken (slouken)
Subject: Re: HELP !!

In games we often need to put sprites in which we nned to change an specific
color numebr (in 256 cl palettized mode) into another one (like in Warcraft II,
the colour of the team). I need this for my game, so I’ll need to use a FOR and
an IF but I’ll need to do it with memory pointers, and it is slower then
SDL_surfaces.

You can directly access the memory pointers of the SDL surface:

Uint8 *mem;
Uint8 in, out;
int i, j;

in = SDL_MapRGB(surface->format, inR, inG, inB);
out = SDL_MapRGB(surface->format, outR, outG, outB);

if ( SDL_LockSurface(surface) < 0 )
/* ERROR */

for ( i=0; ih; ++i ) {
mem = (Uint8 )surface->pixels+isurface->pitch;
for ( j=0; jw; ++j ) {
if ( *mem == in )
*mem = out;
++mem;
}
}

That code assumes 8-bit surfaces. :slight_smile:

Code to do that for 16 bit surfaces would be very similar:

Uint16 *mem;
Uint16 in, out;
int i, j;

in = SDL_MapRGB(surface->format, inR, inG, inB);
out = SDL_MapRGB(surface->format, outR, outG, outB);

if ( SDL_LockSurface(surface) < 0 )
/* ERROR */

for ( i=0; ih; ++i ) {
mem = (Uint16 *)((Uint8 )surface->pixels+isurface->pitch);
for ( j=0; jw; ++j ) {
if ( *mem == in )
*mem = out;
++mem;
}
}

Easy! :slight_smile:

See ya,
-Sam Lantinga (slouken at devolution.com)


Author of Simple DirectMedia Layer -
http://www.devolution.com/~slouken/SDL/

------------------- end forwarded message.

for ( i=0; ih; ++i ) {
mem = (Uint16 *)((Uint8 )surface->pixels+isurface->pitch);
for ( j=0; jw; ++j ) {
if ( *mem == in )
*mem = out;
++mem;
}
}

I realize this code is just for tutorial purposes, but just in case
anyone doesn’t know this:

Actually comparing j to surface->w each time through the loop like
this will be slow, since almost every C compiler will reload
surface->w each time through the loop (since there’s a memory write in
the loop which it isn’t sure won’t change the value of surface->w).
You’re better off either reversing the loop (so you compare against
zero) or storing surface->w and surface->h in local variables.

-Mat