TweetFollow Us on Twitter

Bitmapper
Volume Number:9
Issue Number:9
Column Tag:Getting Started

Related Info: Window Manager Color QuickDraw Graphics Devices Quickdraw

Flicker-Free Bitmap animation

You too can do those really cool graphics that are smooooth

By Dave Mark, MacTech Magazine Regular Contributing Author

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Lately, I’ve been getting lots of mail asking about Macintosh animation. Since that was the topic of my presentation at the MacTech Magazine Live! session at this past MacWorld, I thought the time might be right for a series of articles discussing this deep, dark, Macintosh programming mystery. This column (which started life in an old issue of SPLAsh magazine, just in case it looks a little familiar) starts with the basics, covering black and white animation using quickdraw BitMaps. In later columns, once we cover color quickdraw, we’ll revisit this topic, expanding the techniques to include PixMap animation.

What the Heck is Bitmap Animation?

If you’ve ever written an arcade game, you’ve probably tried your hand at bitmap animation, where a bitmap image appears to move over a stationary background. Your Mac’s cursor is a perfect example. As the cursor moves around the screen, it appears to float over the background without flickering. Take a look at this sequence of pictures:

(a) (b) (c)

Figure (a) shows an arrow cursor partially obscuring my hard drive icon. Once the cursor moves, it leaves an area of the hard drive icon undrawn (b). Before this hole gets noticed, the System fills it back up with its previous contents (c).

Most programs deal with repainting the screen by responding to updateEvts generated by the Window Manager. When an area of a window that was previously obscured needs to be redrawn, the Window Manager adds the newly revealed area to the window’s update region and generates an updateEvt for the window.

The problem with this approach is that update events take time. It takes time for the Window Manager to calculate the update region and it takes time to post an event. More importantly, it takes time for your program to respond to an update event. If your program is busy responding to another event, the update event might sit in the queue for a while, leaving the window undrawn until you get around to fixing it.

When you’ve got a rocket ship shooting across a planet’s surface, you don’t want to leave any holes in the planet, waiting for your program to respond to an update event. You want to fill in the holes in real time, just like the System does when it handles your cursor.

The Off-Screen Bitmap Solution

The solution to this problem lies in the use of off-screen bitmaps. An off-screen bitmap is a bitmap that is drawn in memory, but does not appear on screen. In this month’s program, we’ll create three off-screen bitmaps. One of these will act as a master image, which we’ll constantly copy to a window that does appear on the screen. The second bitmap will hold a background image and the third will hold the foreground image. Our goal is to make the foreground image track the cursor, appearing to float on top of the background image.

Here’s a snapshot of our program in action:

The floating hand is our foreground image. 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. Here’s how this works.

The Basic Approach

We’ll start by creating the off-screen bitmaps for the foreground and background. Next, we create the master bitmap, which we’ll use to mix our foreground and background. In a loop, we copy the background to the mixer, then copy the foreground to the mixer, on top of the background. Still inside the loop, we copy the mixed image to the window. This loop continues until we click the mouse button.

Even though we are constantly updating the image in the window, there is a minimum of flicker. Why? Well, it helps to understand what causes flicker in the first place. Imagine if you tried to simulate the floating image by constantly drawing the background, then the foreground, images in an endless loop. For example, here’s a sequence using a black background and a white triangular foreground:

(a) (b) (c)

Figure (a) shows the triangle on the black background. Figure (b) shows the screen when you draw the background again. Finally, (c) shows the screen after you redrew the foreground again. The point here is that using this approach, every other image will be completely black. The foreground image will flicker in and out of view.

To convince yourself, write a program that draws a pair of PICTs in a window, in an endless loop. First draw one PICT, then the other, one on top of the other. Without off-screen bitmaps, you can minimize flicker, but there’s no way to avoid it altogether.

BitMapper

OK, let’s get on with the program. Create a folder named BitMapper inside your Development folder. Open up ResEdit and create a new resource file named BitMapper.Π.rsrc inside the BitMapper folder.

Next, create two PICT resources, numbered 128 and 129. PICT 128 will be the background image, so make it larger than PICT 129, which will serve as the foreground image. If you’ve got a graphics program like MacPaint or Canvas, create your background by drawing a nice frame, then pasting another image inside it. Copy the whole thing to the clipboard, then paste it inside ResEdit.

For the foreground, you’ll want something relatively small. Use whatever image you like, but be sure to make it resource ID 129. Note that both images should be black and white only, and not color or gray-scale. You can use a color image, but all colored pixels will be translated to black, so things might not come out as you planned them to.

Once your PICT images are in place, quit ResEdit, making sure you save your changes. Now launch THINK C and create a new project named BitMapper.Π in the BitMapper folder. Select New from the File menu and, when the new source code window appears, type in this source code:


