TweetFollow Us on Twitter

Dec 98 Getting Started

Volume Number: 14 (1998)
Issue Number: 12
Column Tag: Getting Started

Color Animation

by Dave Mark and Dan Parks Sydow

How a Mac program generates smooth, flicker-free color animation

A couple of articles back we covered the bitmap and its use in offscreen drawing to create smooth black and white animation. Last month's article introduced Color QuickDraw and drawing in color. In this month's article we combine all these recently learned techniques to tackle smooth, fast, color animation.

Bitmaps and Offscreen

Drawing Review

A bitmap is a representation of a monochrome (blacK-and-white) image. The map is composed of a grid of pixels, with each pixel considered either on or off. An image is defined by specifying the state of each pixel in the map. A single bit is used to keep track of whether a single pixel is on or off.

An offscreen bitmap is a bitmap that is drawn in memory alone - it doesn't have an onscreen representation. That is, a data structure holds the bit information that defines an image, but the contents of this data structure aren't translated to a window's graphics port. Animation is accomplished using a total of three offscreen bitmaps. One bitmap holds a background image, a second bitmap holds the foreground image, and the third bitmap is a mixer, or master, that is a combination of the other two bitmaps. The image that is the foreground bitmap and the image that is the background bitmap combine in the master bitmap offscreen (in memory), after which the image in the master (and only the master) bitmap appears onscreen. Repeating this process via a loop, with a slight shift of the position of the foreground image relative to the background image, is the basis for animation. Because each pass through the loop creates a master bitmap behind the scene in memory rather than in view of the user onscreen, flicker is kept to a minimum.

Pixmaps and Offscreen Drawing

For monochrome animation, the BitMap data structure is used to define the state of the pixels that make up a bitmap image. Here's the BitMap data structure:

struct BitMap
{
   Ptr        baseAddr;
   Short      rowBytes;
   Rect       bounds;
};

A color image necessitates the use of a different data structure. The PixMap data structure includes the same three fields as the BitMap data structure - but it also holds more information as well. Among the extra information stored in the more complex PixMap is the number of bits used to define the color of each pixel. Here's a look at the PixMap data structure:

struct PixMap {
   Ptr               baseAddr;      /*pointer to pixels*/   
   short             rowBytes;      /*offset to next line*/
   Rect              bounds;        /*encloses bitmap*/
   short             pmVersion;     /*pixMap vers number*/
   short             packType;      /*defines packing */
   long              packSize;      /*length of data*/
   Fixed             hRes;          /*horiz. Res. (ppi)*/
   Fixed             vRes;          /*vert. Res. (ppi)*/
   short             pixelType;     /*defines pixel type*/
   short             pixelSize;     /*bits in pixel*/
   short             cmpCount;      /*components in pixel*/
   short             cmpSize;       /*bits per component*/
#if OLDPIXMAPSTRUCT
   long              planeBytes;    /*plane*/
   CTabHandle        pmTable;       /*color map*/
   long              pmReserved;
#else
   OSType            pixelFormat;   /*fourCharCode rep.*/
   CTabHandle        pmTable;       /*color map*/
   PixMapExtHandle   pmExt;         /*pixMap handle ext.*/
#endif
};

With monochrome bitmap animation, all you had to do was fill out the relatively simple BitMap structure, create a GrafPort, then connect the two via a call to SetPortBits(). Once that's done, you are ready to copy the BitMap from port to port via a call to CopyBits().

A PixMap is more complex than a BitMap, so color pixel map animation requires extra effort. Fortunately, the Toolbox offers a high-level set of functions that simplify somewhat the creation of offscreen PixMaps. An offscreen PixMap is known as a graphics world, or GWorld. A GWorld is created in memory and typically drawn to a window via a call to CopyBits(), just as done with a BitMap.

The GWorld is a full-color, offscreen drawing environment. Just as you'd use an offscreen GrafPort and BitMap to prepare a black-and-white image for blitting to the screen (blitting comes from BLock Transfer, meaning copying a block of memory from one area to another, all at once), you'll use a GWorld to do the same for a color image.

PixMapper

Two issues ago, the Getting Started program BitMapper was developed to demonstrate offscreen animation using black-and-white bitmaps. Figure 1 shows the window displayed by BitMapper. The floating hand is the foreground image and the framed gray pattern is the background image. As you move the mouse, the hand appears to float over the gray background, just like a cursor. What the user is seeing is the mixer bitmap - the copied version of the offscreen bitmap that represents the combining of the foreground hand bitmap with the background gray bitmap.

