January 90 - REALISTIC COLOR FOR REAL-WORLD APPLICATIONS
REALISTIC COLOR FOR REAL-WORLD APPLICATIONS
BRUCE LEAK
32-Bit QuickDraw the new extension to the Macintosh graphics system
software, enables the manipulation of 16- and 32-bit color data. This article
gives details on the new offscreen pixMap support, the improved Palette
Manager, color to grayscale conversion through luminosity mapping, and
advanced dithering from 16 and 32 bits per pixel to lower bit depths.
On the Macintosh, Apple's graphics software (QD) lets a programmer work with
a high-level graphics model that is independent of the physical display device.
This gives Apple the option to take advantage of new features and technologies
without requiring application developers to rewrite their code.
32-Bit QuickDraw extends QuickDraw to encompass the full range of
displayable color. Although today's monitors are typically capable of showing a
full spectrum of color or grays, it is the video card and system software of a
computer that control the number of colors or shades of gray on the screen. A
1-bit video card allows 2 colors or shades (typically black and white), 2 bits
gives 4, 4 bits gives 16, 8 bits gives 256, and 24 bits gives over 16 million
colors.
Color QuickDraw always supported the description of nearly unlimited colors
(248) but constrained images and screens to any 256 of the expressible colors.
32-Bit QuickDraw significantly increases the standard number of colors available
for an application while maintaining speed and affordability.
32-Bit QuickDraw--which carries 24 bits of color information--consists of three
files:
- a General cdev that works more effectively with the system, whether the
other pieces are installed or not
- a Monitors cdev extended for 32-bit addressed video cards
- a 32-Bit QuickDraw Init file, which contains the new QuickDraw software
NEW FUNCTIONALITY IN 32-BIT QUICKDRAW
This is the laundry list of 32-Bit QuickDraw features. They are listed in relative
order of importance, but some may be more important to you, depending on
whether you've thought about them before.
Support for 32-bit-per-pixel graphics The pixel data has 8 bits each in red,
green, and blue and an 8-bit alpha channel. Only 24 of the 32 bits per pixel are
used by QuickDraw. 24 bits per pixel--over 16 million colors--gives you pretty
much the maximum number of colors the eye can distinguish. When the display
mode of the graphics system supports this much color, you don't have to restrict
the application or user to a particular set or palette.
Support for 16-bit-per-pixel graphics (1 alpha-5-5-5)The pixel data has 5
bits each in red, green, and blue and a 1-bit alpha channel. 16 bits per pixel--
or over 32,000 colors--is considered by many to be sufficient for high-quality
graphics. Because 16 bits per pixel requires less memory than 32 bits per pixel,displays can use less expensive hardware.
Dithering Dithering of 32- and 16-bit images to lower color resolutions --1,
2, 4, and 8 Color dithering is similar to creating a color that looks like orange by
placing red and yellow pixels close together. If the display is limited to a certain
number of colors, the Macintosh can take images rich in color information and
produce a close match at lower color resolutions, giving the appearance of more
color by combining the limited number of colors in an effective manner.
Gray-level representation with luminosity In grayscale mode, QuickDraw
will map a color to its nearest luminance value or lightness. This produces
superior images, even with 16 gray levels. It's hard to imagine how good this
can be without seeing it. so we'll show you just how great it is in these next two
pictures
An improved Palette Manager The Palette Manager now allows application
developers to have more control over their color environment by improving
multiple monitors support, supporting a highlight color as one of four colors in 2-
bit mode, setting up a true grayscale look-up table on monochrome devices,
and restoring the color environment when an application quits. The new Palette
Manager also directly supports color table animation of pixel images in a
device-independent manner (see "All About the Palette Manager" in this issue
for details).
New offscreen support These new routines can isolate developers from
device dependencies by extending offscreen pixMap support. Developers
typically use offscreen support to buffer drawing for fast, seamless updates to
the screen. Offscreen imaging is also convenient for custom rendering
algorithms that assume a particular frame buffer configuration--since requiring a
particular video display mode is not a user-friendly solution.
Improved graphics performance in all bit modes 32-Bit QuickDraw
provides performance improvements in region-clipped pattern fills and bit blits,
such as updating the desktop pattern or resizing a window.
Improved rescaling of images to smaller sizes When 32-bit-per-pixel images
are resized to smaller sizes, pixels are combined using an averaging technique
to yield recognizable thumbnail-sized images--an important improvement for
the postage stamp market.
New routine to get regions from bitmaps Getting a bitmap from a region is
easy--just paint the region. The new routine BitmapToRgn
provides the
inverse transformation.
Alpha channel movement 32-Bit QuickDraw supports routines that use up to
24 bits of color. The additional 8 bits of information are typically used by
application developers as an alpha channel or transparency mask. QuickDraw
now moves the extra 8 bits around without adding functionality. Note that alpha
channel memory may not actually be present on the video card.
The new Monitors cdev The new cdev improves the Monitors interface and
adds advanced features. Now developers can easily modify the cdev through astandard programming interface.
Support for color PostScript printing Apple's new LaserWriter 6.0 driver
now offers a standard mechanism for printing the high-quality color that 32-Bit
QuickDraw provides.
Color Picker changes Most of the changes to the Color Picker are related to
the user interface. In the former version of the Color Picker, if the where
parameter was set to (0, 0), then the dialog was centered on the main device.
For obvious reasons, this method did not work well if the main device was not a
color device. In the new Color Picker, if you want the dialog centered on the
best device--that is, the device with the highest bit depth, regardless of color
support--then you must pass (-1, -1) as the where parameter.
Compression for file formats 32-bit and 16-bit data are normally compressed
when they are in PICT files so that storage on disk takes significantly less space
than the original data.
Support for very large frame buffers Video cards that require more than 1
MB of memory, such as a 1280 x 1024 x 8-bit deep card, now work in a
standard way with the system.
Changes in rowbyte restrictions 32-Bit QuickDraw relaxes the restriction that
rowbytes be less than $2000. However, the new limit of $3FFE may still be a
problem with large pixel maps at 32 bits per pixel. Early releases of the 32-Bit
QuickDraw documentation incorrectly reported that rowbytes had a limit of
$8000.
Not to mention, as you always expected... 32-Bit QuickDraw has implications
for several familiar aspects of working with the Macintosh. PICT, the Macintosh
graphics resource and file format, has been extended to support 16-bit and 32-
bit data. The transfer modes that allow QuickDraw to blend different bitmaps
and combine their colors interactively in different ways have been extended so
that they work at, and between, all bit depths. Because images of any depth
can be displayed at any depth, you have ultimate flexibility to respond to the
requirements of the task at hand. Colors are mapped to an appropriate match
when increasing or decreasing color depth of the display.
WHAT CAN YOU DO WITH IT
To begin with, you can't use 32-Bit QuickDraw features if you don't know they're
installed. To check for 32-Bit QuickDraw, your application should ensure that
Color QuickDraw is present on the machine by calling
SysEnvirons
. Then,
since 32-Bit QuickDraw internally uses trap number
$AB03
, check to see if
this trap is available by comparing its trap address with that of the standard
unimplemented trap
$A89F
. If the two are the same, trap
$AB03
is
unavailable, and 32-Bit QuickDraw is not present.
You can use the following MPW C code fragment to test for Color QuickDraw
and 32-Bit QuickDraw. If either test fails, tell the user.
#define QD32Trap 0xAB03
#define UnImplTrap 0xA89F
#define False 0
#define True 1
PutUpInformativeMessage()
{
printf("\n 32-Bit QuickDraw is not implemented.");
}
QD32Exists()
{
short error;
Boolean result = False; /* Assume not there */
SysEnvRec theWorld;
error = SysEnvirons (2, &theWorld);
if (theWorld.hasColorQD)
result = (NGetTrapAddress (QD32Trap, ToolTrap) !=
NGetTrapAddress (UnImplTrap, ToolTrap));
return result;
}
main()
{
Boolean QD32IsImplemented;
QD32IsImplemented = QD32Exists();
if (!QD32IsImplemented)
PutUpInformativeMessage();
}
Direct pixMaps 32-Bit QuickDraw supports two new pixel formats,
corresponding to 32-bit pixels and 16-bit pixels. In each case, the pixel's color
is specified by the pixel value directly. The pixel value is not an index into a
color look-up table. In a pixMap, this is specified by setting the pixelType field
to RGBDirect = 16.
Before 32-Bit QuickDraw, when each pixel was a single value representing an
index into a color table, the cmpCount field was always equal to 1. With
RGBDirect pixels, each pixel contains three components, one each for the
intensities of red, green, and blue therefore, cmpCount should be set to 3.
pixelType = 16; {RGBDirect}
pixelSize = 32; {Must be a power of 2}
cmpCount = 3; {Three components: Red, Green, Blue}
cmpSize = 8; {8 bits for each component}
pmVersion = 0; {Must be set for future compatibility}
pmTable {Handle to color table with 1 entry}
ctSeed = 24; {CmpCount * CmpSize}
ctFlags = 0; {No special flags}
ctSize = 0; {Zero based count of entries}
ctTable = {Space for one color spec}
pixelType = 16; {RGBDirect}
pixelSize = 16; {Must be a power of 2}
cmpCount = 3; {Red, Green, Blue
cmpSize = 5; {5 bits for each component}
pmVersion = 0; {Must be set for future compatibility}
pmTable {Handle to color table with 1 entry}
ctSeed = 15; {CmpCount * CmpSize}
ctFlags = 0; {No special flags}
ctSize = 0; {Zero based count of entries}
Since the Window Manager, as well as many applications, examines the ctSeed
of screen pixMaps, the pmTable field for a direct device pixel map should
always contain a valid handle with a color table header. For consistency, the
ctSeed should be equal to cmpCount * cmpSize--although you can have the
seed equal a unique value. If the seed value is the same across devices, then
window moves will copy an image with CopyBits otherwise, the Window
Manager will generate an update event. The ctFlags and ctSize values should
be set to zero.
PixPats In addition to the standard 8 x 8 foreground/background QuickDraw
pattern filling we have all come to know and love, Color QuickDraw supports
drawing objects with tiled pixel images or pixPats (short for pixel patterns).
Although pixPats actually contain a pixMap that is capable of describing a pixel
image of any size and depth, only bit depths 1 through 8 and dimensions that
are a power of two are supported. Since pixPats contain color information, the
grafPort's foreground and background colors are ignored when drawing with
pixel patterns. Future versions of Color QuickDraw will support 16- and 32-bit
pixel patterns.
Color QuickDraw expands a pixPat to the depth of the target device before
drawing. Make sure that enough memory is available for the expanded pattern.
The current 32-Bit QuickDraw limits the volume (area times depth) of an
expanded pixPat to less than 64K. Hence a 128 x 128 pixPat (16K @ 8 bits
deep) will work at 8 bits per pixel but draw incorrectly when rendered at 32 bits
per pixel. A 64 x 128 pixPat (32K @ 32 bits deep) will work at any depth.
Another type of pixPat, the RGB pattern, is completely described by a single
RGB Color. When drawing an object with an RGB pattern, Color QuickDraw
computes an ordered dither matrix that most accurately represents the RGB
Color on each screen it intersects. Since dithering is not performed on 32-bit-
per-pixel devices, there is never any penalty for using makeRGBPat to
approximate a desired color.
Drawing in color When an application requests the drawing of one of the 248
expressible colors, Color QuickDraw finds the closest or best color available on
TheGDevice. In general, this is done by the Color Manager routine
Color2Index(), more appropriately called Color2Pixel. On indexed display
devices, Color2Index() uses the device's inverse table to find the best match.
For direct devices, Color2Index() truncates each color component to the
cmpSize of the device. When the destination device's color table only contains
shades of gray, Color2Index() matches the luminance of the requested color to
the closest gray on the device. Luminance mapping gives superior-looking
images on grayscale displays.
While most of Color QuickDraw will find the best color regardless of inverse
table resolution, CopyBits from a direct pixMap to an indexed device cannot
distinguish between two colors that do not differ in the high itabRes bits of any
component. Fortunately, the default itabRes is four and the standard 8-bit color
table does not contain any colors that are not differentiated by the high four bits
of each component. Future versions of 32-Bit QuickDraw may be able to find
these "hidden colors" (for more information on hidden colors, see Inside
Macintosh, volume V, page 138).
32-bit addressing In 24-bit addressing mode, there are 16 MB of address
space, 6 of which are reserved for NuBus slots at only 1 MB per slot. Since
most 16- and 32-bit-per-pixel video cards, as well as some very large 8-bit ones,
require more than the 1 MB of address space per slot, the CPU must access
these cards in 32-bit addressing mode. 32-Bit QuickDraw performs all drawing
operations in 32-bit addressing mode. The base address of a screen is
assumed to be a valid 32-bit address, while all other pixMap base addresses
are treated as 24-bit addresses. Currently, 32-Bit QuickDraw cannot determine
whether a nonscreen base address is a valid 32-bit address. When setting up a
pixMap, make sure to initialize the pmVersion field to zero and use
StripAddress on dereferenced handles installed as bitmap or pixMap base
addresses.
OFFSCREEN GRAPHICS ENVIRONMENTS
With Color QuickDraw, pixel images are transferred using data from
TheGDevice to determine the destination color information. Consequently,
whenever copying to an offscreen pixel map with characteristics differing from
TheGDevice--usually the main screen--it is necessary to create an appropriate
offscreen GDevice and set it as the current GDevice before the copy. If an
offscreen pixel map is only copied from, then no offscreen GDevice is needed,
since Color QuickDraw obtains the source color information from the source
pixel map.
When creating an offscreen GDevice, setting up the gdPMap properly is not
enough. GDevices associated with direct pixel maps must have a gdType of
directType (=2). Attaching direct pixMaps to indexed devices often yields
rather blue results.
As many developers have learned, offscreen drawing environments can be
used to do wonderful things. For instance, you can do window content buffering
for snappy flicker-free updates, or, of more interest to programmers, you can
isolate the application from the current video display mode. The fastest
CopyBits transfers occur when the source and destination pixMaps have the
same depth, color table, and long word alignment. 32-Bit QuickDraw simplifies
the programmer's model with a set of routines for creating and manipulating
graphics environments or GWorlds. To ensure future compatibility and
developer sanity, use of the new routines is highly recommended.
Using the new routines, text can be antialiased with a clever use of offscreen
drawing environments. When shrinking 32-bit-per-pixel images, 32-Bit
QuickDraw uses an averaging technique that can yield antialiased text. You
can do this by first copying the background image where the text is to be placed
to an offscreen 32-bit deep buffer that is 2 or 4 times bigger than ultimately
desired. Next, image the text at the same enlargement into the offscreen buffer.
Finally, copy the entire offscreen back to the desired destination, shrinking down
by the scale factor. A scale factor of 2 will provide 4 levels of blend between
the text and the background, and a scale factor of 4 will provide 16 levels of
blend. These illustrations show two ways of drawing text the usual way draws text on
top of a given background at the final size. Now 32-Bit QuickDraw allows for
anti-aliasing text to be obtained by first drawing both the background and the
text magnified (4x magnification in the example) and then using CopyBits to
display the result at the desired size. The illustration above shows the contents
of the framed rectangle magnified four times to show the difference in the
resulting text
The following sample code in THINK C creates a 32-bit-per-pixel offscreen
graphics environment, draws an exciting bull's eye image into it, and displays it
on the screen using dithering.
/*************************************************************
*
* Better Bull's eye
* Code fragments for creating and drawing to a 32-bit-per-pixel
* offscreen graphics world.
* Written in THINK C.
* DVB 8-8-89
*
*************************************************************/
static Rect dOffBounds = {0,0,256,256};
static GWorldPtr gMyOffG;
MakeMyOffscreen()
/*
* Create a 32-bit offscreen GWorld with a gray ramp
* and some stylish concentric circles.
*/
{
GDHandle oldGD;
GWorldPtr oldGW;
HSVColor hsvc;
RGBColor rgbc;
long x;
Rect r;
/* Save the current graphics state */
GetGWorld(&oldGW,&oldGD);
if NewGWorld(&gMyOffG,32,&dOffBounds,nil,nil,0)
/* Was it successful? */
PutUpErrorMessageAndExit();
/* Just bail; Could try a smaller one */
LockPixels(gMyOffG->portPixMap);
/* Must lock 'em before drawing there */
SetGWorld(gMyOffG,nil);
/* Start drawing here */
for(x = 0; x<dOffBounds.right; x++)
/* Do a gray ramp from left to right */
{
rgbc.red = rgbc.green = rgbc.blue =
x * 65535 / (dOffBounds.right - 1);
RGBForeColor(&rgbc);
MoveTo(x,0);
LineTo(x,dOffBounds.bottom);
}
r = dOffBounds;
/* Copy the full bounds rectangle */
hsvc.value = 65535;
/* Value and Saturation at full: */
hsvc.saturation = 65535;
/* We'll use bright colors only */
for (x = dOffBounds.right/2; x; x--)
/* Draw a series of concentric ovals */
{
hsvc.hue = x * 131070/(dOffBounds.right - 1);
/* Step the hue as we get smaller */
HSV2RGB(&hsvc,&rgbc);
/* Get an RGB color */
RGBForeColor(&rgbc);
/* Set that as the foreground color */
FrameOval(&r);
/* Draw the oval */
InsetRect(&r,1,1);
/* Step down to the next oval */
}
SetGWorld(oldGW,oldGD);
/* Go back to old graphics state */
UnLockPixels(gMyOffG->portPixMap);
/* Let 'em float around for a while */
}
/*
* Update the current grafport (presumably a window)
* with the contents of the gMyOffG GWorld.
*/
UpdateMyWindow()
{
LockPixels(gMyOffG->portPixMap);
/* Must lock 'em before drawing to it */
/* Fit it to the window with dithering */
CopyBits(&gMyOffG->portPixMap, &thePort->portBits, &dOffBounds,
&thePort->portRect, ditherCopy, 0);
UnLockPixels(gMyOffG->portPixMap);
/* Let 'em float around for a while */
}
ADVANTAGES OF BITMAPTOREGION
BitmapToRegion lets you use most of QuickDraw's region-oriented calls on
bitmaps by converting the bitmaps into regions. Though this call was previously
available through Software Licensing, BitmapToRegion was added to the 32-Bit
QuickDraw package in the interest of seeing it more widely used. This call is
particularly good for converting bitmaps to regions when you need to clip to a
bitmap or drag its outline. One application is using a bitmap to mask a color
image and apply a transfer mode. This allows you to call the more powerful
CopyBits with a region clip instead of CopyMask with a bitmap clip. A
CopyMask operation, for example, would not be recorded into a picture and
does not support transfer modes.
An example of a call done with CopyMask would be:
CopyMask (srcPixMap, maskBitmap, destPixMap, srcRect, maskRect,
destRect)
Instead, you could use:
BitmapToRegion (maskRegion,maskBitmap)
/* Region must have been created previously with NewRgn */
CopyBits (srcPixMap, destPixMap,srcRect,destRect,mode,maskRegion)
Another use for BitmapToRegion would be in creating a patterned paint bucket
fill for a bitmap.
BitmapToRegion (maskRegion,myBitmap);
PenPat (myPattern); /* or PenPixPat (mypixPat) */
PaintRegion(maskRegion);
Alternatively, to change the color of a bitmap, you could use:
BitmapToRegion (maskRegion,myBitmap);
RGBForeColor (mycolor);
PaintRegion(maskRegion);
You could drag the outline of a bitmap around by calling:
BitmapToRegion (maskRegion,mybitmap);
DragGrayRegion (maskRegion, startPt, etc...);
Finally, you could test a mouse point, or whatever, for intersection with a bitmap
with:
BitmapToRegion (maskRegion,mybitmap);
PtInRgn (pt,maskRegion);
THE 72 DPI PIXMAP BARRIER
Actually, there never was a 72 dpi pixMap barrier. Rather, the proper usage of
pixMap resolution has not been well described. In the past, applications have
accepted pixMaps of a given number of rows and columns and assumed that
they were generated on 72 dpi devices. These pixMaps were then copied
around at a 72 dpi resolution and printed out at a 72 dpi resolution, leaving the
impression that QuickDraw could not handle pixMaps of different densities. The
advent of frame grabbers and scanners renders this method of pixMap handling
obsolete. Now, many pixMaps have a higher resolution than 72 dpi. In fact, a
user expects such a pixMap to display an approximation of the information on a
72 dpi display, but print on a higher-resolution device to the best of its ability.
When recording pictures that contain pixMaps, make sure to set the hRes and
vRes fields of the pixMap record to the native resolution of the image. When
importing pictures, obtain pixMap information from the StdBits bottleneck
procedure, not by imaging the picture into its picFrame.
CUSTOM COLOR SEARCH PROCEDURES
The following 32-Bit QuickDraw lore describes the May '89 release and is
subject to change in future 32-Bit QuickDraw versions.
When pixel images are transferred to a different depth, the destination color
information is obtained from TheGDevice. Custom Color Search Procedures,
or Search Procs for short, associated with a GDevice provide a mechanism for
customizing QuickDraw's color matching algorithms. When the source image is
32 or 16 bits per pixel, 32-Bit QuickDraw calls the Search Proc associated with
the destination GDevice for each source pixel. Since 32-Bit QuickDraw always
accesses direct pixel maps in 32-bit addressing mode, and since direct pixMap
image translation is performed at draw time, don't be surprised if your custom
Color Search Procedure gets called in 32-bit addressing mode. Color Search
Procedures should call StripAddress on dereferenced handles and
SwapMMUMode if toolbox access such as Color2Index is required (for more
information on 32-bit addressing and SwapMMUMode, see Inside Macintosh,
volume V, page 592).
Also, for direct pixel source images, the application's global pointer in register
A5 may not be valid on entry to custom Color Search Procedures. If your
Color Search Procedure accesses global data structures referenced from
register A5 (including thePort), it must first save and later restore the A5
contents (see Technical Notes #180 and #208).
In the current version of 32-Bit QuickDraw, custom Color Search Procedures
are ignored when transferring 32-bit or 16-bit images to a device of identical
depth--this is subject to change in future releases. Since dithering techniques
need to accurately maintain colorspace distance, 32-Bit QuickDraw refuses to
dither direct pixMaps when a custom Search Procedure is present. A printer-
driver developer should not rely on this functionality. To prevent a picture from
dithering, intercept the StdBits bottleneck routine, and remap the transfer mode
to srcCopy.
CopyBits error codes QuickDraw uses stack space for work buffers. For
complex operations such as depth conversion, dithering, or image resizing,
stack space may not be enough. In such situations, Color QuickDraw simply
skips the operation. In this case, 32-Bit QuickDraw will request temporary
memory from MultiFinder. If that is still not enough, or if MultiFinder is not
present, 32-Bit QuickDraw returns
QDErr = -149 /* Insufficient stack */
This value can be obtained by calling QDError(), which will reset QDErr to zero.
One recourse for the application is to divide the operation--for example, divide
the image into left and right halves--and try again.
Region creation error codes While recording drawing operations into an
open region, it is possible that the resulting region description will overflow the
current 64K limit. Should this happen, 32-Bit QuickDraw will return
#define rgnOverflowErr -147 /* Region overflow */
Since the resulting region is potentially corrupt, closeRgn will return an empty
region if it detects QDErr has been set to -147.
32-Bit QuickDraw's offscreen bitmaps, luminosity mapping, and advanced
dithering automatically do work that would have required sophisticated and
lengthy code from a developer. The new Palette Manager unloads much of the
color management burden from your application. When all this is combined with
the ability to display such broad ranges of color, we can see that 32-Bit
QuickDraw represents a tremendous programming effort.
Bruce Leak, our local pixel dealer, is one of our famous convertible-driving,
shorts-wearing maniacal-laughing system software engineers. He has a MSEE
from Stanford University and trained for this job at Sandcastles and Microsoft.
Now he spends his nights and weekends changing how you see the world on
your Macintosh (32-bit QuickDraw is his
specialty), and his days on the soccer field. If you have any questions (about
anything) feel free to call him at home. He's at (408) 767-1739. *
At the time of this writing, 32-Bit QuickDraw was installable as a set of files that
could be dragged into the latest system folder. 32-Bit QuickDraw will be
integrated into Apple's System 7.0. *
32-Bit QuickDraw takes an additional 100K of RAM, so we recommend you use
it with at least two MB of memory. 32-Bit QuickDraw also requires Color
QuickDraw, which is present on the SE/30 or Macintosh II family computers. *