/* 1 */

#define kMoveToFront (WindowPtr)-1L

const short kBackgroundPictID =    128;
const short kForegroundPictID =    129;


/***************/
/*  Functions  */
/***************/

void    ToolboxInit( void );
WindowPtr WindowInit( void );
PicHandle LoadPicture( short resID );
GrafPtr CreateBitMap( const Rect *rPtr );


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

void  main( void )
{
 Rect   r;
 GrafPtrbackPortPtr, forePortPtr, mixerPortPtr;
 WindowPtrwindow;
 PicHandlebackPict, forePict;
 Point  p;
 
 ToolboxInit();
 window = WindowInit();
 
 backPict = LoadPicture( kBackgroundPictID );
 r = (**backPict).picFrame;
 OffsetRect( &r, -r.left, -r.top );
 
 /* Leaves backPortPtr as current port */
 backPortPtr = CreateBitMap( &r ); 
 DrawPicture( backPict, &r );
 
 /* Leaves mixerPortPtr as current port */
 mixerPortPtr = CreateBitMap( &r );
 
 forePict = LoadPicture( kForegroundPictID );
 r = (**forePict).picFrame;
 OffsetRect( &r, -r.left, -r.top );
 
 /* Leaves forePortPtr as current port */
 forePortPtr = CreateBitMap( &r );
 DrawPicture( forePict, &r );
 
 HideCursor();
 
 while ( !Button() )
 {
 CopyBits( &(backPortPtr->portBits),
 &(mixerPortPtr->portBits),
 &(backPortPtr->portBits.bounds),
 &(mixerPortPtr->portBits.bounds), srcCopy, nil );
 
 GetMouse( &p );
 SetPort( window );
 GlobalToLocal( &p );
 r = forePortPtr->portBits.bounds;
 OffsetRect( &r, p.h, p.v );
 
 CopyBits( &(forePortPtr->portBits), 
 &(mixerPortPtr->portBits),
 &(forePortPtr->portBits.bounds), &r,
 srcOr, nil );
 
 CopyBits( &(mixerPortPtr->portBits), &(window->portBits),
 &(mixerPortPtr->portBits.bounds), 
 &(window->portRect), srcCopy, nil );
 }
}


/****************** ToolboxInit *********************/

void  ToolboxInit( void )
{
 InitGraf( &thePort );
 InitFonts();
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs( nil );
 InitCursor();
}


/****************** WindowInit ***********************/

WindowPtr WindowInit( void )
{
 WindowPtrwindow;
 PicHandlepic;
 Rect   r;
 
 pic = LoadPicture( kBackgroundPictID );
 r = (**pic).picFrame;
 
 OffsetRect( &r, 20 - r.left, 50 - r.top );
 
 window = NewWindow( nil, &r, "\pBitMapper", true, 
 noGrowDocProc, kMoveToFront, false, 0L );
 
 return( window );
}


/****************** LoadPicture *********************/

PicHandle LoadPicture( short resID )
{
 PicHandlepicture;
 
 picture = GetPicture( resID );
 
 if ( picture == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the PICT resource!!!  */
 ExitToShell();
 }
}


/****************** CreateBitMap *********************/

GrafPtr CreateBitMap( const Rect *rPtr )
{
 short  i;
 BitMap *bPtr;
 GrafPtrg;
 
 g = (GrafPtr)NewPtr( sizeof(GrafPort) );
 if ( g == nil )
 SysBeep(20);
 
 bPtr = (BitMap *)NewPtr( sizeof( BitMap ) );
 if ( bPtr == nil )
 SysBeep( 20 );
 bPtr->bounds = *rPtr;
 
 bPtr->rowBytes = (rPtr->right - rPtr->left + 7) /8;
 
 i = rPtr->bottom - rPtr->top;
 bPtr->baseAddr = NewPtr( bPtr->rowBytes * i );
 
 if ( bPtr->baseAddr == nil )
 SysBeep( 20 );
 
 OpenPort( g );
 SetPortBits( bPtr );
 
 return( g );
}

Once your source code is typed in, save it under the name BitMapper.c, then add the code to the project by selecting Add from the Source menu. Run BitMapper by selecting Run from the Project menu. Once your code compiles, a window should appear with your background PICT drawn in it. The window will be the exact size of the background PICT.

As you move the mouse, the foreground PICT should appear, following the mouse’s movement. Click the mouse to exit the program.

Walking Through the BitMapper Source Code

BitMapper starts off with a few constant definitions.

/* 2 */

#define kMoveToFront (WindowPtr)-1L

const short kBackgroundPictID =    128;
const short kForegroundPictID =    129;

These are followed by BitMapper’s function prototypes.