Figure 1. The BitMapper window.

This month's program is called PixMapper. Like BitMapper, PixMapper moves a foreground image over a background image. As we did for BitMapper, in PixMapper we create a PICT resource to serve as the foreground image. To demonstrate a different technique, though, in PixMapper we create the background image in our code. Figure 2 shows the PICT resource (an image we copied from the Scrapbook) moving over the background (which is simply a checkerboard pattern drawn with few calls to QuickDraw routines).

Figure 2. PixMapper in action.

As soon as you run PixMapper the menu bar, featuring the Apple, File, Edit, and Help menus, appears. With the exception of the Quit item in the File menu, there's nothing of significance in these menus. Next, a window appears, filling the entire main screen (the screen with the menu bar). PixMapper fills the window with a checkerboard pattern of red and green colored squares (just in time for Christmas, of course!). PixMapper then loads a PICT resource, and uses a series of offscreen GWorlds to animate the PICT across the colored background. The animation begins in the upper left corner and moves towards the lower right. Every time the PICT hits the edge of the window, the PICT bounces off and continues in the opposite direction.

The speed of the foreground image depends on the speed of your machine and the size of the PICT. The important thing to notice is that the PICT animates smoothly with absolutely no flicker. If there is any hesitation, it is most likely due to the system taking time to do some housekeeping chore.

Creating the PixMapper Resources

To get started, open your CodeWarrior development folder and create a folder named PixMapper. Start up ResEdit and create a new resource file named PixMapper.rsrc inside the PixMapper folder. Figure 3 shows the five types of resources used by PixMapper. By now you should be experienced in creating and working with each of these resource types.

Figure 3. The PixMapper resources.

Figure 3 shows the three MENU resources the program needs. Only the Quit item in the File menu is of significance - the other items exist in preparation for turning PixMapper into a "real" program.

PixMapper uses the same ALRT and DITL resources that have been used in recent Getting Started examples. The one ALRT and one DITL are used to support the error-handling alert displayed by the program's DoError() routine (see the September 1998 Apple Events Getting Started column for more information on these resources and on the DoError() routine).

The one WIND resource will be used to display the color animation. The size of the WIND isn't at all important - we'll be resizing the window from within the source code. Since the window will be fixed on the screen, the type of WIND isn't too important either, though you'll want to choose a type that foregoes the drag bar (title bar) so the user doesn't get the impression that the window is movable.

You need a single PICT resource to serve as the foreground image. In the PixMapper source code we'll be referencing this resource by an ID of 128, so make sure to assign the PICT that value. For the foreground image you'll want something relatively small. Of course to witness the power of the PixMapper program you'll want to use a color image. You might also consider using a picture that is non-rectangular or that has a hole in it. In your paint program use the lasso tool to select only the pixels in the picture (and not the background). Though a rectangular picture will work just fine, a non-rectangular picture (like an X or an O shape) produces much more impressive results.

That's it for the PixMapper.rsrc file. Now quit ResEdit, making sure to first save your changes.

Creating the PixMapper Project

Launch CodeWarrior and create a new project based on the MacOS:C_C++:MacOS Toolbox:MacOS Toolbox Multi-Target stationary. You should have already created a project folder, so uncheck the Create Folder check box. Name the project PixMapper.mcp and designate the PixMapper folder as the project's destination. Remove the SillyBalls.c and SillyBalls.rsrc placeholder files from the new project window, then add the PixMapper.rsrc file. The PixMapper project doesn't use of any of the standard ANSI libraries, so feel free to remove the ANSI Libraries folder.

Now choose New from the File menu to create a new, empty source code window. Save it with the name PixMapper.c and then choose Add Window from the Project menu to add the file to the project. The full source code listing for the PixMapper program appears next in the source code walk-through. You can type it into the PixMapper.c file as you read the walk-through, or you can take a shortcut and download the entire PixMapper project from MacTech's ftp site at ftp://ftp.mactech.com/src/mactech/volume14_1998/14.12.sit.

Walking Through the Source Code

On to the code. As with other Getting Started projects, PixMapper starts off with some constant definitions.

/********************* constants *********************/

#define kMBARResID            128
#define kALRTResID            128
#define kWINDResID            128

#define kSleep                7
#define   kMoveToFront        (WindowPtr)-1L

#define kSquareSize           16

#define kForegroundPICT       128
#define kIgnored              nil
#define kUseMaxDepth          0

#define mApple                128
#define iAbout                1

#define mFile                 129
#define iQuit                 1