/* 3 */

/***************/
/*  Functions  */
/***************/

void    ToolboxInit( void );
WindowPtr WindowInit( void );
PicHandle LoadPicture( short resID );
GrafPtr CreateBitMap( const Rect *rPtr );

main() starts off by initializing the Toolbox.

/* 4 */

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

void  main( void )
{
 Rect   r;
 GrafPtrbackPortPtr, forePortPtr, mixerPortPtr;
 WindowPtrwindow;
 PicHandlebackPict, forePict;
 Point  p;
 
 ToolboxInit();

Next, a window is created. The WindowPtr is returned and stored in the variable window.

/* 5 */

 window = WindowInit();

Next, the background PICT is loaded from the resource fork. The frame of the PICT (its bounding rectangle) is normalized, so its top and left are both 0.

/* 6 */

 backPict = LoadPicture( kBackgroundPictID );
 r = (**backPict).picFrame;
 OffsetRect( &r, -r.left, -r.top );

This normalized Rect is passed on to CreateBitMap(). CreateBitMap(), listed below, creates an off-screen GrafPort the size of the specified Rect. This GrafPort can be drawn in, just like a window’s GrafPort. You can use SetPort() on it, as well as all the standard Quickdraw routines such as DrawString() and DrawPicture(). While your drawing won’t appear on the screen, the drawing will affect the memory used to implement the GrafPort.

/* 7 */

 /* Leaves backPortPtr as current port */
 backPortPtr = CreateBitMap( &r );

CreateBitMap() returns a pointer to the newly created GrafPort. When CreateBitMap() returns, this port is made the current port. Next, DrawPicture() is called to draw the background PICT in the background GrafPort.

/* 8 */

 DrawPicture( backPict, &r );

Next, the master GrafPort is created. This GrafPort is used to merge the foreground PICT with the background PICT. Once again, when this call of CreateBitMap() returns, the new GrafPort is the current port.

/* 9 */

 /* Leaves mixerPortPtr as current port */
 mixerPortPtr = CreateBitMap( &r );

Just as we did with the background PICT, this next sequence of code loads the foreground PICT, creates a normalized bounding Rect, and finally creates a GrafPort for the foreground PICT.

/* 10 */

 forePict = LoadPicture( kForegroundPictID );
 r = (**forePict).picFrame;
 OffsetRect( &r, -r.left, -r.top );
 
 /* Leaves forePortPtr as current port */
 forePortPtr = CreateBitMap( &r );

The call of CreateBitMap() leaves forePortPtr as the current port. Next, DrawPicture() is used to draw the foreground picture in this newly created GrafPort.

/* 11 */

 DrawPicture( forePict, &r );

OK. That’s about all the preliminary stuff. Now we’re ready to animate. Before we do, we’ll use HideCursor() to make the cursor invisible.

/* 12 */

 HideCursor();

Next, we’ll enter a loop, waiting for the mouse button to be clicked.

/* 13 */

 while ( !Button() )
 {

At the heart of our program is the CopyBits() Toolbox routine. CopyBits() copies one Quickdraw BitMap to another. We’ll get into the BitMap data structure a bit later on. This call of CopyBits() copies the background BitMap into the mixer BitMap, using the bounding rectangle associated with each of the BitMaps. The srcCopy parameter specifies how the BitMap is copied. srcCopy tells CopyBits() to replace all bits in the destination BitMap’s rectangle with the bits in the source BitMap.

/* 14 */

 CopyBits( &(backPortPtr->portBits), 
 &(mixerPortPtr->portBits), 
 &(backPortPtr->portBits.bounds),
 &(mixerPortPtr->portBits.bounds), srcCopy, nil );

Next, we get the current position of the mouse, in global coordinates.

/* 15 */

 GetMouse( &p );

Next, set the port to the BitMapper window, then convert the mouse position to the window’s local coordinates.

/* 16 */

 SetPort( window );
 GlobalToLocal( &p );

Next, the foreground BitMap’s bounding rectangle is copied to a local variable, r, and offset by the mouse’s position. Basically, r is the same size as the foreground BitMap (the pointing hand), positioned on the background BitMap (which is the same size as the window) according to the current location of the mouse.

/* 17 */

 r = forePortPtr->portBits.bounds;
 OffsetRect( &r, p.h, p.v );

Next, the foreground BitMap is copied to the mixer BitMap, using r as the destination bounding rectangle. Notice the use of srcOr instead of srcCopy. This makes the foreground BitMap transparent. To see the effect this has, try changing the srcOr to srcCopy.

/* 18 */

 CopyBits( &(forePortPtr->portBits), 
 &(mixerPortPtr->portBits), 
 &(forePortPtr->portBits.bounds), &r,
 srcOr, nil );

Finally, the mixer BitMap is copied to the window. The loop works like this: Build the window’s image off-screen, copy the combined image to the window.

/* 19 */

 CopyBits( &(mixerPortPtr->portBits), &(window->portBits),
 &(mixerPortPtr->portBits.bounds), 
 &(window->portRect), srcCopy, nil );
 }
}