There is a bunch of globals used by PixMapper. The familiar gDone starts life as false and is set to true when Quit is selected from the File menu. The program's only window is kept track of using the WindowPtr variable gMainWindow. Variables gXBump and gYBump specify the number of pixels the PICT moves each new animation cycle. One way to speed up the animation is to raise the bump values, though the code was written to work with single pixel movements.

/****************** global variables *****************/

Boolean           gDone;
WindowPtr         gMainWindow;
short             gXBump = 1, gYBump = 1;

We'll use three GWorlds. The graphics world gPictWorld holds the PICT image. Graphics world gSaveWorld holds the background of the window for later restoration. Finally, gSaveMixWorld is used to combine the PICT and the background. The three PixMapHandles are handles to the PixMaps tied to their respective GWorld.

GWorldPtr         gPictWorld;
GWorldPtr         gSaveWorld;
GWorldPtr         gSaveMixWorld;
PixMapHandle      gPixMapSave;
PixMapHandle      gPixMapSaveMix;
PixMapHandle      gPixMapPict;

The rectangle gPictWorldRect is the exact size of the PICT and is the bounding rectangle for gPictWorld. Rectangle gWorldRect is the bounding Rect for the mixing GWorld. The mixing GWorld is one pixel bigger in all directions than the PICT. This was done so that when we save a region the size of gWorldRect from the PixMapper window, we'll have a one pixel border around the PICT. This way, when the PICT moves one pixel in any direction, we'll have the right pixels saved for later restoration. You'll see how this works later in the code. Rectangle gSavedFloaterRect contains the current position of the PICT in the PixMapper window.

Rect                  gPictWorldRect;
Rect                  gWorldRect;
Rect                  gSavedFloaterRect;

Next come the program's function prototypes:

/********************* functions *********************/
void            ToolBoxInit( void );
void            MenuBarInit( void );
Boolean      HasGWorlds( void );
void            CreateWindow( void );
void            PaintWindow( void );
void            GWorldInit( void );
GWorldPtr    MakeGWorld( Rect *boundsPtr );
void            DrawFirstFloater( void );
void            MoveFloater( void );
void            CalcNewFloaterPosition( void );
void            EventLoop( void );
void            DoEvent( EventRecord *eventPtr );
void            HandleMouseDoWn( EventRecord *eventPtr );
void            HandleMenuChoice( long menuChoice );
void            HandleAppleChoice( short item );
void            HandleFileChoice( short item );
void            DoError( Str255 errorString );

As always, main() begins by initializing the Toolbox.

/************************ main ***********************/

void   main( void )
{
   ToolBoxInit();

Next, HasGWorlds() is called to see if GWorlds are available on this machine. We'll look at HasGWorlds() just ahead.

   if ( ! HasGWorlds() )
      DoError( "\pDeep GWorlds not supported" );

If so, the menu bar is set up, the main window is created, and the three graphics worlds are created. Both CreateWindow() and GWorldInit() are discussed later in this walk-through.

   MenuBarInit();
   CreateWindow();
   GWorldInit();

Next, the initial position of the PICT is plotted and the main animation loop is entered. The word floater refers to the foreground PICT, which appears to float over the background.

   DrawFirstFloater();
   
   EventLoop();
}

ToolBoxInit() and MenuBarInit() are the same as prior versions.

/******************** ToolBoxInit ********************/

void   ToolBoxInit( void )
{
   InitGraf( &qd.thePort );
   InitFonts();
   InitWindows();
   InitMenus();
   TEInit();
   InitDialogs( NULL );
   InitCursor();
}

/******************** MenuBarInit ********************/

void   MenuBarInit( void )
{
   Handle         menuBar;
   MenuHandle      menu;
   
   menuBar = GetNewMBar( kMBARResID );
   SetMenuBar( menuBar );

   menu = GetMenuHandle( mApple );
   AppendResMenu( menu, 'DRVR' );
   
   DrawMenuBar();
}

HasGWorlds() calls Gestalt() using the selector gestaltQuickdrawFeatures. If Gestalt() returns an error we'll display an appropriate error message.

/********************* HasGWorlds ********************/

Boolean   HasGWorlds( void )
{
   long      response;
   long      mask;
   OSErr   err;
   
   err = Gestalt( gestaltQuickdrawFeatures, &response );
   
   if ( err != noErr )
      DoError( "\pError calling Gestalt()" );

Next, we'll set up a comparison mask so we can look at the appropriate bit in response. Since gestaltHasDeepGWorlds has a value of 1, we'll want to look at bit number 1, which is the second bit from the right. We'll use the << operator to set bit number 1 in mask, leaving mask with a value of 2.

   mask = 1 << gestaltHasDeepGWorlds;

Finally, we'll use mask to see if bit number 1 is set in response. If so, deep GWorlds are available and we'll return true. Otherwise, we'll return false.

   if ( response & mask )
      return true;
   else
      return false;
}

CreateWindow() creates a new color window a little shorter than the main screen. The top of the window starts just below the menu bar. After setting up the window's size, a call to GetNewCWindow() creates a new CWindowRecord (as opposed to the WindowRecord that would result from a call to GetNewWindow()).

/******************* CreateWindow ********************/

void   CreateWindow( void )
{
   Rect      wBound;
   long      wWidth, wHeight;
   
   wBound = qd.screenBits.bounds;
   wBound.top += GetMBarHeight();
         
   gMainWindow = GetNewCWindow(    kWINDResID, nil,
                                   kMoveToFront);

The window is based on a WIND resource. Recall that we chose an arbitrary size for the window when creating this resource. Now it's time to match the window size to the size of the user's screen. The window boundary calculations are based of the wBound rectangle, which holds the display area of the graphics device (less the menu bar height). Finally, a call to PaintWindow() fills the window with colored rectangles.

   wWidth = wBound.right - wBound.left;
   wHeight = wBound.bottom - wBound.top;
   
   SizeWindow( gMainWindow, wWidth, wHeight, true );
   MoveWindow( gMainWindow, wBound.left, wBound.top, true );
   
   ShowWindow( gMainWindow );
   SetPort( gMainWindow );

   PaintWindow();
}

PaintWindow() starts by declaring several variables and calculating the number of columns and rows in the PixMapper window.

/******************** PaintWindow ********************/

void   PaintWindow( void )
{
   RGBColor      redColor  = {65535, 0, 0};
   RGBColor      greenColor = {0, 40000, 15000};
   RGBColor      currentColor;
   Rect            r;
   short         row, col, numRows, numCols;
   
   SetPort( gMainWindow );
   
   r = gMainWindow->portRect;

Both numCols and numRows are based on kSquareSize. Each square on the window will be kSquareSize pixels on a side. If either numCols or numRows is not evenly divisible by kSquareSize, we'll add another row or column just so we don't leave any white space at the edge of the window.

   numCols = (r.right - r.left) / kSquareSize;
   if ( numCols != numCols/kSquareSize * kSquareSize )
      numCols++;
      
   numRows = (r.bottom - r.top) / kSquareSize;
   if ( numRows != numRows/kSquareSize * kSquareSize )
      numRows++;

Next, we'll step through all the squares, drawing each in the color appropriate to create a red and green checkerboard pattern. First, we set up the boundaries of a single square.

   for ( row = 0; row < numRows; row++ )
      for ( col = 0; col < numCols; col++ )
      {
         r.top = row * kSquareSize;
         r.bottom = r.top + kSquareSize;
         r.left = col * kSquareSize;
         r.right = r.left + kSquareSize;

Now, we determine whether the square should be red or green. Recall from your C background that the modulus operator (%) returns the remainder of an integral division. So, for example, if row is even and we divide by 2, the modulus result is 0 (no remainder). If row is odd when we divide by 2, the modulus is always 1. The following could be written a little more compact then it now appears, but the result would be even more confusing!

         if ( ( row % 2 == 1 ) && ( col % 2 == 1 ) )
            currentColor = redColor;
         else if ( ( row % 2 == 0 ) && ( col % 2 == 0 ))
            currentColor = redColor;
         else
            currentColor = greenColor;

A call to RGBForeColor() is made to set up subsequent drawing in the appropriate color. Recall from last month that RGBForeColor() is the QuickDraw routine that accepts an RGB color as its parameter. A call to the QuickDraw function PaintRect() actually draws the colored rectangle.

         RGBForeColor( &currentColor );
         
         PaintRect( &r );
      }

When we're done, we set the foreground and background colors to their normal values. QuickDraw defines eight global constants to represent eight very basic colors (including black and white - refer to the QuickDraw.h universal header file for the rest). The QuickDraw routines ForeColor() and BackColor() are used with any of these eight constants to set the foreground color (the color used for drawing) and the background color (the color used to repaint a window's content area). Note that we could have used RGBForeColor() and RGBBackColor() here, provided we set up and specified black and white as RGBColor variables.

   ForeColor( blackColor );
   BackColor( whiteColor );
}