ToolboxInit() is the same as it ever was...

/* 20 */

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

void  ToolboxInit( void )
{
 InitGraf( &thePort );
 InitFonts();
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs( nil );
 InitCursor();
}

WindowInit() loads the background PICT, copying its framing rectangle into r.

/* 21 */

/****************** WindowInit ***********************/

WindowPtr WindowInit( void )
{
 WindowPtrwindow;
 PicHandlepic;
 Rect   r;
 
 pic = LoadPicture( kBackgroundPictID );
 r = (**pic).picFrame;

r is normalized, then offset 20 pixels from the left and 50 pixels from the top. r will be used to create a window the same size as the background PICT.

/* 22 */

 OffsetRect( &r, 20 - r.left, 50 - r.top );

NewWindow() is used to create the BitMapper window, using r as a bounding rectangle.

/* 23 */

 window = NewWindow( nil, &r, "\pBitMapper", true, 
 noGrowDocProc, kMoveToFront, false, 0L );

The WindowPtr is returned to the calling routine.

/* 24 */

 return( window );
}

LoadPicture() loads the specified PICT resource.

/* 25 */

/****************** LoadPicture *********************/

PicHandle LoadPicture( short resID )
{
 PicHandlepicture;
 
 picture = GetPicture( resID );

If the PICT wasn’t found, beep once, then exit.

 if ( picture == nil )
 {
 SysBeep( 10 );  /*  Couldn't load the PICT resource!!!  */
 ExitToShell();
 }
}

CreateBitMap() will create a new GrafPort() the size of the specified Rect. A BitMap is a Quickdraw data structure designed to hold a bitmap of an image one pixel deep (black and white). The BitMap is described in Inside Macintosh, Volume I, page 144, and in Inside Macintosh: Overview, page 91.

/* 26 */

/****************** CreateBitMap *********************/

GrafPtr CreateBitMap( const Rect *rPtr )
{
 short  i;
 BitMap *bPtr;
 GrafPtrg;

First, a new GrafPort is allocated using NewPtr(). If the memory couldn’t be allocated, beep once.

/* 27 */

 g = (GrafPtr)NewPtr( sizeof(GrafPort) );
 if ( g == nil )
 SysBeep(20);

Next, a BitMap data structure is allocated. Again, if the memory was not allocated, beep once. These beeps aren’t really effective. They’re put in place as a weak substitute for error checking. You’ll want to weave memory allocation failure into your overall error handling scheme.

/* 28 */

 bPtr = (BitMap *)NewPtr( sizeof( BitMap ) );
 if ( bPtr == nil )
 SysBeep( 20 );

Next, the specified rectangle is copied into the BitMap’s bounds field. This field specifies the coordinates bounding the BitMap.

/* 29 */

 bPtr->bounds = *rPtr;

The rowBytes field specifies how many bytes are used to store one row of the BitMap. For example, 0 through 8 pixels can be stored in 1 byte, 9 through 16 pixels in 2 bytes, etc.

/* 30 */

 bPtr->rowBytes = (rPtr->right - rPtr->left + 7) /8;

Next, i is set to the number of rows in the bounding rectangle, and i * rowBytes bytes are allocated for the bit image itself.

/* 31 */

 i = rPtr->bottom - rPtr->top;
 bPtr->baseAddr = NewPtr( bPtr->rowBytes * i );

Again, if the memory was not allocated, beep once.

/* 32 */

 if ( bPtr->baseAddr == nil )
 SysBeep( 20 );

Next, OpenPort() is called to initialize the new GrafPort, which is pointed to by g. OpenPort() leaves g as the current port. SetPortBits() ties the specified BitMap to the current port.

/* 33 */

 OpenPort( g );
 SetPortBits( bPtr );

Finally, we return a pointer to the newly allocated GrafPort.

/* 34 */

 return( g );
}

Till Next Month...

This sample code should get you on your way to successful bitmap animation. Once you’ve mastered this technique, you’re ready to tackle color animation by using PixMaps and the Toolbox routine CopyPixMap(). These are described in Inside Macintosh, Volume V. As I mentioned at the beginning of the column, we’ll eventually go over PixMap animation, but first we’ll have to cover the basics of programming with color quickdraw.

In next month’s column, we’ll take a break from the Toolbox and explore some of the differences between C and C++. In the meantime, I’ll be busy trying to catch up with Daniel. Oh, how those little feet can fly...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.