Now it's time to look at some code that involves graphics worlds. The three GWorlds are created in GWorldInit(), a routine that was called from main(). GWorldInit() starts by loading the PICT resource.

/********************* GWorldInit ********************/

void   GWorldInit( void )
{
   PicHandle      pic;
   
   pic = GetPicture( kForegroundPICT );

   if ( pic == nil )
      DoError( "\pError loading PICT..." );

We'll grab the PICT's frame and normalize it (make its upper left corner (0,0)).

   gPictWorldRect = (**pic).picFrame;
   OffsetRect(    &gPictWorldRect, -gPictWorldRect.left, 
                     -gPictWorldRect.top );

gWorldRect is set to be 2 pixels taller and 2 pixels wider than the PICT. That leaves a one pixel border all the way around.

   gWorldRect = gPictWorldRect;
   gWorldRect.bottom += 2;
   gWorldRect.right += 2;

Next, we'll call our own MakeGWorld() routine to build one GWorld the size of the PICT and two the size of gWorldRect, storing the pointers in our three globals.

   gPictWorld = MakeGWorld( &gPictWorldRect );
   gSaveWorld = MakeGWorld( &gWorldRect );
   gSaveMixWorld = MakeGWorld( &gWorldRect );

When we create a GWorld, a PixMap is created for us. We'll call GetGWorldPixMap() to store the handle to each PixMap in its respective global.

   gPixMapPict = GetGWorldPixMap( gPictWorld );
   gPixMapSave = GetGWorldPixMap( gSaveWorld );
   gPixMapSaveMix = GetGWorldPixMap( gSaveMixWorld );

Next, we'll lock all three PixMaps in memory. Why? Just as you'd lock a handle before you singly dereferenced it to access its pointer, you lock your PixMap before you draw into it. Normally, you'd lock the pixels just before you draw, then unlock the pixels after the call to the drawing routine returns to prevent heap fragmentation. To keep things simple, we're just going to lock all three PixMaps for the duration of the program.

   if ( ! LockPixels( gPixMapPict ) )
      DoError( "\pLockPixels failed..." );

   if ( ! LockPixels( gPixMapSave ) )
      DoError( "\pLockPixels failed..." );

   if ( ! LockPixels( gPixMapSaveMix ) )
      DoError( "\pLockPixels failed..." );

Finally, we'll make the gPictWorld the current GWorld and draw the PICT in it. SetGWorld() makes the specified GWorld the current port, just as a call to SetPort() might make a window the current port.

   SetGWorld( gPictWorld, kIgnored );
      
   DrawPicture( pic, &gPictWorldRect );
}

MakeGWorld() calls NewGWorld() to create a new GWorld, returning a pointer to the new GWorld. The first parameter is the address of the GWorldPtr that will eventually point to the new GWorld. The second parameter specifies the pixel depth of the new GWorld. By passing in a value of 0, we're asking NewGWorld() to use the deepest device that intersects boundsPtr, the third parameter. The fourth and fifth parameters specify a color table and a GDevice, in case you want to roll your own. We'll pass nil in for each, asking NewGWorld() to take care of these parameters for us. The final parameter lets us set special GWorld flags. We'll pass in 0, ignoring the flags. You can read about these flags in the description of NewGWorld() in the Offscreen Graphics Worlds chapter of Inside Macintosh: Imaging With QuickDraw.

/********************* MakeGWorld ********************/

GWorldPtr MakeGWorld( Rect *boundsPtr )
{
   QDErr         err;
   GWorldPtr   newGWorld;

   err = NewGWorld( &newGWorld, kUseMaxDepth,
            boundsPtr, kIgnored, kIgnored, noNewDevice );
            
   if ( err != noErr )
      DoError( "\pMy call to NewGWorld died! Bye..." );
   
   return( newGWorld );
}

Here, in DrawFirstFloater(), comes the really important stuff. Just as it did in BitMapper, CopyBits() is used to copy a block of pixels from one offscreen to another. Though CopyBits() expects to work with pointers to BitMaps, it can handle either BitMaps or PixMaps. A bit of typecasting is necessary, however, if only to placate the compiler's typecasting mechanism.

/****************** DrawFirstFloater *****************/

void   DrawFirstFloater( void )
{

Each call to CopyBits() copies from the first parameter to the second, using the Rects in the third and fourth parameters. The srcCopy mode tells CopyBits() to replace all the destination bits with the appropriate source bits. The transparent mode, on the other hand, tells the compiler not to copy the white pixels. This comes in handy when we copy a non-rectangular or non-solid image from one GWorld to another. The last parameter to CopyBits() specifies an optional mask parameter which we won't use. Passing nil tells CopyBits() to ignore this parameter.

The first call to CopyBits() copies the background of the PixMapper window into the gPixMapSave PixMap. We're saving away the pixels we're about to obliterate with the PICT, with an extra one pixel border we'll need when the floater moves in one direction or the other.

   CopyBits(    &(gMainWindow->portBits), 
                  (BitMap *)(*gPixMapSave),
                  &gWorldRect, &gWorldRect, srcCopy, nil );

Next, we'll set up a Rect the size of the PICT that is 1 pixel down and 1 pixel to the right of the upper left corner of the window. This is where we'll plot the PICT.

   gSavedFloaterRect = gPictWorldRect;
   OffsetRect( &gSavedFloaterRect, 1, 1 );

This call to CopyBits() draws the PICT in the PixMapper window.

   CopyBits(    (BitMap *)(*gPixMapPict), 
                  &(gMainWindow->portBits),
                  &gPictWorldRect, &gSavedFloaterRect, 
                  transparent, nil );
}

MoveFloater() is responsible for moving the foreground image. Because the image is moved only slightly, MoveFloater() gets called repeatedly from the event loop. MoveFloater() starts off by calling CalcNewFloaterPosition() to update the values of gXBump and gYBump, in case the floater is hitting the edge of the window.

/******************** MoveFloater ********************/

void   MoveFloater( void )
{
   Rect      r;
   RgnHandle   newRgn, savedRgn, oldClip;

   CalcNewFloaterPosition();

This call to CopyBits() copies the saved pixels to the mixer GWorld.

   CopyBits(    (BitMap *)(*gPixMapSave), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gWorldRect, &gWorldRect, srcCopy, nil );

Next, we position a Rect the size of the PICT in the mix GWorld using gXBump and gYBump. This Rect is the new position of the floater in the mix GWorld. We'll then call CopyBits() to copy the floater on top of the saved pixels in the mixing GWorld. Remember, we used transparent mode so we'd only draw the non-background pixels. You might want to handle this differently if you need to draw white pixels.

   r = gPictWorldRect;
   OffsetRect( &r, gXBump + 1, gYBump + 1 );
   
   CopyBits(    (BitMap *)(*gPixMapPict), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gPictWorldRect, &r, transparent, nil );

Next, we construct a Rect at the floater's last position in the PixMapper window, then make it one pixel bigger in all directions (the size of the mixing GWorld). We're going to use this Rect to copy the contents of the mixing GWorld into the window.

   r = gSavedFloaterRect;
   InsetRect( &r, -1, -1 );

   CopyBits(    (BitMap *)(*gPixMapSaveMix), 
                  &(gMainWindow->portBits),
                  &gWorldRect, &r, srcCopy, nil );

Now we update the saved floater position stored in gSavedFloaterRect to reflect the new position.

   OffsetRect( &gSavedFloaterRect, gXBump, gYBump );

Following that, we create our one pixel bigger Rect again, this time at the floater's new position. We then copy the floater, with a one pixel border, into the mixing GWorld.

   r = gSavedFloaterRect;
   InsetRect( &r, -1, -1 );
   
   CopyBits(    &(gMainWindow->portBits), 
                  (BitMap *)(*gPixMapSaveMix),
                  &r, &gWorldRect, srcCopy, nil );

Next, copy the saved pixels into the appropriate position in the mixing GWorld. The idea here is that we are reconstructing the pixels that should be behind the floater.

   r = gWorldRect;
   OffsetRect( &r, -gXBump, -gYBump );
   
   CopyBits(    (BitMap *)(*gPixMapSave), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gWorldRect, &r, srcCopy, nil );

Finally, we copy the reconstructed "behind the floater" pixels from the mix GWorld into the save GWorld. We are now ready to move the floater all over again.

   CopyBits(    (BitMap *)(*gPixMapSaveMix), 
                  (BitMap *)(*gPixMapSave),
                  &gWorldRect, &gWorldRect, srcCopy, nil );
}

This routine figures out if bumping the floater will move it off the edge of the window in any direction. If so, the direction of floater movement is changed, so the floater moves away from that edge, rather than towards it.

/*************** CalcNewFloaterPosition **************/

void   CalcNewFloaterPosition( void )
{
   Rect   r;
   
   r = gSavedFloaterRect;
   
   OffsetRect( &r, gXBump, gYBump );
   
   if (   (r.left < gMainWindow->portRect.left) ||
         ( r.right > gMainWindow->portRect.right ) )
      gXBump *= -1;
   
   if (   (r.top < gMainWindow->portRect.top) ||
         ( r.bottom > gMainWindow->portRect.bottom ) )
      gYBump *= -1;
}

At this point we're home free. The remaining code, with a single exception, is all "copy and paste" code from other Getting Started examples. The exception appears in EventLoop(). It's here that we repeatedly call MoveFloater() to keep the animation running. Only when the user quits does the animation loop end.

/********************** EventLoop ********************/

void   EventLoop( void )
{      
   EventRecord      event;
   
   gDone = false;
   while ( gDone == false )
   {
      if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
         DoEvent( &event );

      MoveFloater();
   }
}

/*********************** DoEvent *********************/

void   DoEvent( EventRecord *eventPtr )
{
   char   theChar;
   
   switch ( eventPtr->what )
   {
      case mouseDown: 
         HandleMouseDown( eventPtr );
         break;
      case keyDown:
      case autoKey:
         theChar = eventPtr->message & charCodeMask;
         if ( (eventPtr->modifiers & cmdKey) != 0 ) 
         HandleMenuChoice( MenuKey( theChar ) );
         break;
      case updateEvt:
         BeginUpdate( (WindowPtr)(eventPtr->message) );
         EndUpdate( (WindowPtr)(eventPtr->message) );
         break;
   }
}

/******************* HandleMouseDown *****************/

void   HandleMouseDown( EventRecord *eventPtr )
{
   WindowPtr      window;
   short          thePart;
   long           menuChoice;
   
   thePart = FindWindow( eventPtr->where, &window );
   
   switch ( thePart )
   {
      case inMenuBar:
         menuChoice = MenuSelect( eventPtr->where );
         HandleMenuChoice( menuChoice );
         break;
      case inSysWindow : 
         SystemClick( eventPtr, window );
         break;
   }
}

/******************* HandleMenuChoice ****************/

void   HandleMenuChoice( long menuChoice )
{
   short   menu;
   short   item;
   
   if ( menuChoice != 0 )
   {
      menu = HiWord( menuChoice );
      item = LoWord( menuChoice );
      
      switch ( menu )
      {
         case mApple:
            HandleAppleChoice( item );
            break;
         case mFile:
            HandleFileChoice( item );
            break;
      }
      HiliteMenu( 0 );
   }
}

/****************** HandleAppleChoice ****************/

void   HandleAppleChoice( short item )
{
   MenuHandle   appleMenu;
   Str255       accName;
   short        accNumber;
   
   switch ( item )
   {
      case iAbout:
         SysBeep( 10 );
         break;
      default:
         appleMenu = GetMenuHandle( mApple );
         GetMenuItemText( appleMenu, item, accName );
         accNumber = OpenDeskAcc( accName );
         break;
   }
}

/******************* HandleFileChoice ****************/

void   HandleFileChoice( short item )
{
   switch ( item )
   {
      case iQuit:
         gDone = true;
         break;
   }
}

/*********************** DoError *********************/

void   DoError( Str255 errorString )
{
   ParamText( errorString, "\p", "\p", "\p" );
   
   StopAlert( kALRTResID, nil );
   
   ExitToShell();
}

Running PixMapper

Run PixMapper by selecting Run from the Project menu. Once your code compiles, a window appears with a checkerboard pattern drawn in it. The window will be the exact size of your screen. The animation begins automatically. As the foreground image moves, notice that the background shows through the image openings. Choose Quit from the File menu to end the animation and the program.

Till Next Month...

PixMap data structures and graphics worlds can be tricky to work with, but the PixMapper code should give you a good base for creating your own animated effects. Don't worry too much about the specifics of the PixMapper algorithm. The important things to understand are how to construct a GWorld, how to use CopyBits() to copy PixMaps between GWorlds and windows, and the basics of working with color. You can get more information on the PixMap data structure in the Color QuickDraw chapter of Inside Macintosh: Imaging With QuickDraw. The QuickDraw Drawing chapter of that same volume discusses the all-important CopyBits() routine. For more on graphics worlds, read the Offscreen Graphics Worlds chapter of Imaging With QuickDraw.

If you want to turn PixMapper into a more useful program, provide the user with some control of the animation. PixMapper's MoveFloater() routine is responsible for creating one "frame" in an animated sequence, and is called repeatedly from EventLoop(). Be aware that while a routine like MoveFloater() needs to be called from within a loop to achieve an animated effect, that loop doesn't have to be the event loop. Try adding an Animation menu and then moving the call to a routine that handles a selection from that menu.

If PixMapper seems somewhat slow to you, there's a reason for that. CopyBits() is a general purpose routine designed to handle all color environments and both BitMaps and PixMaps. There are also many ways you can improve the performance of the basic PixMapper algorithm, though that tends to make the code even more confusing. One simple way to speed things up a bit is to increase the value of both the gXBump and gYBump global variables. To maintain smooth animation, you'll also have to alter a little bit of the code. Hint: It's no coincidence that as written, gXBump and gYBump both have a value of 1, and the global variable gWorldRect is set up to be one pixel larger in each direction then the foreground image.

These suggestions should provide you with plenty to do until next month's column. See you then...

 
AAPL
$111.78
Apple Inc.
-0.87
MSFT
$47.66
Microsoft Corpora
+0.14
GOOG
$516.35
Google Inc.
+5.25

MacTech Search:
Community Search:

Software Updates via MacUpdate

Monolingual 1.6.2 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
NetShade 6.1 - Browse privately using an...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
calibre 2.13 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Evernote 6.0.5 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more

Latest Forum Discussions

See All

Make your own Tribez Figures (and More)...
Make your own Tribez Figures (and More) with Toyze Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
So Many Holiday iOS Sales Oh My Goodness...
The holiday season is in full-swing, which means a whole lot of iOS apps and games are going on sale. A bunch already have, in fact. Naturally this means we’re putting together a hand-picked list of the best discounts and sales we can find in order... | Read more »
It’s Bird vs. Bird in the New PvP Mode f...
It’s Bird vs. Bird in the New PvP Mode for Angry Birds Epic Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Telltale Games and Mojang Announce Minec...
Telltale Games and Mojang Announce Minecraft: Story Mode – A Telltale Games Series Posted by Jessica Fisher on December 19th, 2014 [ permalink ] | Read more »
WarChest and Splash Damage Annouce Their...
WarChest and Splash Damage Annouce Their New Game: Tempo Posted by Jessica Fisher on December 19th, 2014 [ permalink ] WarChest Ltd and Splash Damage Ltd are teaming up again to work | Read more »
BulkyPix Celebrates its 6th Anniversary...
BulkyPix Celebrates its 6th Anniversary with a Bunch of Free Games Posted by Jessica Fisher on December 19th, 2014 [ permalink ] BulkyPix has | Read more »
Indulge in Japanese cuisine in Cooking F...
Indulge in Japanese cuisine in Cooking Fever’s new sushi-themed update Posted by Simon Reed on December 19th, 2014 [ permalink ] Lithuanian developer Nordcurrent has yet again updated its restaurant simulat | Read more »
Badland Daydream Level Pack Arrives to C...
Badland Daydream Level Pack Arrives to Celebrate 20 Million Downloads Posted by Ellis Spice on December 19th, 2014 [ permalink ] | Read more »
Far Cry 4, Assassin’s Creed Unity, Desti...
Far Cry 4, Assassin’s Creed Unity, Destiny, and Beyond – AppSpy Takes a Look at AAA Companion Apps Posted by Rob Rich on December 19th, 2014 [ permalink ] These day | Read more »
A Bunch of Halfbrick Games Are Going Fre...
A Bunch of Halfbrick Games Are Going Free for the Holidays Posted by Ellis Spice on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

The Apple Store offering free next-day shippi...
The Apple Store is now offering free next-day shipping on all in stock items if ordered before 12/23/14 at 10:00am PT. Local store pickup is also available within an hour of ordering for any in stock... Read more
It’s 1992 Again At Sony Pictures, Except For...
Techcrunch’s John Biggs interviewed a Sony Pictures Entertainment (SPE) employee, who quite understandably wished to remain anonymous, regarding post-hack conditions in SPE’s L.A office, explaining “... Read more
Holiday sales this weekend: MacBook Pros for...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sales this weekend: MacBook Airs for...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
Holiday sales this weekend: iMacs for up to $...
B&H Photo has 21″ and 27″ iMacs on sale for up to $200 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 1.4GHz... Read more
Holiday sales this weekend: Mac minis availab...
B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off MSRP... Read more
Holiday sales this weekend: Mac Pros for up t...
B&H Photo has Mac Pros on sale for up to $500 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2599, $400 off MSRP - 3.5GHz 6-core Mac Pro: $3499, $... Read more
Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more

Jobs Board

*Apple* Store Leader Program (US) - Apple, I...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on experience, Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.