Vous êtes sur la page 1sur 489

This is a volume in

The Gr aphi cs Gems Ser i es The Gr aphi cs Gems Ser i es The Gr aphi cs Gems Ser i es The Gr aphi cs Gems Ser i es The Gr aphi cs Gems Ser i es
A Collect ion of Pract ical Techniques
f or t he Comput er Graphics Programmer
Series Edit or
Andrew S. Glassner
Xerox Palo Alt o Research Cent er
Palo Alt o, Calif omia
G G
G GGRAPHICS RAPHICS
RAPHICS RAPHICS RAPHICS
G G
G GGEMS EMS
EMS EMS EMS
II II
II II II
edit ed by
JAMES ARVO
Pr ogr am of Comput er Gr aphi cs Pr ogr am of Comput er Gr aphi cs Pr ogr am of Comput er Gr aphi cs Pr ogr am of Comput er Gr aphi cs Pr ogr am of Comput er Gr aphi cs
Cor nel l Uni ver si t y Cor nel l Uni ver si t y Cor nel l Uni ver si t y Cor nel l Uni ver si t y Cor nel l Uni ver si t y
It haca, New Yor k It haca, New Yor k It haca, New Yor k It haca, New Yor k It haca, New Yor k
AP PROFESSIONAL
Bost on San Diego NewYor k
London Sydney Tokyo Tor ont o
Copyright (c) 1995 by Academic Press, Inc.
GRAPHICS GEMS copyright (c) 1990 by Academic Press, Inc.
GRAPHICS GEMS II copyright (c) 1991 by Academic Press, Inc.
GRAPHICS GEMS III copyright (c) 1992 by Academic Press, Inc.
QUICK REFERENCE TO COMPUTER GRAPHICS TERMS
copyright (c) 1993 by Academic Press, Inc.
RADIOSITY AND REALISTIC IMAGE SYNTHESIS
copyright (c) 1993 by Academic Press Inc.
VIRTUAL REALITY APPLICATIONS AND EXPLORATIONS
copyright (c) 1993 by Academic Press Inc.
All rights reserved.
No part of this product may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including input into or storage in any information
system, other than for uses specified in the License Agreement, without permission
in writing from the publisher.
Except where credited to another source, the C and C++ Code may be used freely to
modify or create programs that are for personal use or commercial distribution.
Produced in the United States of America
ISBN 0-12-059756-X
v
About t he Cover About t he Cover About t he Cover About t he Cover About t he Cover
The cover image is t he second in t he Gems t heme t hat I began last year. And r ew
Glassner and I bou nced some id eas back and for t h, and t he d esign solid ied pret t y
qu ickly. The gems t hemselves are t he same as in last year s image.The pict u re was
gener at ed at Pacic Dat a Images u sing t heir in-hou se soft ware. All of t he t ext u res and
mod els are proced u r ally gener at ed . The sand t ext u re, t he sand su r face shape, t he
wood gr ain, t he sea foam, and t he st ar sh t ext u re are all d er ived from fr act al noise
pat t er ns. I spent most of my t ime on t he wat er, making it look all shiny and wet and
t r ansparent , bu t not t oo t r ansparent . The foam on t he wat er s su r face was also ver y t ime-
consu ming. Anot her challenge was t o get t he gems t o all pile on t op of each ot her
convincingly. I wrot e a pr ogr am t hat d ropped t hem, one at a t ime, and as t hey fell, t hey
were r ot at ed t o t he angle t hat moved t hem t he fu r t hest d own wit hou t int er sect ing
anyt hing t hat was t here alread y. This progr am t ook a cou ple of hou r s t o ru n, bu t it was
mu ch fast er t han t r ying t o place t hem by hand . The pict u re was rend ered wit h a r ay-
t r acing progr am and t ook 50 hou r s on an Silicon Gr aphics 4D25 compu t er at a resolu t ion
of 2250 3000 pixels wit h fou r samples per pixel.
Thad d eu s Beier
Silicon Graphics Comput er Syst ems
When And r ew asked if I want ed t o d o t he cover for Graphics Gems II, I said Su r e . .
. we can reu se t he soft ware we bu ilt last year for Graphics Gems. While it wasnt qu it e
t hat simple, it was mu ch easier t o prod u ce t his cover t han t he r st one. As before, t he
image was d esigned on a color monit or prod u cing red , green and blu e pixels. For
pr int ing, we need ed t o conver t t hese pixels t o cyan, magent a, yellow, and black pixels
(pr int er color space). Once in t his for m, t he image was processed commercially t o
prod u ce half-t oned lm su it able for pr int ing. This nal st ep was per for med at Ked ie-
Orent , Su nnyvale, Califor nia, on t heir Croseld d igit al prepress syst em.
As was t he case wit h t he r st Gems pict u re, many of t he or iginal image color s cou ld
not be exact ly repr od u ced in pr int for m. The color s had t o be mod ied t o map int o t he
set of color s t hat can be prod u ced by t he pr int er, it s gamu t . The t r ick is t o d o t he
mod icat ion while maint aining t he appear ance of t he image. In t his pict u re, t he color s
in t he sand , shells, and wat er were most ly insid e t he pr int er gamu t . However, some of
t he gem color s, par t icu lar ly t he br ight blu e-greens, were far ou t sid e t he gamu t . The
t r ansfor mat ion we applied was similar t o t he one we d esigned for Graphics Gems; color s
ou t sid e of t he gamu t were d esat u r at ed t o color s of t he same light ness while maint aining
t he same hu e. If one color of a par t icu lar hu e need ed t o be d esat u r at ed , all color s of
t he same hu e wou ld be d esat u r at ed t o preser ve shad ing d et ail. However, color s ou t sid e
of t he gamu t move more t han color s insid e of t he gamu t t o maint ain t he over all
sat u r at ion.
The color s of t he Graphics Gems II cover are light er and mor e d elicat e t han t he cover
of Graphics Gems, and mu ch more of t he image lies in t he int er ior of t he pr int er gamu t .
We t u ned t he t r ansfor mat ion for t his image t o minimize t he change t o t he less sat u r at ed
color s, preser ving t he su bt le shad ing in t he sand and wat er.
Thanks t o Bill Wallace, who wrot e t he or iginal gamu t mapping soft ware for Graphics
Gems, and t o Ken Fishkin, who helped wit h t he prod u ct ion of t he cover t his year.
Mau reen St one
Xerox Palo Alt o Research Cent er

vi
vii
C CC CCONTENTS ONTENTS ONTENTS ONTENTS ONTENTS
The symbol C denotes gems that have accompanying C implementations on disk.
Foreword
By Andrew Glassner xvii
Preface xix
Mat hemat ical Not at ion xxi
Pseudo-Code xxiii
Cont ribut ors xxix
I II II
2 22 22 D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS
Int rod uct ion 3
1. The Area of a Simple Polygon 5
Jon Rokne
2. Int er sect ion of Line Segment s
C
7
Mukesh Prasad
3. Dist ance from a Point t o a Line 10
Jack C. Morrison
4. An Easy Bound ing Circle 14
Jon Rokne
viii
5. The Smallest Circle Cont aining t he Int er sect ion
C
of Two Circles 17
Jon Rokne
6. Appoloniuss 10t h Problem 19
Jon Rokne
7. A Peano Cur ve Gener at ion Algor it hm
C
25
Ken Musgrave
8. Space-Filling Cur ves and a Measure of Coherence
C
26
Douglas Voorhies
9. Scanline Coherent Shape Algebr a 31
Jonat han E. St einhart
II II II II II
I II IIMAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSING
Int rod uct ion 49
1. Image Smoot hing and Shar pening by Discret e
Convolut ion 50
Dale A. Schumacher
2. A Compar ison of Digit al Halft oning Techniques
C
75
Dale A. Schumacher
3. Color Dit her ing
C
72
Spencer W. Thomas and Rod G. Bogart
4. Fast Anamor phic Image Scaling 78
Dale A. Schumacher
5. Real Pixels 80
Greg Ward
6. A Fast 90-Degree Bit map Rot at or
C
84
Sue-Ken Yap
CONTENTS
i x
CONTENTS
7. Rot at ion of Run-Lengt h Encod ed Image Dat a
C
86
Jeff Holt
8. Ad apt ive Run-Lengt h Encod ing 89
Andrew S. Glassner
9. Image File Compression Mad e Easy 93
Alan W. Paet h
10. An Opt imal Filt er for Image Reconst ruct ion 101
Nelson Max
11. Noise Threshold ing in Ed ge Images 105
John Schlag
12. Comput ing t he Area, t he Circumference, and t he Genus
of a Binar y Digit al Image
C
107
Hanspet er Bieri and Andreas Kohler
III III III III III
F FF FFRAM RAM RAM RAM RAME E E E E BUFFER TECH BUFFER TECH BUFFER TECH BUFFER TECH BUFFER TECHN NN NNIQUES IQUES IQUES IQUES IQUES
Int rod uct ion 115
1. Efficient Inver se Color Map Comput at ion
C
116
Spencer W. Thomas
2. Efcient St at ist ical Comput at ions for Opt imal Color
Quant izat ion 126
Xiaolin Wu
3. A Rand om Color Map Animat ion Algor it hm
C
134
Ken Musgrave
4. A Fast Approach t o PHIGS PLUS Pseud o Color 138
Mapping
James Hall and Terence Lindgren
5. Mapping RGB Tr iples ont o 16 Dist inct Values 143
x
6. Television Color Encoding and Hot Broadcast
Colors
C
147
David Mart indale and Alan W. Paet h
7. An Inexpensive Met hod of Set t ing t he Monit or
Whit e Point 159
Gary W. Meyer
8. Some Tips for Making Color Hard copy 163
Ken Musgrave
IV IV IV IV IV
3 33 33 D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS D GEOMETRY AND ALGORITHMS
Int rod uct ion 169
1. Area of Planar Polygons and Volume of Polyhed r a 170
Ronald N. Goldman
2. Get t ing Around on a Sphere 172
Clifford A. Shaffer
3. Exact Dihed r al Met r ics for Common Polyhed r a 174
Alan W. Paet h
4. A Simple Viewing Geomet r y 179
Andrew S. Glassner
5. View Cor r elat ion
C
181
Rod G. Bogart
6. Maint aining Winged -Ed ge Mod els 191
Andrew S. Glassner
7. Quad t ree/ Oct r ee-t o-Bound ar y Conver sion 202
Claudio Mont ani and Robert o Scopigno
8. Three-Dimensional Homogeneous Clipping
of Tr iangle St r ips
C
219
Pat rick-Gilles Maillot
CONTENTS
xi
9. Int er Phong Shad ing
C
232
Nadia Magnenat Thalmann, Daniel Thalmann,
and Hong Tong Minh
V VV VV
R RR RRAY TRACING AY TRACING AY TRACING AY TRACING AY TRACING
Int rod uct ion 245
1. Fast RayConvex Polyhed ron Int er sect ion
C
247
Eric Haines
2. Int er sect ing a Ray wit h an Ellipt ical Torus
C
251
Joseph M. Cychosz
3. RayTr iangle Int er sect ion Using Binar y Recur sive
Subd ivision 257
Douglas Voorhies and David Kirk
4. Improved Ray Tagging for Voxel-Based Ray Tr acing 264
David Kirk and James Arvo
5. Efciency Improvement s for Hier archy Tr aver sal
in Ray Tr acing 267
Eric Haines
6. A Recur sive Shad ow Voxel Cache for Ray
Tr acing
C
273
Andrew Pearce
7. Avoid ing Incor rect Shad ow Int er sect ions for Ray
Tr acing 275
Andrew Pearce
8. A Bod y Color Mod el: Absor pt ion of Light t hrough
Tr anslucent Med ia 277
Mark E. Lee and Samuel P. Uselt on
9. More Shad ow At t enuat ion for Ray Tr acing Tr ansparent
or Tr anslucent Object s 283
Mark E. Lee and Samuel P. Uselt on
CONTENTS
xii
CONTENTS
Vl Vl Vl Vl Vl
R RR RRADIOSITY ADIOSITY ADIOSITY ADIOSITY ADIOSITY
Int rod uct ion 293
1. Implement ing Progressive Rad iosit y wit h User-
Provid ed Polygon Display Rout ines
C
295
Shenchang Eric Chen
2. A Cubic Tet r ahed r al Ad apt at ion of t he Hemi-Cube
Algor it hm 299
Jeffrey C. Beran-Koehn and Mark J. Pavicic
3. Fast Ver t ex Rad iosit y Upd at e
C
303
Filippo Tampieri
4. Rad iosit y via Ray Tr acing 306
Pet er Shirley
5. Det ect ion of Shad ow Bound ar ies for Ad apt ive Meshing
in Rad iosit y 311
Franois Sillion
Vl l Vl l Vl l Vl l Vl l
M MM MMATRIX TECHNIQUES ATRIX TECHNIQUES ATRIX TECHNIQUES ATRIX TECHNIQUES ATRIX TECHNIQUES
Int rod uct ion 319
1. Decomposing a Mat r ix int o Simple
Tr ansfor mat ions
C
320
Spencer W. Thomas
2. Recover ing t he Dat a from t he Tr ansfor mat ion Mat r ix 324
Ronald N. Goldman
3. Tr ansfor mat ions as Exponent ials 332
Ronald N. Goldman
4. More Mat r ices and Tr ansfor mat ions: Shear and
Pseud o-Per spect ive 338
Ronald N. Goldman
xiii
5. Fast Mat r ix Inver sion
C
342
Kevin Wu
6. Quat er nions and 4 4 Mat r ices 351
Ken Shoemake
7. Rand om Rot at ion Mat r ices
C
355
James Arvo
8. Classifying Small Spar se Mat r ices
C
357
James Arvo
Vl l l Vl l l Vl l l Vl l l Vl l l
N NN NNUMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING
T TT TTECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES
Int rod uct ion 365
1. Bit Picking 366
Ken Shoemake
2. Fast er Four ier Tr ansfor m 368
Ken Shoemake
3. Of Int eger s, Field s, and Bit Count ing
C
371
Alan W. Paet h and David Schilling
4. Using Geomet r ic Const ruct ions t o Int er polat e
Or ient at ion wit h Quat er nions 377
John Schlag
5. A Half-Angle Id ent it y for Digit al Comput at ion: 381
The Joys of t he Halved Tangent
Alan W. Paet h
6. An Int eger Square Root Algor it hm
C
387
Christ opher J. Musial
7. Fast Approximat ion t o t he Arct angent 389
Ron Capelli
CONTENTS
xiv
CONTENTS
8. Fast Sign of Cross Prod uct Calculat ion
C
392
Jack Rit t er
9. Int er val Sampling 394
Ken Shoemake
10. A Recur sive Implement ation of t he Perlin Noise Funct ion
C
396
Greg Ward
I II IIX XX XX
C CC CCURVES AN URVES AN URVES AN URVES AN URVES AND D D D D SURFACES SURFACES SURFACES SURFACES SURFACES
Int rod uct ion 405
1. Least -Squares Approximat ions t o Bzier Cur ves
and Sur faces 406
Doug Moore and Joe Warren
2. Beyond Bzier Cur ves 412
Ken Shoemake
3. A Simple For mulat ion for Cur ve Int er polat ion
wit h Var iable Cont rol Point Approximat ion 417
John Schlag
4. Symmet r ic Evaluat ion of Polynomials 420
Terence Lindgren
5. Menelauss Theorem 424
Hans-Pet er Seidel
6. Geomet r ically Cont inuous Cubic Bzier Cur ves 428
Hans-Pet er Siedel
7. A Good St r aight -Line Approximat ion of a Circular
Arc
C
435
Christ opher J. Musial
8. Great Circle Plot t ing 440
Alan W. Paet h
9. Fast Ant i-Aliased Circle Gener at ion 446
Xiaolin Wu
PSEUDO-CODE
.
PSEUDO-CODE
.
xvii GRAPHICS GEMS II Edit ed by JAMES ARVO xvii
FOREWORD
F FF FFOREWORD OREWORD OREWORD OREWORD OREWORD
by Andrew Glassner
Welcome to Graphics Gems II, a new collection of practical techniques
and methods for the computer graphics programmer. This book is a
collection of contributions from many people, most of whom work inde-
pendently of each other. Yet through these volumes we are able to share
our observations and insights with each other and our readers, and
together build a communal library of graphics programming techniques.
In the preface to the original Graphics Gems, I wrote that This
book . . . concludes one turn of a cycle of discovery, documentation,
editing, publishing, and reading, which will in turn lead to new discover-
ies. I am delighted that we have completed another loop around the
cycle, and emerged with another strong collection of programming tech-
niques. As with its predecessor, the articles in this book are primarily not
research results; those can be found in the formal professional literature.
Rather, the Graphics Gems books are a conduit for practical informa-
tion. Much of the detailed information in these volumes would be inap-
propriate for a technical paper, but is invaluable to the implementor.
This volume has been edited by Jim Arvo, who is well known in the
graphics community as a skilled researcher and teacher. Jim and I have
taught several courses together at SIGGRAPH conferences and other
venues, and I have always been impressed with his insight and eager ness
to share his knowledge. The ne selection and organization of material in
this volume demonstrates his abilities well.
There may be more volumes in the Graphics Gems series. We will
continue to solicit and collect contributions, and organize them into new
books, as long as t he qualit y remains high and t he result s useful. Each
xviii GRAPHICS GEMS II Edit ed by JAMES ARVO xviii
FOREWORD
volume will be edited by a different individual, since I believe this will
help keep the results lively and fresh, and reect the diversity that is part
of what makes computer graphics such an exciting eld to work in.
One quality that I believe is shared by most engineers and scientists
is a desire for elegance. An elegant solution is one that is simple and direct,
and often provokes an Aha! reaction when rst encountered. Often
such clean techniques depend on an insight derived from knowledge or
experience from another context. Many of the techniques in this book t
this criterion for elegance, and enlarge the repertoire of tools upon which
we draw for solutions to new, unexpected challenges. Each time we learn
how another person solved an important problem, we grow as designers
and implement or s.
It is in celebr at ion of t he t win spir it s of growt h and shar ing t hat we
br ing you t his book. I hope you nd it infor mat ive and useful.
xix GRAPHICS GEMS II Edit ed by JAMES ARVO xix
PREFACE
P PP PPREFACE REFACE REFACE REFACE REFACE
Cont inuing in t he spirit of t he inaugural Graphics Gems volume,
Graphics Gems II represents the collective expertise of a large and
diverse group of people. The common thread shared by all the contribu-
tors is that each has devised or rened useful ideas which can benet
other computer graphics practitioners, and they have graciously agreed to
disseminate them. The resulting amalgam has a character quite distinct
from any text book on the subject, as it reects ideas and approaches
every bit as diverse and unique as the people behind them.
In the eld of computer graphics, as with almost any endeavor, there is
rarely a best way to do anything. Therefore, this volume shares a recur-
ring theme with the original volume by presenting techniques for doing
well-known operations faster or easier. Some present a new way of
looking at an old problem while others provide useful mathematical
machinery with broad application.
There are several ways to use this book. First, it can be a source of
solutions to specic problems. If one of the gems in this collection
addresses a particular problem of interest to you, the idea can be
employed with little ado. This is facilitated by the program listings
provided with many of the gems. A second way to use this book is to
simply browse, learning clever solutions to problems you may not have
encountered or even considered yet. Often the ideas behind the gems can
be applied in contexts much broader than those shown, or they may serve
as the seeds to get you thinking along new lines. In any event, there is
much to be gained by looking over the shoulders of experienced graphics
programmers as they apply the subtle tricks of the trade.
The overall structure, mathematical notation and pseudo-code used
here are t he same as in t he r st volume. The scope and names of some
xx GRAPHICS GEMS II Edit ed by JAMES ARVO xx
PREFACE
parts have been changed slightly to best accommodate this new collection
of gems. In order to make this book as self-contained as possible we have
included several of the important sections verbatim from the rst volume
for easy reference; there are the sections entitled Mathematical Nota-
tion, Pseudo-Code, and the listings Graphics Gems C Header File
and 2D and 3D Vector Library in Appendix I. The last of these contains
several corrections and extensions. Only the part titled Radiosity has
no counterpart in the rst volume. This new part has been added to
complement the part on ray tracing and to reect current research trends.
The gems comprising each part all relate to some common theme.
Gems that share something more fundamental are linked via the See
also section at the end of each gem. Gems identied by gem number are
contained in this volume; gems identied by page number are in the rst
volume of Graphics Gems. The mathematical background which is as-
sumed in most of the gems is limited to elementary calculus and linear
algebra, the staples of computer graphics.
The C programming language has been used for all the program listings
in the appendix because it is widely used and is among the most portable
of languages. It is also a favorite among graphics programmers because
of its exibility. These considerations made it the obvious choice. All the
C code in this book is in the public domain, and is yours to study, modify,
and use. As of this writing, all code listings are available via anonymous
ftp transfer from the machine weedeater.math.yale.edu (internet ad-
dress 130.132.23.17). When you connect to this machine using ftp, log in
as anonymous, and give your own last name as the password. Then use
the cd command to move to the directory pub/ GraphicsGems.
Download and read the le called README to learn about where the code
is kept, and how to report bugs.
Thanks are due to the many people who made this book possible. First
and foremost Id like to thank all the gem contributors, whose expertise
and insight is what this book is all about. Also, Id like to thank Andrew
Glassner for pioneering this whole adventure and for assisting in every
aspect along t he way. Special t hanks t o Ter r y Lind gren for his
t remend ously helpful input where it was most need ed , and t o Greg
Ward, John Francis, Paul Heckbert, and Eric Haines for their reviews,
expert opinions, and helpful suggestions. Finally, Id like to thank Craig
Kolb for providing a safe haven for t he public domain C code.
xxi GRAPHICS GEMS II Edit ed by JAMES ARVO xxi
MATHEMATICAL NOTATION
M MM MMATHEMATICAL ATHEMATICAL ATHEMATICAL ATHEMATICAL ATHEMATICAL
N NN NNOTATION OTATION OTATION OTATION OTATION
Geomet r i c Obj ect s Geomet r i c Obj ect s Geomet r i c Obj ect s Geomet r i c Obj ect s Geomet r i c Obj ect s
0 t he number 0, t he zero vect or, t he point (0, 0), t he
point (0, 0, 0)
a, b, c t he real number s (lower case it alics)
P, Q point s (upper-case it alics)
l , m lines (lower-case bold )
A, B vect or s (upper-case bold )(component s A
i
)
M mat r ix (upper-case bold )
, angles (lower-case greek)
Der i ved Obj ect s Der i ved Obj ect s Der i ved Obj ect s Der i ved Obj ect s Der i ved Obj ect s
A

the vector perpendicular to A (valid only in 2D, where


A

= (A
y
, A
x
)
M
-1
t he inver se of mat r ix M
M
T
t he t r anspose of mat r ix M
M
*
t he ad joint of mat r ix M

M
1

det M ( )
|
.

`
,

| M| d et er minant of M
d et (M) same as above
M
i,j
element from row i, column j of matrix M (top-left is
(0, 0)
M
i,
all of row i of mat r ix M
xxii GRAPHICS GEMS II Edit ed by JAMES ARVO xxii
MATHEMATICAL NOTATION
M
,j
all of column j of Mat r ix

ABC t r iangle for med by point s A, B, C


ABC angle for med by point s A, B, C wit h ver t ex at B
Basi c Oper at or s Basi c Oper at or s Basi c Oper at or s Basi c Oper at or s Basi c Oper at or s

+, , / ,
st and ard mat h oper at or s

t he d ot (or inner or scalar ) prod uct

t he cross (or out er or vect or ) prod uct


Basi c Expr essi ons and Funct i ons Basi c Expr essi ons and Funct i ons Basi c Expr essi ons and Funct i ons Basi c Expr essi ons and Funct i ons Basi c Expr essi ons and Funct i ons

x
]
floor of x (largest int eger not great er t han x)

x
]
ceiling of x (smallest int eger not smaller t han x)
a| b mod ulo ar it hmet ic; remaind er of a b
a mod b same as above

B
i
n
t ( ) Ber nst ein polynomial =

n
i
|
.

`
,

t
i
1 t ( )
n i
, i 0Ln

n
i
|
.

`
,
binomial coefficient

n!
n i ( )!i!
xxiii
PSEUDO-CODE
GRAPHICS GEMS II Edit ed by JAMES ARVO xxiii
P PP PPSEUDO-CODE SEUDO-CODE SEUDO-CODE SEUDO-CODE SEUDO-CODE
Decl ar at i ons ( not r equi r ed) Decl ar at i ons ( not r equi r ed) Decl ar at i ons ( not r equi r ed) Decl ar at i ons ( not r equi r ed) Decl ar at i ons ( not r equi r ed)
name: TYPE init ialValue;
examples:

:real 3.14159;
v: array [0..3] of i nteger [0, 1, 2, 3];
Pr i mi t i ve Dat a Types Pr i mi t i ve Dat a Types Pr i mi t i ve Dat a Types Pr i mi t i ve Dat a Types Pr i mi t i ve Dat a Types
array [lower Bound ..upper Bound ] of TYPE;
bool ean
char
i nteger
real
doubl e
poi nt
vector
matri x3
equivalent t o:
mat rix3: record [array [0..2] of array [0..2] of real;];
example: m:Matrix3 [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]];
m[2][1] is 8.0
m[0][2] 3.3; assigns 3.3 t o upper-right corner of mat rix
xxiv
PSEUDO-CODE
GRAPHICS GEMS II Edit ed by JAMES ARVO xxiv
matri x4
equivalent t o:
mat rix4: record [array [0..3] of array [0..3] of real;];
example: m: Mat rix4 [
[1.0, 2.0, 3.0, 4.0],
[5.0, 6.0, 7.0, 8.0],
[9.0, 10.0, 11.0, 12.0],
[13.0, 14.0, 15.0, 16.0]];
m[3][1] is 14.0
m[0][3] 3.3; assigns 3.3 t o upper-right corner of mat rix
Recor ds ( St r uct ur es) Recor ds ( St r uct ur es) Recor ds ( St r uct ur es) Recor ds ( St r uct ur es) Recor ds ( St r uct ur es)
Record denit ion:
Box: record [
left , r ight , t op, bot t om: i nteger;
];
newBox: Box new[Box];
dynamically allocate a new instance of Box and return a pointer to it
newBox.left 10;
t his same not at ion is appropriat e whet her newBox is a point er or
st ruct ure
Ar r ays Ar r ays Ar r ays Ar r ays Ar r ays
v: array [0..3] of integer [0, 1, 2, 3]; v is a four-element array of integers
v[2] 5; assign t o t hird element of v
Comment s Comment s Comment s Comment s Comment s
A comment may appear anywhereit is indicat ed by it alics
xxv
PSEUDO-CODE
GRAPHICS GEMS II Edit ed by JAMES ARVO xxv
Bl ocks Bl ocks Bl ocks Bl ocks Bl ocks
begi n
St at ement ;
St at ement ;

L
end;
Condi t i onal s and Sel ect i ons Condi t i onal s and Sel ect i ons Condi t i onal s and Sel ect i ons Condi t i onal s and Sel ect i ons Condi t i onal s and Sel ect i ons
i f Test
then St at ement ;
[el se St at ement ]; else clause is opt ional
result = sel ect It em from
inst ance: St at ement ;
endcase: St at ement ;
Fl ow Cont r ol Fl ow Cont r ol Fl ow Cont r ol Fl ow Cont r ol Fl ow Cont r ol
for Cont rolVar iable: Type Init ialExpr, Next Expr do
St at ement ;
endl oop;
unti l Test do
St at ement ;
endl oop;
whi l e Test do
St at ement ;
endl oop;
l oop; go direct ly t o t he next endloop
exi t; go direct ly t o t he rst st at ement aft er t he next endloop
return[value] ret urn value as t he result of t his funct ion call
xxvi
PSEUDO-CODE
GRAPHICS GEMS II Edit ed by JAMES ARVO xxvi
Logi cal Connect i ves Logi cal Connect i ves Logi cal Connect i ves Logi cal Connect i ves Logi cal Connect i ves
or, and, not, xor
Bi t wi se Oper at or s Bi t wi se Oper at or s Bi t wi se Oper at or s Bi t wi se Oper at or s Bi t wi se Oper at or s
bi t-or, bi t-and, bi t-xor
Rel at i ons Rel at i ons Rel at i ons Rel at i ons Rel at i ons
=, , >, , <,
Assi gnment Symbol Assi gnment Symbol Assi gnment Symbol Assi gnment Symbol Assi gnment Symbol

(not e: t he t est for equalit y is = )


Avai l abl e Funct i ons Avai l abl e Funct i ons Avai l abl e Funct i ons Avai l abl e Funct i ons Avai l abl e Funct i ons
These funct ions are d ened on all d at a t ypes
min(a, b) ret urns minimum of a and b
max(a, b) ret urns maximum of a and b
abs(a) ret urns absolut e value of a
sin(x) sin(x)
cos(x) cos(x)
t an(x) t an(x)
arct an(y) arct an(y)
arct an2(y, x) arct an(y/x), defined for all values of x and y
arcsin(y) arcsin(y)
arccos(y) arccos(y)
r shift (x, b) shift x right b bit s
lshift (x, b) shift x left b bit s
swap(a, b) swap a and b
lerp(, l, h) linear interpolation: ((1 )*l) +(*h) = l + ((h l))
xxvii
PSEUDO-CODE
GRAPHICS GEMS II Edit ed by JAMES ARVO xxvii
clamp(v, l, h) return l if v < l, else h if v > h, else v: min(h,max(l,v))
oor (x) or

x
]
round x t owards 0 t o rst int eger
ceiling(x) or

x
]
round x away from 0 t o rst int eger
round(x) round x to nearest integer, if frac(x) = .5, round towards
0
fr ac(x) fract ional part of x
xxix
CONTRIBUTORS
GRAPHICS GEMS II Edit ed by JAMES ARVO xxix
CONTRIBUTORS CONTRIBUTORS CONTRIBUTORS CONTRIBUTORS CONTRIBUTORS
Numbers in parent heses indicat e pages on which aut hors gems begin.
James Ar vo (264, 355, 357), Cornell Universit y, Program of Comput er Graphics,
It haca, New York, 14853, arvo@wisdom.graphics.cornell.edu
Thad d eus Beier (cover ), Silicon Graphics Comput er Syst ems, 2011 Shoreline Boule-
vard, Mount ain View, California, 94043
Jeffrey C. Ber an-Koehn (299), Minard 300, Nort h Dakot a St at e Universit y, Fargo,
Nort h Dakot a, 58105, beran-ko@plains.nodak.edu
Hanspet er Bier i (107), Inst it ut fu r Informat ik und angewandt e Mat hemat ik der Uni-
versit t Bern, Langgass St rae 51, CH-3012, Bern, Swit zerland
Rod G. Bogar t (72), Chrysler Cent er, Room 229, 2121 Bonist eel Boulevard, Ann Arbor;
Michigan 48109, rgbcaen.engin.umich.edu
Ronald B. Capelli (389), IBM Corporat ion, Depart ment C13, Building 703-2, P.0. Box
950, Poughkeepsie, New York 12602
Shenchang Er ic Chen (293), Apple Comput er, Inc., MS60W, 20707 Valley Green Drive,
Cupert ino, California 95014, chense@apple.com
Joseph M. Cychosz (251), Purdue Universit y CADLAB, Pot t er Engineering Cent er, 520
Evergreen, West Lafayet t e, Indiana 47907, cychosz@ecn.purdue.edu
And rew S. Glassner (89, 179, 191), Xerox PARC, 3335 Coyot e Hill Road, Palo Alt o,
California 94304, glassner. pa@xerox. com
Ronald N. Gold man (170, 324, 332, 338), Depart ment of Comput er Science, Rice
Universit y, P.0. Box 1892, Houst on, Texas 77251
Er ic Haines (247, 267), 3D/Eye, Inc., 2359 Nort h Triphammer Road, It haca, New
York 14850, erich@eye.com
xxx
CONTRIBUTORS
GRAPHICS GEMS II Edit ed by JAMES ARVO xxx
James Hall (138), Prime/Comput er Vision, 14 Cosby Drive, Bedford, Massachuset t s,
01730
St eve Hollasch (467), 1437 West 6t h St reet , Tempe, Arizona 85281-3205
Jeff Holt (86), Int ergraph Corporat ion, 4515 Bonnell Drive, #25H, Hunt sville, Al-
abama 35894-0001, UUNET!INGR!HOLT!HOLT
David Kir k (257, 264), CALTECH Comput er Science 256-80, Pasadena, California
91125, dk@csvax.calt ech.ed
And reas Kohler (107), Inst it ut fr Informat ik und angewandt e Mat hemat ik der Uni-
versit t Bern, CH-3012 BERNE, Langgassst rasse 51, Swit zerland
Mar k E. Lee (277, 283), Amoco Product ion Company, Tulsa Research Cent er, P.0. Box
3385, Tulsa, Oklahoma 74102, zmel02@t rc.amoco.com
Ter ence Lind gren (138, 420), Prime/Comput er Vision, 14 Cosby Drive, Bedford,
Massachuset t s, 01730
Patrick-Gilles Maillot (219), Sun MicroSystems, Inc., 2550 Garcia Avenue, MTV 21-04,
Mount ain View, California 94043
David Mar t ind ale (147), Imax Syst ems Corporat ion, 2525 Speakman Drive, Sheridan
Park, Ont ario, Canada, L5K Ibl, , labrea!adobe!uunet !ut ai!imax!dave
Nelson Max (101), L-301, Lawrence Livermore Nat ional Laborat ory, P.0. Box 808,
Livermore, California 94550, max2@llnl.gov
Gar y W. Meyer (159), Depart ment of Comput er and Informat ion Science, Universit y
of Oregon, Eugene, Oregon 97403, gary@cs.uoreqon.edu
Hong Tong Minh (232), c/o Daniel Thalmann, Comput er Graphics Lab., Swiss Fed-
eral Inst it ut e of Technology, CH-1015 Lausanne, Swit zerland, t hallmann
@eldi.ep.ch
Claud io Mont ani (202), Inst it ut o di Elaborazione delInformazione, Consiglio Nazionale
delle Ricerche, Via Sant a Maria 46, 56126 Pisa, It aly, mont ani@icnucevm.cnuce.cnr.it
Doug Moore (406), Depart ment of Comput er Science, Rice Universit y, P.0. Box 1892,
Houst on, Texas 77254, dougm@rice.edu
Jack C. Mor r ison (10), 5654 Sout h Jackpine Road, Evergeen, Colorado 80439,
ncar!boulder!agcsun!jackm
F. Ken Musgr ave (25, 163), Depart ment s of Mat hemat ics and Comput er Science, Yale
Univ ersit y, Box 2155 Yale St at ion, New Hav en, Connect icut 06520,
musgrave@yale.edu
Chr ist opher J. Musial (387, 435), 801 Leonard Drive, Rock Hill, Missouri 63119
Alan W. Paet h (93, 143, 147, 174, 371, 381, 440), NeuralWare, Inc., Penn Cent er West
Building 4, Suit e 227, Pit t sburgh, Pennsylvania 15276
xxxi
CONTRIBUTORS
GRAPHICS GEMS II Edit ed by JAMES ARVO xxxi
Mar k J. Pavicic (299), Minard 300, Nort h Dakot a St at e Universit y, Fargo, Nort h
Dakot a 58105, pavicic@plains.nodak.edu
And rew Pearce (273, 275), Alias Research, #500, 110 Richmond St reet E., Toront o,
Ont ario, Canada M5C IPI, pearce@alias.UUCP
Mukesh Pr asad (7), Met a Mind, Inc., Two Trolley Square, Suit e 146, East Haven,
Connect icut 06512
Jack Rit t er (392), SHO Graphics, 1890 N. Shoreline Boulevard, Mount ain View,
California, 94043
Jon Rokne (5, 14, 17, 19), Depart ment of Comput er Science, Universit y of Calgary,
Calgary, Albert a, Canada T2N 1N4, rokne@cpsc.ucalgary.ca
David Schilling (371), 4609 148t h Avenue NE II201, Bellevue, Washingt on 98007
John F. Schlag (105, 377, 417), 105-A Fairview Avenue, Capit ola, California 95010
Dale A. Schumacher (50, 57, 78), 399 Beacon St reet , St . Paul, Minnesot a 55104,
dal@synt el. mn. org
Rober t o Scopigno (202), Inst it ut o CNUCE Consiglio Nazionale delle Ricerche, Via
Sant a Maria, 36, 56126 Pisa, It aly, scop@icnucevm.cnuce.cnr.it
Hans-Pet er Seid el (424, 428), Depart ment of Comput er Science, Universit y of Wat erloo,
Wat erloo, Ont ario, Canada N2L 3G1, hpseidel@wat cgl.wat erloo.edu
Clifford A. Shaffer (172), Depart ment of Comput er Science, Virginia Tech, Blacksburg,
Virginia 24061, shaffer@cs.vt .edu
Pet er Shirley (306), Comput er Science Depart ment , 101 Lindley Hall, Indiana Universit y,
Bloomingt on, Indiana 47405-4101, shirley@cs.indiana.edu
Kennet h Shoemake (351, 366, 368, 394, 412), Xerox PARC, 3333 Coyot e Hill Road,
Palo Alt o, California 94304
Fr anois Sillion (311), Cornell Universit y, Program of Comput er Graphics, It haca,
New York, 14853, fxs@fsat urn.graphics.cornell.edu
Jonat han E. St einhar t (31), 20180 Baker Creek Road, McMinnville, Oregon 97128-
8016
Filippo Tampier i, (303), Program of Comput er Graphics, 580ETC Building, Cornell
Universit y, It haca, New York, 14853, fxt @graphics.cornell.edu
Daniel Thalmann (232), Comput er Graphics Laborat ory, Swiss Federal Inst it ut e of
Technology, CH-1015 Lausanne, Swit zerland, t halmann@ligsg2.ep.ch
Nad ia Magnenat Thalmann (232), MIRALab, CUI, Universit y of Geneva, 12 rue du
lac, C 1207, Geneva, Swit zerland, t halmann@uni2a.unige.ch
Spencer W. Thomas(72, 116, 320), EECS Depart ment , Universit y of Michigan, 1101
Beal Avenue, Ann Arbor, Michigan 48109-2110, spencer@eecs.umich.edu
xxxii
CONTRIBUTORS
GRAPHICS GEMS II Edit ed by JAMES ARVO xxxii
Samuel P. Uselt on (277, 283), NASA Ames Research Cent er, M/S T 045-1, Moffet t
Field, California 94035, uselt on@nas.nasa.gov
Douglas Voorhies (26, 257), Apollo Syst ems Division, Hewlet t -Packard, 300 Apollo
Drive, Chelmsford, Massachuset t s 01824, dougv@apollo.com
Greg War d (80, 396), Lawrence Berkeley Laborat ory, 1 Cyclot ron Road, 90-3111,
Berkeley, California, 94720, gjward@ldl.gov
Joe War ren (406), Depart ment of Comput er Science, Rice Universit y, P.0. Box 1892,
Houst on, Texas 77254, jwarren@rice.edu
Kevin Wu (342), Sun MicroSyst ems Inc., 2550 Garcia Avenue, MTV 21-04, Mount ain
View, California 94043, kevin.wu@eng.sun.com
Xiaolin Wu (126), Depart ment of Comput er Science, Universit y of West ern Ont ario,
London, Ont ario, Canada N6A 5B7, wu@csd.uwo.ca
Sue-Ken Yap (84), CSIRO Division of Informat ion Technology, P.0. Box 664, Can-
berra, ACT 2601, Aust ralia, ken@csis.dit .csiro.au
I
2D GEOMETRY
AND
ALGORITHMS
3 GRAPHICS GEMS II Edit ed by JAMES ARVO 3
2D GEOMETRY AND ALGORITHMS
I II II
2D GEOMETRY 2D GEOMETRY 2D GEOMETRY 2D GEOMETRY 2D GEOMETRY
AND AND AND AND AND
ALGORITHMS ALGORITHMS ALGORITHMS ALGORITHMS ALGORITHMS
Two-d imensional geomet r y per vad es comput er gr aphics. For t hat reason,
a gr aphics progr ammer requires t ools for solving a wid e var iet y of 2D
geomet r ical problems efficient ly. Solut ions t o sever al t ypical 2D problems
are present ed in t his Par t : comput ing t he area of a planar figure, t he d ist ance
from a point t o a line, and find ing t he minimal enclosing area for some set
of object s.
Problems of t his t ype ar ise par t ly because of t he inherent t wo-d imensional
nat ure of t he scr een or sur face on which gr aphics out put is d isplayed .
Anot her reason 2D geomet r y is impor t ant is t hat larger problems in t hree
d imensions are frequent ly at t acked by red ucing t hem t o smaller and simpler
problems in one or t wo d imensions. This t act ic of breaking a large problem
int o lit t le palat able ones is perhaps nowhere more evid ent t han in large
comput er progr ams. Gr aphics, in par t icular, t end s t o red uce ult imat ely t o
a large number of small 2D problems, increasing t he impor t ance of hand ling
each one robust ly and efficient ly.
The fir st six gems of t his Par t ad d ress some common 2D oper at ions t hat
can ser ve as basic build ing blocks for more complex t asks. The next
t wo gems d eal wit h gener at ing and u t ilizing a class of space-filling
cur ves. These cur ves are member s of an infinit e family of relat ed cur ves
t hat possess an int erest ing proper t y: If t he st eps in t heir const r uct ions are
car r ied out a sufficient ly large number of t imes, t he result ing cur ves will
come ar bit r ar ily close t o ever y point in some region of space. Alt hough
t his concept is equally valid in spaces of any d imension, space-filling
cur ves are most immed iat ely useful and accessible for comput er gr aphics
4 GRAPHICS GEMS II Edit ed by JAMES ARVO 4
2D GEOMETRY AND ALGORITHMS
when t hey are in t wo d imensions. For inst ance, t heir convolut ed pat hs
provid e an int erest ing ord er in which t o gener at e t he pixels of an image,
as d escr ibed in Gem number 1.8. The final gem in t his Par t d escr ibes a
uniform framework that provides many useful operations on two-dimensional
figures.
5
I.1 THE AREA OF A SIMPLE POLYGON
GRAPHICS GEMS II Edit ed by JAMES ARVO 5
I. 1 I. 1 I. 1 I. 1 I. 1
T TT TTHE AREA OF A SIMPLE HE AREA OF A SIMPLE HE AREA OF A SIMPLE HE AREA OF A SIMPLE HE AREA OF A SIMPLE
P PP PPOLYGON OLYGON OLYGON OLYGON OLYGON
Jon Rokne
Universit y of Calgary
Calgary, Albert a, Canada
The for mula for t he area of a t r iangle is given in Tr iangles (Gold man,
l990b). This was gener alized by St one (1986) t o a for mula for a simple
polygon t hat is easy t o remember.
Let P
i
= (x
i
, y
i
), i = 1, . . . , n be t he count erclockwise enumer at ion of
t he ver t ices of t he polygon as in Fig. 1.
The area of t he polygon is t hen

A
1
2
x
1
x
2
x
n
x
1

y
1
y
2
y
n
y
1

,
where t he int er pret at ion of


x
1
x
2
x
n
x
1
y
1
y
2
y
n
y
1

is t he su mming of t he p rod u ct s of t he d ownward s d iagonals and
subt r act ion of t he prod uct of t he upward s d iagonals.
A specic example ser ves t o clar ify t he for mula. Consid er t he polygon
in Fig. 2.
The area of t his polygon is
A =

1
2

6 5 2 4 2 6
2 4 3 3 1 2

= (6 4 + 5 3 + 2 3 + 4 1 + 2 2
5 2 2 4 4 3 2 3 6 1)/ 2
= 7.5.
6
I.1 THE AREA OF A SIMPLE POLYGON
GRAPHICS GEMS II Edit ed by JAMES ARVO 6
Figur e 2.
See also IV. 1 Th e Ar ea of Pl a n a r Pol ygon s a n d Vol u me of
Polyhed r a, Ronald N. Gold man
7
I.2 INTERSECTION OF LINE SEGMENTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 7
I. 2 I. 2 I. 2 I. 2 I. 2
I II IINTERSECTION OF NTERSECTION OF NTERSECTION OF NTERSECTION OF NTERSECTION OF
L LL LLINE SEGMENTS INE SEGMENTS INE SEGMENTS INE SEGMENTS INE SEGMENTS
Mukesh Prasad
Met a Mind, Inc.
East Haven, Connect icut
Pr obl em Pr obl em Pr obl em Pr obl em Pr obl em
Given t wo line segment s in 2D space, d et er mine whet her t hey int er sect or
not . If t hey int er sect , t hen d et er mine t he point of int er sect ion.
Al gor i t hm Al gor i t hm Al gor i t hm Al gor i t hm Al gor i t hm
The following approach is par t icular ly efcient if t he lines oft en d o not , in
fact , int er sect since it wor ks from par t ial result s. It also is ver y ad apt -
able t o int eger-only comput at ion.
Let t he line L12 connect point s (x1, y1) and (x2, y2).
Let t he line L34 connect point s (x3, y3) and (x4, y4).
Let t he equat ion of L12 be F(x, y) = 0, and t hat of L34 be G(x, y) = 0.
Then t his approach consist s of t he following st eps:
1. From t he equat ion of L12, by subst it ut ing x3 and y3 for x and y,
comput e r3 = F(x3, y3).
2. Comput e r4 = F(x4, y4).
3. If (i) r3 is not equal t o 0, (ii) r4 is not equal t o 0, and (iii) t he signs
of r3 and r4 are t he same (eit her bot h posit ive or bot h negat ive),
t he lines d o not int er sect . Ter minat e algor it hm.
8
I.2 INTERSECTION OF LINE SEGMENTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 8
4. From t he equat ion of L34, comput e r1 = G(x1, y1).
5. Comput e r2 = G(x2, y2).
6. If (i) r1 is not equal t o 0, (ii) r2 is not equal t o 0, and (iii) t he signs
of r1 and r2 are t he same, t he lines d o not int er sect . Ter minat e
algor it hm.
7. Lines int er sect (or t hey are collinear ). Comput e point of int er sec-
t ion
Not es Not es Not es Not es Not es
The algor it hm is d et er mining if:
(x 3, y 3) and (x 4, y 4) lie on t he same side of L12. If t hey do,
t he line segment s obviously do not int ersect .
(x 1, y1) a nd (x 2, y2) lie on t he same side of L34. If t hey do,
t he line segment s obviously do not int ersect .
Ot her wise, t he lines must int er sect , or be collinear.
Compar ison of signs usually is ver y efcient . The C Implement at ion for
t his gem (Append ix 2) assumes a 2s complement number represent a-
t ion, and uses t he XOR oper at ion t o d et er mine efcient ly whet her t he
signs are t he same or not .
The int er med iat e result s obt ained are useful in t he nal st epcom-
put e point of int er sect ionimproving t he algor it hm efciency.
The algor it hm, obviously, will wor k in oat ing point coord inat es; but if
all x
i
and y
i
ar e available as int eger s (as is usually t he case in bit map
gr aphics) and t he result is required on an int eger gr id , only int eger
ar it hmet ic is required . However, for int eger-only ar it hmet ic, care should
be t aken t o guard against t he possibilit y of over ow. The polynomial
evalu at ions in t he C Imp lement at ion (Ap p end ix 2) are at most of
d egree 3; t herefore, using 32-bit int eger s, a r ange of 0-1023 in bot h X
and Y d irect ions can be hand led . For larger r anges, oat ing point
oper at ions may be necessar y, or a rear r angement of t he int er sect ion-
point comput at ions may be necessar y.
9
I.2 INTERSECTION OF LINE SEGMENTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 9
For fur t her efciency, t he cases of r1, r2, r3, or r4 being 0 can be
hand led separ at ely. In t hese sit uat ions, one of t he end point s is t he
point of int er sect ion, and need not act ually be comput ed
If a collinear it y check need s t o be efcient , it can also be d et er mined
from t he fact t hat bot h r3 and r4 (or bot h r1 and r2) will be 0 in t his
case. The lines may or may not over lap in t his case, and if necessar y,
t hat can be easily d et er mined by compar ing ext ent s.
See also (49) A Fast 2D Point -on-Line Test , Alan W. Paet h;
(304) Int ersect ion of Two Lines in Three-Space, Ronald
Goldman
1 0
I.3 DISTANCE FROM A POINT TO A LINE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 0
I. 3 I. 3 I. 3 I. 3 I. 3
D DD DDISTANCE FROM ISTANCE FROM ISTANCE FROM ISTANCE FROM ISTANCE FROM
A AA AA POINT TO A LINE POINT TO A LINE POINT TO A LINE POINT TO A LINE POINT TO A LINE
Jack C. Morrison
Evergreen, Colorado
This Gem gives efcient for mulae for t he d ist ance d
l
bet ween a point P
and t he line d ened by point s A and B, and t he d ist ance d
2
bet ween P
and t he line segment AB. (See Fig. 1.) An example of t his applicat ion is
an int er act ive progr am searching for a d isplayed line segment nearest t o
a cur sor being moved by t he user. For t his t ype of oper at ion, coord inat es
usually are int eger s, and comput at ionally expensive funct ions need t o be
avoid ed t o provid e r apid response. Oft en, nd ing d
2
1
or d
2
2
is sufcient .
The d ist ance from a point t o a line is t he lengt h of t he segment PQ
per pend icular t o line AB. St ar t wit h t he for mula for t he area of t r iangle
ABP,

1
2
|A
x
B
y
+ B
x
P
y
+ P
x
A
y
A
y
B
x
B
y
P
x
P
y
A
x
|.
Rear r anging t er ms t o save mult iplies gives t he following for mula for a2,
t wice t he signed area of ABP:
a2 = (P
y
A
y
)(B
x
A
x
) (P
x
A
x
)(B
y
A
y
).
Since t he area of ABP is also given by

1
2
d
1
|AB|,
1 1
I.3 DISTANCE FROM A POINT TO A LINE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 1
Figure 1.
t he square of t he d esir ed d ist ance can be comput ed as

1
2
d
a2
2
B
x
A
x
( )
2
+ B
y
A
y
( )
2
.
The d ifferences in t he d enominat or alread y were comput ed for a2, so t he
t ot al oper at ion count is six adds, ve mult iplies, and one divide. If d
l
is need ed d irect ly, a square root also is necessar y; but if an approxima-
t ion will d o, we can apply Alan Paet h' s Graphics Gem shor t cut for |AB|
t o get


a2
B
x
A
x
+ B
y
A
y

1
2
min B
x
A
x
, B
y
A
y
( )
for an approximat e d ist ance wit h only t wo mult iplies and one divide.
d

1 2
I.3 DISTANCE FROM A POINT TO A LINE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 2
When t he per pend icu lar int er sect ion p oint Q is ou t sid e t he segment
AB, d
l
is shor t er t han d
2
, t he d ist ance from P t o t he nearest point of t he
segment . For applicat ions only int erest ed in segment s wit hin some maximum
d ist ance from P, a simple bound ing box t est can be used t o quickly reject
segment s t hat are t oo far away:
min(A
x
, B
x
) margin < P
x
< max(A
x
, B
x
) + margin,
min(A
y
, B
y
) margin < P
y
< max(A
y
, B
y
) + margin,
and t hen d
l
can be t aken as an approximat ion for d
2
.
To proper ly comput e t he d ist ance d
2
, not e r st t hat
d
2
= |AP| if Q is on t he half-line from A away from B,
d
2
= d
l
if Q is on t he segment AB,
d
2
= |BP| i f Q i s on t h e h a l f-l i n e fr om B a wa y fr om A.
The appropr iat e case can be d et er mined by using t he d ot prod uct equal-
it y,
AP AB = |AP| |AB| cos a
= (P
x
A
x
)(B
x
A
x
) + (P
y
A
y
)(B
y
A
y
),
where a is t he angle PAB.
If Q is at A, t hen a is 90, and cos a (and t he d ot prod uct ) is zero. If Q
is on t he same sid e of A as B, a is less t han 90, and t he d ot prod uct is
posit ive. This lead s t o t he following algor it hm for d
2
:
t (Px Ax)(Bx Ax) + (Py Ay)(By Ay) (dot product )
i f t < 0
then d 2 |AP| Q beyond A
el se begi n
t (Bx Px)(Bx Ax) + (By Py)(By Ay)
i f t < 0
then d 2 |BP| Q beyond B
el se d 2 d 1 Q on AB
end
1 3
I.3 DISTANCE FROM A POINT TO A LINE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 3
The coord inat e d ifferences again can be reused , and an approximat ion for
|AP| and |BP| may be sufcient .
Wit h int eger coor d inat es for A, B, and P, t hese for mu lae can be
comp u t ed wit hou t u sing oat ing p oint , alt hou gh care is requ ired t o
p revent over ow. For examp le, t he wor st case for t hree p oint s in a
512 512 region gives a value of 262,144 for a2, whose square exceed s
32 bit s.
See also (3) Useful 2D Geomet ry, Andrew S. Glassner
1 4
I.4 AN EASY BOUNDING CIRCLE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 4
I. 4 I. 4 I. 4 I. 4 I. 4
A AA AAN EASY BOUNDING N EASY BOUNDING N EASY BOUNDING N EASY BOUNDING N EASY BOUNDING
C CC CCIRCLE IRCLE IRCLE IRCLE IRCLE
Jon Rokne
Universit y of Calgary
Calgary, Albert a, Canada
In Graphics Gems (Rit t er, 1990), we nd a near-opt imal algor it hm for
comput ing a bound ing sphere for N point s in 3D space. Her e, we present
a simple exact algor it hm for comput ing t he smallest bound ing circle for
N point s P
l
, . . . , P
N
in 2D. It was d evised for a numer ical analysis
problem by E. Gr assmann, who met wit h a fat al climbing accid ent when
t he paper (Gr assmann and Rokne, 1979) was about t o be published .
We u se t h e con ven t i on t h at a p oi n t P i n 2D can be wr i t t en as
P = (P
x
, P
y
), wh er e P
x
i s t h e x coor d i n a t e of P a n d P
y
i s t h e y
coord inat e of P. Also, |P Q| is t he Eu clid ean d ist ance bet ween P
and Q.
From geomet r y, it follows t hat t he smallest bound ing circle is d ened
by t wo or t hree point s of t he point set . See, for example, Rad emacher and
Toeplit z (1957).
Case 1. The circle is d et er mined by t wo point s, P and Q. The cent er of
t he circle is at (P + Q)/ 2.0 and t he r ad ius is |(P Q)/ 2.0|.
Case 2. The circle is d et er mined by t hree point s, P, Q, and R, for ming
a t r iangle wit h acut e angles.
The t wo cases are shown in Fig. 1.
In bot h cases, t here may be ot her point s of t he point set lying on t he
circle.
The algor it hm proceed s as follows. Fir st , d et er mine a point P wit h t he
smallest P
y
. Then nd a point Q such t hat t he angle of t he line segment
PQ wit h t he x axis is minimal. Now nd R such t hat t he absolut e value
of t he angle PRQ is minimal.
If t his angle is acut e, t hen t he circle C
l
d et er mined by P, Q, and R
cont ainsaccord ing t o element ar y geomet r yall t he point s, since t here
1 5
I.4 AN EASY BOUNDING CIRCLE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 5
Figur e 1.
Figure 2.
1 6
I.4 AN EASY BOUNDING CIRCLE
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 6
are no point s t o t he r ight of t he d irect ed segment PQ. If t he t r iangle PQR
has acut e angles only, we are nished . If t he angle at R is obt use, t hen
t he cent er of t he circle we are looking for is (P + Q)/2.0 and t he r ad ius
is |(P Q)/ 2.0|.
If t he angle at P or Q is obt use, say at Q, we replace Q by R and
repeat t o get a circle C
2
. See Fig. 2.
From element ar y geomet r y, it follows t hat t he cent er of C
l
is t o t he left
of t he d irect ed line segment PR, since t he angle at Q ot her wise would be
acut e. Since t he r ad ius of C
2
at most is as large as t hat of C
l
, it follows
t hat all t he point s insid e C
l
t hat are t o t he r ight of t he segment PR also
are insid e C
2
. No point s are lost , t herefore, and C
2
cont ains all t he point s
of t he point set .
We claim t hat aft er nit ely many repet it ions, we get t he minimal circle.
To show t his, we only need t o obser ve t hat a point t o t he r ight of t he line
segment PR st ays t o t he r ight , and t herefore, we have at most N 2
it er at ions.
The algor it hm has a wor st -case complexit y of O(N 2).
See also (301) An Efcient Bounding Sphere, Jack Rit t er
1 7
I.5 THE SMALLEST CIRCLE CONTAINING THE INTERSECTION OF TWO CIRCLES
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 7
I. 5 I. 5 I. 5 I. 5 I. 5
T TT TTHE SMALLEST CIRCLE HE SMALLEST CIRCLE HE SMALLEST CIRCLE HE SMALLEST CIRCLE HE SMALLEST CIRCLE
C CC CCONTAINING THE INTERSECTION ONTAINING THE INTERSECTION ONTAINING THE INTERSECTION ONTAINING THE INTERSECTION ONTAINING THE INTERSECTION
O OO OOF TWO CIRCLES F TWO CIRCLES F TWO CIRCLES F TWO CIRCLES F TWO CIRCLES
Jon Rokne
Universit y of Calgary
Calgary, Albert a, Canada
In Graphics Gems (Thompson, 1990), an algor it hm is given for t he area
of int er sect ion of t wo circles. Here we give a simple pseud o-cod e for
nd ing t he cent er and r ad ius of t he smallest circle cont aining t he int er-
sect ion of t wo circles.
We use t he convent ion t hat a point in 2D can be wr it t en as P = (P
x
, Py)
where P
x
is t he x coord inat e of P and P
y
is t he y coord inat e of P. Also,
|P Q| is t he Euclid ean d ist ance bet ween P and Q.
The t wo circles are (P, r) and (Q, s) and t he circle cont aining t he
int er sect ion is (R, t ).
In Fig. 1, we show t he case of non-t r ivial int er sect ion.
Let l = |P Q|. Then from t he geomet r y, we have for t his case t he t wo
equat ions,
z
2
+ t
2
= r
2
,
(l z)
2
+ t
2
= s
2
,
which can be solved for
z = (l
2
+ r
2
s
2
)/ (2l),

t r
2
z
2
.
Th e ot h er ca ses a r e (P, r) (Q, s), (Q, s) (P, r), a n d (P, r)
(Q, s) = .
1 8
I.5 THE SMALLEST CIRCLE CONTAINING THE INTERSECTION OF TWO CIRCLES
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 8
Pseudo- Code Pseudo- Code Pseudo- Code Pseudo- Code Pseudo- Code
l |P Q|;
If l > r + s then int ersect ion empt y
el se i f l + r < s then C P, t r;
el se i f l + s < r then C q, t s;
el se begi n
z (l
2
+ r
2
s)/(2l);
t

r
2
z
2
;
R P + (P Q)z/ l;
end
endi f
endi f
endi f
See also 1.6 Appoloniuss 10t h Problem, Jon Ro ne
Figur e 1.
1 9
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 1 9
I. 6 I. 6 I. 6 I. 6 I. 6
A AA AAPPOLONIUS S IOTH PPOLONIUS S IOTH PPOLONIUS S IOTH PPOLONIUS S IOTH PPOLONIUS S IOTH
P PP PPROBLEM ROBLEM ROBLEM ROBLEM ROBLEM
Jon Rokne
Universit y of Calgary
Calgary, Albert a, Canada
A problem t hat occur s in comput er gr aphics and CAD is t he const ruct ion
of t he smallest circle t ouching t hree given circles from t he out sid e. This
problem alread y was consid ered by Appolonius (c. 262-190 B.C.).
The solut ion given here was used in a numer ical analysis problem
(Gr assmann and Rokne, 1979).
It should be point ed out t hat t he problem of nd ing t he smallest sphere
cont aining t hree given spheres also is red uced t o t he problem of Appolo-
nius by consid er ing t he plane passing t hrough t he cent er s of t he spheres.
We not e r st t hat t he problem may have no solut ion; i.e., t here might
not exist a circle t ouching t he given circles from t he out sid e. See Figs. 1
and 2.
In Fig. 1, t here is no circle t hat t ouches t he given circles, whereas in
Fig. 2, at least one of t he cir cles has t o be ou t sid e. The d ecision
proced ure for t he case in Fig. 1 is obvious, whereas t he d ecision proce-
d u re for t he case in Fig. 2 requ ir es t he comp u t at ion of t he ou t sid e
common t angent s of t he largest and t he smallest circle as well as for t he
largest and t he mid d le circle. See Glassner (1990b).
It is convenient t o use some geomet r ic proper t ies of complex analysis
t o d evelop t he algor it hm. These are not st ressed in t he usual cour ses in
complex analysis in Nor t h Amer ica; hence, we refer t o Behnke et al.,
(1983), where t he required for mulas are given.
We id ent ify point s in t he plane wit h complex quant it ies; t hat is, if Z is
a p oint in 2D, t hen we wr it e t he x coord inat e as Re Z and t he y
coord inat e as Im Z, and we also t hink of it as a complex quant it y,
Z = Re Z + i Im Z. An over line means reect ion wit h t he real axis for a
2 0
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 0
Figur e 1.
Figure 2.
2 1
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 1
mapping t he Z plane int o a W plane.
This maps t he unknown circle int o a st r aight line, t he t wo ot her circles
int o circles wit h cent er s and r ad ii (W
i
,
i
), where (as shown by Gargant ini
and Henr ici (1972), Eq. (2.1), or any t ext book d escr ibing t he Moebius
t r ansfor mat ion)
Figur e 3.

W
i

Z
i
Z
3
( )
Z
i
Z
3
2
r
i
( )
2

i

r
i

Z
i
Z
3
2
r
i
( )
2
i = 1, 2. (1)
, ,
point in 2D and t he complex conjugat e when we consid er t he point as
a complex quant it y.
Let (Z
i
, r
i
), i = 1, 2, 3 be t he cent er and r ad ii of t he circles. Fir st , subt r act
t h e sma l l est r a d i u s, sa y r
3
, fr om t h e ot h er t wo, get t i n g r
i
*=
r
i
r
3
.
If we can find a circle (Z, r) t hat passes t hrough Z
3
and t ouches (Z
i
, r
i
*),
i = 1, 2 from out sid e, t hen t he d isc (Z, r + r
3
) will be t he solut ion t o t he
or iginal problem. The geomet r y of t his is shown in Fig. 3.
To find t his circle, we use t he t r ansfor mat ion,

W (Z)
1
Z Z
3
,
2 2
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 2
Not e t hat
i
< 0 if Z
3
is cont ained in d isc i, i = 1, 2, and t hat any circle
t hrough Z
3
in t he Z plane is mapped int o a line in t he W plane.
The problem now is t o nd a common t angent line, l: Re UW = c, in
t he W plane. This line mapped back int o t he Z plane will provid e t he
d esired circle.
If l separ at es t he cent er s from t he or igin, t he cor respond ing circle in
t he Z plane will separ at e t he cent er s from , i.e., cont ain t he given d iscs
insid e.
The const ant s U and c are d et er mined by t he following met hod .
We can assume t hat |U| = 1. Then t he d ist ance for mula gives
Re UW
i
c =
i
, i= 1, 2. (2)
Subt r act ing, we get
Re U(W
1
W
2
) =
1

2
,
and calling
= arg U(W
1
W
2
),
we get
cos =

1

2
W
1
W
2
(3)
and
sin =

t 1 cos
2
,
(4)
so
cos + i sin =

U W
1
W
2
( )
W
1
W
2
,
and mult iplying bot h sid es by

W
1
W
2
( )
W
1
W
2
,
2 3
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 3
we get
U = (cos + i sin )

W
1
W
2
( )
W
1
W
2
. (5)
The ambiguit y of t he root in Eq. (2) gives t he t wo solut ions, U
l
, U
2
,
exp ect ed fr om geomet r y. (The geomet r ic meaning of is t he angle
bet ween t he nor mal of l and t hat of t he line joining W
l
and W
2
.) The fact
t hat we have posit ive
i
has t he geomet r ic meaning t hat t he nor mals U
j
point t oward s t he cent er s, and t he line d oes not separ at e t he cent er s.
Using t he r st of t he equ at ions, (2), we get t he cor resp ond ing c
j
,
c
j
= Re W
1
U
j

i
.
The line separ at es t he W
i
from t he or igin if c
j
> 0.
We shall need t he point s of cont act as well. They are
T
i

j
= W
i

i
U
j
, i = 1, 2, j = 1, 2. (6)
We now t r ansfor m t he equat ions, Re U
j
W = c
j
, back int o t he Z plane
and get
Re

U
j
Z Z
3



1
Z Z
3
2
Re U
j
(Z Z
3
) = c
j
,
and wr it ing Z Z
3
= + i, U
j
= m
j
+ in
j
, we get
m
j
+ n
j
= c
j
(
2
+
2
),
or since, |U
j
| = 1,



m
j
2c
j
|
.

`
,

2
+
n
j
2c
j
|
.

`
,

2
=
1
4c
j
2 ,
i.e., t he circle has cent er Z = U
j
/ (2c
j
) + Z
3
and r ad ius r = 1/ (2c
j
).
We can see t hat we need only t he line for which c
j
is great er, since we
are int erest ed in t he circle of minimal r ad ius.
2 4
I.6 APPOLONIUS S 10TH PROBLEM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 4
The point s of cont act are

T
ij

1
T
ij
*
+ Z
3
.
The comput at ions are quit e simple as shown by t he following pseud o-
cod e.
Pseudo- Code Pseudo- Code Pseudo- Code Pseudo- Code Pseudo- Code
Comput e

1

r
,
2

r .
Comput e W
1
, W
2
,
1
,
2
from (1).
Comput e cos from (3) and sin from (4).
Comput e c
1
, c
2
from (5).
Choose c = max (c
1
, c
2
) and corresponding U from (5).
The required circle is t hen Z = U/ (2c) + Z
3
wit h radius r = 1/ (2c).
See also 1.5 Th e Smallest Cir cle Con t ain in g t h e In t er sect ion of
Two Circles, Jon Rokne
2 5
I.7 A PEANO CURVE GENERATION ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 5
I. 7 I. 7 I. 7 I. 7 I. 7
A AA AA PEANO CURVE PEANO CURVE PEANO CURVE PEANO CURVE PEANO CURVE
G GG GGENERATION ALGORITHM ENERATION ALGORITHM ENERATION ALGORITHM ENERATION ALGORITHM ENERATION ALGORITHM
Ken Musgrave
Yale Universit y
New Haven, Connect icut
One occasionally may d esire a space-lling Peano curve in n d imensions
(Peano, 1980). The Peano cur ve is a fr act al wit h int eger-fr act al d imen-
sion. This cur ve provid es a cont inuous mapping from t he int eger s t o
n-space, wit h t he proper t ies t hat all point s in t he d omain are close in t he
r ange, and most point s t hat are close in t he r ange are close in t he d omain.
Applicat ions we have found includ e image compression, color quant iza-
t ion (St evens et al., 1983; Whit t en and Neal, 1982), and d ebugging for
int er act ive four-d imensional rot at ion rout ines.
We have implement ed But zs algor it hm (1971) for gener at ing an n-
d imensional Peano cur ve t o m bit s of precision, t hat is, wit h 2
m
seg-
ment s per d imension,

2
m
n
segment s t ot al. It is based on bit wise boolean
oper at ions, and is t he only algor it hm we have ever cod ed where we have
had absolu t ely no insight int o how it wor ks. Bu t t he cod es cor rect
oper at ion has been ver ied in t wo, t hree and four d imensions. See gs. 1
and 2 (color inser t ) for an example in 2-d imensions.
The algor it hm, bu t not it s d er ivat ion, is d escr ibed in Bu t z (1971).
Unfor t unat ely, no insight is offered t here for t he logic of t he algor it hm.
See also 1.8 Space-Filling Cur ves and a Measure of Coherence,
Douglas Voorhies
1.7 Figures 1 and 2. These plates show the Peano curve in two dimensions with 8 subdivisions, or bits of
precision, at 512 by 512 resolution. Thus alternating pixels are covered by the curve. The two images represent
the same curve, as seen at different points in a colormap animation performed by ran_ramp. Note the changing
patterns created by the colormap animation.
2 6
I.8 SPACE-FILLING CURVES AND A MEASURE OF COHERENCE
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 6
I. 8 I. 8 I. 8 I. 8 I. 8
S SS SSPACE-FILLING CURVES AND PACE-FILLING CURVES AND PACE-FILLING CURVES AND PACE-FILLING CURVES AND PACE-FILLING CURVES AND
A MEASURE OF COHERENCE A MEASURE OF COHERENCE A MEASURE OF COHERENCE A MEASURE OF COHERENCE A MEASURE OF COHERENCE
Douglas Voorhies
Hewlet t Packard Co.
Chelmsf ord, Massachuset t s
Tr aver sal Tr aver sal Tr aver sal Tr aver sal Tr aver sal
Per for mance of r ay t r acer s and ot her rend er ing algor it hms can be im-
proved by alt er ing t he pr imar y r ay gener at ion sequence. The key is t o
bet t er exploit coherence.
Coherence p r ovid es op p or t u nit ies t o u se memor y more effect ively.
Mod er n memor y hier archies employ caches, t r anslat ion look-asid e buffer s,
and p aging, which d ep end u p on ext reme rep et it ion in t he reference
pat t er n. In t his environment , rend er ing approaches t hat minimize chur n-
ing of t he wor king set runs consid er ably fast er, even if t he t ot al comput a-
t ion is t he same.
Object -space rend er ing (e.g., r ay t r acing or rever se-mapped volumet -
r ic) t ypically processes t he screen-space pixels in scanline ord er, which
is med iocre in it s chur ning of t he wor king set . An object whose screen
project ion is sever al pixels across will have sever al consecut ive pixels
t hat enjoy t he same int er sect ions and similar light ing exper iences, but t he
scanline t r aver sal sequence t hen leaves t he object and d oes not ret ur n for
a long t ime. Thus, scanline t r aver sal exploit s only one d imension of
object coherence.
An id eal t r aver sal sequence visit s all t he pixels in t he ent ire ar ea of
each object before moving on t o t he next object , t hus exploit ing coher-
ence in t wo d imensions. Unfor t unat ely, t here is a wid e r ange of on-screen
object sizes, and neit her t heir size nor p osit ion is known a priori.
Fur t her more, d ifferent levels of memor y hier archies wor k best wit h repe-
t it ion wit hin wor king set s of d ifferent sizes. Thus, t he concept of object
2 7
I.8 SPACE-FILLING CURVES AND A MEASURE OF COHERENCE
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 7
area in t his cont ext may be ext end ed t o mean repet it ious access at many
size levels.
Two imp or t ant p r op er t ies for a t r aver sal sequ ence which exp loit s
coherence are t hat :
1. All t he pixels in an area are visit ed before moving on.
2. The sequent ially visit ed areas always are adjacent .
Bot h proper t ies d ecrease t he reload ing of memor y by minimizing t he
number of t imes an object area is exit ed and reent ered . Assuming t hat t he
t r aver sal sequence is xed r at her t han ad apt ive, it s select ion must be
based on shape alone.
Space- Fi l l i ng Cur ves Space- Fi l l i ng Cur ves Space- Fi l l i ng Cur ves Space- Fi l l i ng Cur ves Space- Fi l l i ng Cur ves
Some space-lling cur ves can exploit coherence in t wo d imensions d e-
spit e a r ange of object area sizes. As fr act als, t hey are self-similar at
mult iple resolut ions. Thus, if t hey d o a good job of visit ing all t he pixels
cor respond ing t o a par t icular object area at one scale, t hen t hey may have
Normal uni di recti onal Peano Curve Hi l bert Curve
scanl i ne traversal
Figur e 1.
2 8
I.8 SPACE-FILLING CURVES AND A MEASURE OF COHERENCE
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 8
t his ad vant age for much larger or smaller object areas. As t opologically
cont inuous cur ves, areas visit ed always are ad jacent . Let us look at t wo of
t hem, as shown in Fig. 1.
Peano curves ar e r ecu r si ve bou st r op h ed on i c p at t er n s. Th ey sn ake
back and for t h at mult iple recur sion levels, lling t he plane. Since each
pat t er n ent er s and exit s from opposit e rect angle cor ner s, t hey implicit ly
use ser pent ines wit h an od d number of swat hs, a minimum of t hree. Thus,
t hey can be self-similar at 3 3, 9 9, 27 27, 81 81, et c. resolu-
t ions. (If squeezed in one d imension only, t hey can repeat as 2 3,
6 9, 18 27, 54 81, et c.)
A Hilbert curve is fold ed even more t ight ly. It can visit all t he pixels in
a 2 2, 4 4, 8 8, 16 16, et c. area before moving on, so it s
self-similar, area-lling pat t er ns are more numerous and closer t oget her
in scale.
A Measur e of Coher ence A Measur e of Coher ence A Measur e of Coher ence A Measur e of Coher ence A Measur e of Coher ence
How can one measu re t he abilit y of a t r aver sal sequ ence t o exploit
coherence, ind epend ent of a specic image and rend erer ? A pr agmat ic
measure can be based on t he not ion of a memor y wor king set . For a given
object area, any t r aver sal will consist of consecut ive pixels t hat are wit hin
t hat object s screen project ion and ot her s t hat lie out sid e. Par t of t he
wor king set of a rend erer can be t hought of as t he current object area
Figur e 2.
2 9
I.8 SPACE-FILLING CURVES AND A MEASURE OF COHERENCE
GRAPHICS GEMS II Edit ed by JAMES ARVO 2 9
Figure 3. Aver age coherence of Peano and Hilber t t r aver sal sequences for object
r ad ii of .5 t o 100.
3 0
I.8 SPACE-FILLING CURVES AND A MEASURE OF COHERENCE
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 0
plus t he recent ly t ouched ones. In t his cont ext , high coherence means
st aying wit hin t he cur rent object area (or near by ones) most of t he t ime,
and vent ur ing out sid e r arely, unt il all t he cur rent object area pixels have
been visit ed .
To make t his concret e, I assume t hat an imaginar y object project s as a
circle in screen space. Choosing a circle favor s no t r aver sal d irect ion over
anot her. Coherence of a t r aver sal sequence t hen is t he cur rent object
circles d iamet er d ivid ed by t he nu mber of t imes t he sequ ence exit s
t he circle. Hyst eresis is ad d ed by only count ing pat hs t hat exit t he ob-
ject circle and t hen vent ure anot her r ad ius away; t his avoid s penalizing
small excur sions beyond t he circle t hat immed iat ely ret ur n. See Fig. 2.
By t his pr agmat ic measure, object areas not t ouching t he screen ed ges
have a coherence measure of 1.00 for nor mal scanline t r aver sal, since all
sequences t hat penet r at e t he circle exit and cont inue all t he way t o t he
screen ed ge and t hus are count ed . For Fig. 3, a 1024 1024 screen is
t r aver sed by t hree met hod s: nor mal scanline t r aver sal, a Peano cur ve, and
a Hilber t cur ve. (Since t he Peano cur ve d id not t evenly int o 1024
1024, it was clipped .) The coherence of 1000 circles cent ered at r and om
on-screen posit ions is aver aged for a r ange of r ad ii.
Bot h t he Peano and Hilber t cu r ves far exceed t he coherence = 1.00
measure of convent ional scanline t r aver sal. The Hilber t cur ve appear s
su p er ior, and is easier t o gener at e. Bet t er p er for mance fr om a real
rend erer can be expect ed simply by choosing eit her of t hese alt er nat ive
t r aver sal sequences.
See also 1.7 A Peano Cur ve Gener at ion Algor it hm,
Ken Musgr ave
3 1
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 1
I. 9 I. 9 I. 9 I. 9 I. 9
S SS SSCANLINE COHERENT CANLINE COHERENT CANLINE COHERENT CANLINE COHERENT CANLINE COHERENT
S SS SSHAPE ALGEBRA HAPE ALGEBRA HAPE ALGEBRA HAPE ALGEBRA HAPE ALGEBRA
Jonat han E. St einhart
Independent Consult ant
McMinnville, Oregon
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Shape algebr a has many applicat ions in r ast er gr aphics. Wind ow manage-
ment syst ems use shape algebr a t o comput e t he visible regions of over-
lapping wind ows. Shape algebr a can be used t o implement caps and joins
in fat line d r awing cod e. POSTSCRI PT-st yle (Ad obe, 1985a, 1985b) clip
pat hs are yet anot her applicat ion of shape algebr a.
This gem d et ails an approach t o shape algebr a t hat can be implement ed
efcient ly as par t of a r ast er gr aphics syst em. Rout ines are provid ed t hat
imp lement t he basic union, int ersect ion an d difference op er at ion s as
shown in Fig. 1. A nu mber of u t ilit y fu nct ions and sp ecial p u r p ose
var iat ions also are provid ed , as are some example applicat ions.
Backgr ound Backgr ound Backgr ound Backgr ound Backgr ound
Previous published wor k in t his area falls int o t wo cat egor ies: quad t rees
(Samet , 1990a, 1990b) and t he Apple pat ent (At kinson, 1986).
Quadt rees are d at a st ruct ures t hat represent ar bit r ar y shapes t hrough
rect angular t wo-d imensional binar y subd ivision. Alt hough shape algebr a
can be per for med efcient ly on quad t rees, t he binar y subd ivision t ech-
nique makes it expensive t o coalesce ad jacent rect angles. This makes it
d ifcult t o t ake ad vant age of scanline coherence d ur ing r ast er izat ion.
The Apple pat ent uses a scanline-wid t h bit mask t o mar k hor izont al
t r ansit ions across t he region bound ar ies. The bit mask is upd at ed at each
ver t ical bound ar y t r ansit ion. Alt hough t he Apple approach allows one
t o t ake ad vant age of scanline coherence, it has t wo major d isad vant ages.
3 2
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 2
Figure 1. Basic shape algebr a oper at ions.
Fir st , t he bit mask is expensive t o maint ain for wid e scan lines. Second ,
t here is an unquant ied legal expense involved in t he ut ilizat ion of t his
pat ent .
Two unpublished paper s exist t hat d escr ibe por t ions of t he approach
present ed here, Gosling (1986) and Donat o and Rocchet t i (1988). Ear lier
ver sions of t his wor k appear in St einhar t et al. (1989, 1990).
Dat a St r uct ur es Dat a St r uct ur es Dat a St r uct ur es Dat a St r uct ur es Dat a St r uct ur es
Our approach is t o represent ar bit r ar y shapes as y-sor t ed list s of x-sor t ed ,
non-over lapping rect angles. The d ecomposit ion of an ellipse wit h a rect -
angular hole int o our shape represent at ion is shown in Fig. 2.
We st or e shape represent at ions as linked list s. Alt hough packed ar r ay
for mat s such as t he one d iscussed in St einhar t et al. (1989) are more
compact , a signicant amount of d at a copying can occur in t he d ifference
oper at ion. Also, it is d ifcu lt t o manage t he amou nt of ar r ay space
requ ir ed , since t he wor st -case combinat ion of a shap e cont aining m
rect angles wit h a shape cont aining n rect angles is a shape cont aining
m n rect angles.
Figure 2. Sample shape d ecomposit ion.
3 3
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 3
Figure 3. Represent at ion of a sample shape.
The choice of memor y management t echniqu es u sed for t he d at a
st r uct ures can have a d r amat ic impact on t he per for mance of t he algo-
r it hms. This gem d oes not go int o t he d et ails of memor y management ,
since t he choice of t echnique is ver y d epend ent on t he oper at ing environ-
ment .
A shape is a ver t ically or d er ed set of hor izont al spans. Each sp an
cont ains a hor izont ally ord ered set of segment s. The span d at a st r uct ure
cont ains t he y coord inat e of t he t op of t he span, a point er t o t he next
span, and a point er t o t he segment list . Each element of t he segment list
cont ains an x coord inat e and a point er t o t he next segment . Figure 3
shows a sample shape and t he d at a st ruct ures t hat represent it .
There are t hree sp ans in t he st ru ct u re. The r st one d escr ibes t he
rect angle ((10, 10),(50, 20)). The second span d escr ibes t he t wo rect an-
gles, ((10, 20),(20, 30)) and ((40, 20),(50, 30)). The t hird span d escr ibes no
rect angles and merely provid es t he upper y bound for t he second span.
Not e t hat we place t he pixels bet ween t he gr id lines as shown in Fig.
4a, not on t he gr id lines as shown in Fig. 4b.
3 4
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 4
Figure 4. Pixel locat ions.
Spans and st ruct ures are const ruct ed from inst ances of t he span and
segment d at a st r uct ures, d ened as follows:
segment : record [ span: record [
next : segment ; next : span;
x: i nteger; x: segment ;
]; y: i nteger;
];
We allow a NIL point er t o represent an empt y shape for convenience.
The Basi c Al gor i t hm The Basi c Al gor i t hm The Basi c Al gor i t hm The Basi c Al gor i t hm The Basi c Al gor i t hm
The shape algebr a rout ines alt er nat ely process spans in an out er loop
and segment s in an inner loop. Let us look at what happens wit h oper a-
t i on s on t wo si mp l e sh a p es, t h e r ect a n gl es ((10, 10), (20, 20)) a n d
((15, 15),(25, 25)), as shown in Fig. 5.
The ou t er loop cont ains t wo p oint er s, one for each sp an list . One
point er is ad vanced or bot h areeach t ime t hrough t he loop. The span
whose y value is lowest has it s point er ad vanced ; bot h point er s are
ad vanced if bot h spans have t he same y value. The effect is t o gener at e a
new set of span y values as shown in Fig. 6.
Figure 5. Two simple shapes.
3 5
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 5
Each it er at ion t hrough t he out er loop prod uces a y coord inat e and a
pair of segment s t o be oper at ed on by t he inner loop. Not e t hat t he out er
loop supplies an empt y segment in cases where one shape begins or end s
before t he ot her.
The inner loop processes t he segment s in much t he same manner as
t he out er loop processes t he spans. A bit is used t o keep t r ack of t he st at e
of each segment . Each x value t oggles t his st at e bit . The st at e bit s from
each segment are combined int o a st at e cod e as shown in Fig. 7.
Figure 7. St at e cod e gener at ion.
Figure 6. Span processing.
3 6
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 6
Figure 8. Shape algebr a opcod es.
One segment is ad vanced or bot h areeach t ime t hrough t he inner
loop. The segment t hat end s at t he lower x coord inat e is ad vanced ; bot h
segment s are ad vanced if t hey bot h end at t he same place. The st at e cod e
is monit ored ; x values t hat cause t he st at e cod e t o change t o or from t he
opcode are ad d ed t o t he out put . The effect of each opcod e is shown in
Fig. 8. Not e t hat cod e 1 prod uces AB; a cod e of 2 would pr od uce BA.
The x coord inat es in segment s come in pair s. The r st coord inat e in
each pair is a t r ansit ion from off t o on for t he coord inat e value. The
second coord inat e in each pair is a t r ansit ion from on t o off t hat
occur s aft er t he coord inat e value.
The basic shape algebr a rout ine is present ed as follows. Alt hough a
single r ou t ine cou ld be u sed t o imp lement all of t he op er at ions, a
consid er able amount of t ime can be wast ed using t he opcod e t o choose
t he ap p rop r iat e sp ecial case hand ling cod e. Su bst ant ial p er for mance
benet s can be realized by using opt imized cod e for each opcod e. The
special case hand ling cod e is d iscussed in t he following sect ions.
procedure shape_oper at ion(shape1, shape2, opcod e)
begi n
result x1 x2 NIL;
handle special cases t hat occur before t he shapes overlap in y
whi l e shape1 NIL and shape2 NIL do
begi n
t est shape1.y shape2.y;
i f t est 0 then
begi n y shape1.y; x1 shape1.x; shape1 shape1.next;
end;
3 7
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 7
i f t est 0 then
begi n y shape2.y; x2 shape2.x; shape2 shape2.next ;
end;
ag old 0;
segment NIL;
handle special cases t hat occur before t he shapes overlap in x
p1 x1; p2 x2;
whi l e p1 NIL and p2 NIL do
begi n
t est p1.x p2.x;
i f t est 0 then
begi n x p1.x; ag ag bi t-xor 1; p1 p1.next ; end;
i f t est 0 then
begi n x p2.x; ag ag bi t-xor 2; p2 p2.next ; end;
i f ag = opcod e or old = opcod e then
begi n append a new element t o segment wit h ualue x
end;
old ag;
end;
handle special cases t hat occur aft er t he shapes overlap in x
i f segment NIL or result NIL then
append a new element t o result wit h values y and segment
end;
handle special cases t hat occur aft er t he shapes overlap in y
return [result ];
end;
Int er sect i on Int er sect i on Int er sect i on Int er sect i on Int er sect i on
The int er sect ion algor it hm t akes ad vant age of t he fact t hat t he result is
empt y if one oper and is empt y. Only one piece of special case cod e is
necessar y; t he remaining pieces are empt y.
special case code for before t he shapes overlap in y
i f shape1 = NIL or shape2 = NIL
return [NIL];
3 8
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 8
Uni on Uni on Uni on Uni on Uni on
Bot h shape oper and s must be t r aver sed t o t he end in t he union algor it hm.
We can get some per for mance improvement by avoid ing t he t est s and
hand ling t he cases where one span or segment is empt y as st r aight for-
ward copies.
special case code for before t he shapes overlap in y
i f shape1 = NIL then
begi n return [a copy of shape2]; end;
i f shape2 = NIL then
begi n return [a copy of shape1]; end;
i f shape1.y < shape2.y then
begi n
copy t he span from shape1 and append it t o result
x1 shape1.x;
shape1 shape1.next ;
end;
el se i f shape2.y < shape1.y then
begi n
copy t he span from shape2 and append it t o result
x2 shape2.x;
shape2 shape2.next ;
end;
special case code for before t he shapes overlap in x
i f x1 NIL then
begi n copy x1; end;
el se i f x2 NIL then
begi n copy x2; end;
el se
do t he normal inner loop processing
special case code for aft er t he shapes overlap in x
i f x1 NIL then
begi n copy t he remainder of x1; end;
el se i f x2 NIL then
begi n copy t he remainder of x2; end;
3 9
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 3 9
special case code for aft er t he shapes overlap in y
i f shape1 NIL then
begi n copy t he remainder of shape1 t o result end;
el se
begi n copy t he remainder of shape2 t o result end;
Di f f er ence Di f f er ence Di f f er ence Di f f er ence Di f f er ence
Only t he r st shape oper and must be t r aver sed t o t he end in t he d iffer-
ence algor it hm. We can get some per for mance improvement by avoid ing
t he t est s and hand ling t he cases where one span or segment is empt y as
st r aight for ward copies.
special case code for before t he shapes overlap in y
i f shape1 = NIL then
return [NIL];
i f shape2 = NIL then
begi n return [a copy of shape1]; end;
i f shape1.y < shape2.y then
begi n
copy t he span from shape1 and append it t o result
x1 shape1.x;
shape1 shape1.next ;
end;
el se i f shape2.y < shape1.y then
begi n x2 shape2.x; shape2 shape2.next ; end;
special case code for before t he shapes overlap in x
i f x1 = NIL then
begi n segment is NIL; end;
el se i f x2 = NIL then
begi n copy x1; end;
el se
do t he normal inner loop processing
special case code for aft er t he shapes overlap in x
i f x1 NIL then
begi n copy t he remainder of x1; end;
4 0
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 0
special case code for aft er t he shapes overlap in y
i f shape1 NIL then
begi n copy t he remainder of shape1 t o result end;
Handy Ut i l i t i es Handy Ut i l i t i es Handy Ut i l i t i es Handy Ut i l i t i es Handy Ut i l i t i es
This sect ion present s sever al ut ilit y funct ions t hat make wor king wit h
shape d escr ipt ions easier. The r st creat es a shape from a d escr ipt ion of
a rect angle.
procedure shape_box(x, y, wid t h, height )
begi n
result new[span];
result .y y;
result .next new[span];
result .next .y y + height ;
result .next .next NIL.
result .x new[segment ];
result .x.x = x;
result .x.next new[segment ];
result .x.next .x x + wid t h;
result .x.next .next NIL.
return [result ];
end;
A u sefu l var iant of t he shape_box r ou t ine, shap_t mp_box, cr eat es t he
shape in a st at ic d at a area. This allows t empor ar y shapes t o be gener at ed
wit hout memor y allocat ion overhead .
The next ut ilit y makes a copy of a shape d escr ipt ion.
procedure shape_copy(shape)
begi n
for each span in shape do
begi n
add a span t o t he result wit h t he y from t he current span
4 1
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 1
for each segment in t he current span do
add a new segment t o t he new span wit h t he x from t he current
segment
end
return [result ];
end;
The t hird ut ilit y t r anslat es a shape by a relat ive x, y offset .
procedure shape_t r anslat e(shape, x, y)
begi n
for each span in shape do
begi n
span.y span.y + y;
for each segment in t he current span do
begi n segment .x segment .x + x; end
end
return;
end;
The nal ut ilit y d eallocat es t he st or age consumed by a shape d escr ipt ion.
procedure shape_free(shape)
begi n
whi l e shape NIL d o
begi n
x shape.x;
whi l e x NIL do
begi n t mpx x; x x.next ; free_memor y(t mpx); end
t mpy shape; shape shape.next ; free_memor y(t mpy);
end
return;
end;
Appl i cat i ons Appl i cat i ons Appl i cat i ons Appl i cat i ons Appl i cat i ons
Shape algebr a is useful for comput ing and represent ing t he visible area of
wind ows in wind ow management syst ems. Let us assume t hat we have a
4 2
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 2
hier archical wind ow syst em in which d escend ent wind ows are clipped t o
t heir ancest or s bou nd ar ies. The window d at a st r u ct u r e shown next
cont ains point er s t o ot her wind ows in t he wind ow t ree, t he size and
posit ion of t he wind ow, and t he visible area d escr ipt ion.
wind ow: record[
parent : wind ow; parent window
child : wind ow; highest priorit y (front most ) child)
n_sib: wind ow; next lowest priorit y sibling
p_sib: wind ow; next highest priorit y sibling
x: i nteger; x coordinat e of upper left corner
y: i nteger; y coordinat e of upper left corner
wid t h: i nteger; widt h of window
height : i nteger; height of window
visible: span; shape t hat describes visible area
];
Figure 9 shows how t he wind ow point er s d escr ibe t he relat ionship of a
wind ow wit h ot her wind ows in t he wind ow t ree.
The visible area for each wind ow in t he t ree can be comput ed using t he
following algor it hm.
Figure 9. Wind ow t ree
4 3
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 3
procedure comput e_wind ow_area( )
begi n
root .visible shape_box(r oot .x, root .y, root .wid t h, root .height );
comput e _subwind ow_area(root );
return
end
procedure comput e_subwind ow_area(parent )
begi n
for each child in order from front t o back do
begi n
shape_free(child .visible);
child .visible = shape_int er sect (parent .visible,
shape_t mp_box(child .x, child .y, child .wid t h, child .height ));
t mp = parent .visible;
parent .visible = shape_d ifference(parent .visible, child .visible);
shape_free(t mp);
comput e_subwind ow_area(child );
end
return
end
Complex gr aphical object s such as fat cur ves can be gener at ed using
shape algebr a. One t echnique for t he gener at ion of fat cur ves t o d r ag a
pen along t he cur ve t r aject or y. An example of t his t echnique is shown in
Fig. 10. The line mar ks t he act ual t r aject or y; t he d ashed boxes show t he
pen shape d escr ipt ion.
Figure 10. Fat cur ve gener at ion.
4 4
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 4
a) Shape t o d r aw b) Clipping shape c) Clipped d r awn shape
Figur e 11. Complex clipping.
The following algor it hm can be used t o gener at e fat cur ves. Not e t hat a
special union rout ine t hat t ook pen offset par amet er s would be more
efficient t han t he repeat ed t r anslat ion of t he pen shape d escr ipt ion.
cur ve_shape NIL
for each point in t he curve do
begi n
t r anslat ed _pen shape_t r anslat e(pen, point .x, point .y);
cur ve_shape = shape_union(cur ve_shape, t r anslat ed _pen);
shape_free(t r anslat ed _shape);
end
Anot her applicat ion of shape algebr a is complex clipping such as t hat
used by POSTSCRI PT and by wind ow management syst ems. The algo-
r it hms for t he r ast er izat ion of many pr imit ives, includ ing polygons (Foley
et al., 1990) and fat cur ves, prod uce out put t hat essent ially is a y-sor t ed
list of x-sor t ed r ect angles. These pr imit ives can be clipped easily t o
ar bit r ar y shapes using int er sect ion as shown in Fig. 11.
An efcient var iat ion on t he int er sect ion rout ine for clipping is int er-
sect and ll. This var iat ion invokes an act ual d r awing funct ion each t ime
a new rect angle would be ad d ed t o t he result shape inst ead of build ing
t he shape.
Impr ovement s Impr ovement s Impr ovement s Impr ovement s Impr ovement s
An examinat ion of shape algebr a applicat ions reveals a pat t er n; t empo-
r ar y shapes are being creat ed , u sed , and t hen d est royed . This gives
4 5
I.9 SCANLINE COHERENT SHAPE ALGEBRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 5
memor y management a real wor kout . The following t ype of oper at ion is
t ypical:
shape1 shape1 op shape2;
The amount of over lap bet ween shape oper and s oft en is minimal when
compared t o t he t ot al size of t he shapes in oper at ions such as fat cur ve
d r awing. The shape_union and shape_difference rou t ines can be mod i-
ed t o subst ant ially red uce memor y management overhead in such appli-
cat ions.
procedure shape_oper at ion(shape1, shape2, opcod e)
begi n
for any part of shape1 that comes before any part of shape2 do
det ach spans from shape1 and at t ach t hem t o t he result
do t he normal operat ion
for any part of shape1 that comes after any part of shape2 do
det ach spans from shape1 and at t ach t hem t o t he result
free t he spans in shape1 t hat overlapped shape2
This is effect ive only for t he union and d ifference oper at ions as t he
non-over lapping par t s of shapes are d iscard ed for int er sect ion oper at ions.
Shap e algebr a op er at ions can p rod u ce fr agment ed shap es in which
more t han t he minimal number of rect angles is used t o represent t he
shape. Su ch shapes can be comp ressed int o minimal rep r esent at ions,
alt hough t his t ypically consumes more t ime t han it saves. Compression is
a wor t hwhile opt imizat ion only in sit uat ions where a comput ed shape is
used for a long per iod of t ime wit hout being changed .
Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s
I would like t o t hank Julie Donnelly, Rober t Reed , and Ken Rhod es for
t heir proofread ing, wit hout which t his gem would have been awed .
I I
IMAGE
PROCESSING
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 9
II II II II II
I II IIMAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSING
The out put of ever y gr aphics progr am is an image. Images are t ypically
represent ed as a t wo-d imensional ar r ay of pixels, or some encod ing of
t hat infor mat ion. When t he input and out put of a progr am are bot h
images, we say t he p rogr am is p er for ming image processing. All t he
gems of t his par t involve some for m of image t r ansfor mat ion or change of
represent at ion. These includ e accur at e pixel represent at ions, scaling and
shar pening, rot at ion, mapping an image int o a near ly equivalent image
wit h fewer color s or shad es of gr ay, and compr ession.
This last t opic, compression, is d r iven by a ver y common problem. A
pict ure may be wor t h a t housand word s, but as many a gr aphics progr am-
mer will at t est , it frequent ly t akes many more t han a t housand word s t o
st ore one. In fact , t he st or ing of images is not or ious for eat ing up vast
amount s of second ar y st or age, such as d isk or t ape. For t unat ely, most
images cont ain a large amount of red und ant infor mat ion t hat can be
squeezed out for compact st or age. Two of t he gems in t his par t present
simple approaches for d oing just t hat .
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 0
II.1 II.1 II.1 II.1 II.1
I II IIMAGE SMOOTHING AND MAGE SMOOTHING AND MAGE SMOOTHING AND MAGE SMOOTHING AND MAGE SMOOTHING AND
SHARPENING BY DISCRETE SHARPENING BY DISCRETE SHARPENING BY DISCRETE SHARPENING BY DISCRETE SHARPENING BY DISCRETE
CONVOLUTION CONVOLUTION CONVOLUTION CONVOLUTION CONVOLUTION
Dale A. Schumacher
St Paul, Minnesot a
One of t he reasons for capt ur ing an image d igit ally is t o allow us t o
manipulat e it t o bet t er ser ve our need s. Oft en t his will includ e t r ying t o
improve t he subject ive appear ance of an image t hrough smoot hing of
gr ainy feat ures or shar pening of ind ist inct feat ures. These goals some-
t imes can be accomp lished t hrou gh t he u se of a discret e convolut ion
oper at ion (also called digit al filt ering).
Discret e convolut ion d et er mines a new value for each pixel in an image
by comput ing some funct ion of t hat pixel and it s neighbor s. Oft en t his
funct ion simply is a weight ed sum of pixel values in a small neighborhood
of t he source pixel. These weight s can be represent ed by a small mat r ix
t hat somet imes is called a convolut ion kernel. The d imensions of t he
mat r ix must be od d so t here will be a cent r al cell t o represent t he weight
of t he or iginal value of t he pixel for which we are comput ing a new value.
The new valu e is comp u t ed by mu lt ip lying each p ixel valu e in t he
neighborhood of t he cent r al pixel by t he cor respond ing weight in t he
mat r ix, summing all t he weight ed values, and d ivid ing by t he sum of
t he weight s in t he mat r ix. The following pseud o-cod e shows t his compu-
t at ion for a 3 3 convolut ion ker nel.
input : array [1..wid t h] of array [1..height ] of pi xel ;
out put : array [1..wid t h] of array [1..height ] of pi xel ;
ker nel: array [1..1] of array [1..1] of i nteger;
sum, ksum: i nteger;
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 1
comput e_out put _value(x: i nteger, y: i nteger);
begi n
sum 0;
ksum 0;
f or j: i nteger 1, j j + 1, j <= 1 do
f or i: i nteger 1, i i + 1, i <= 1 do
sum sum + (ker nel[i][j]*input [x + i][y + j]);
ksum ksum + ker nel[i][j];
endl oop;
endl oop;
out put [x][y] = sum/ ksum;
end;
One of t he simplest ker nels is one t hat gives all pixels in a 3 3
neighborhood equal weight, as shown in Fig. 2. This sometimes is called a
box lt er, since t he shape of t he lt er ing funct ion t his ker nel represent s
is a one-unit -high box t hree unit s on a sid e. This ker nel simply comput es
t he aver age pixel value over a 3 3 area and has a smoot hing effect on
t he image, since t he cent r al pixel is mad e more similar t o it s neighbor s.
The ker nel shown in Fig. 3 is similar t o t he box lt er, but ignores
complet ely t he or iginal value of t he cent er pixel. This prod uces a halo-like
effect around shar p ed ges in t he image. This lt er can be t hought of as
comput ing t he aver age of t he neighborhood sur round ing a pixel, a useful
concept t o remember for lat er d iscussion.
Fi gu r e 4 somet i mes i s ca l l ed a t riangle or t ent lt er beca u se i t
d enes a pyr amid -shaped volume. This lt er gives a lit t le more weight t o
t he cent er pixel, alt hough t he over all weight given t o t he cent er ver sus
t he sur round ing aver age is st ill

1
3
ver sus

2
3
, Not ice how t he st ronger
cent er-weight s in t his and t he next lt er red uce t he smoot hing effect .
Figu re 5 shows a half-and -half balance bet ween t he pixels cu r rent
value and t he value suggest ed by t he aver age of t he pixels neighbor s. If
t he d iagonal neighbor s were includ ed , wit h weight s of 1 in each cor ner,
t hen t he weight of t he cent r al pixel would have t o be 8 t o achieve t he
same half-and -half balance.
Anot her commonly used lt er is an approximat ion of a gaussian d ist r i-
but ion, as shown in Fig. 6. Sampling of t he real wor ld (which we assume
is a continuous function) to create a discrete image often is described as a
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 2
Figure 1. Or iginal t est
image
Figure 2. Figure 3. Figure 4.
Figure 5. Figure 6. Figure 7.
1 1 1
1 1 1
1 1 1
1 1 1
1 0 1
1 1 1
0 1 0
1 2 1
0 1 0
0 1 0
1 4 1
0 1 0
1 2 1
2 5 2
1 2 1
1 1 1
8 16 8
1 1 1
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 3
sequence of spat ially separ at ed gaussian-shaped samples; t hus, using a
gaussian weight ed lt er should accur at ely emulat e such sampling.
Up t o now, t he lt er s shown have been hor izont ally and ver t ically
symmet r ical. Somet imes, an asymmet r ic lt er is d esired , su ch as for
processing images t aken from int er laced vid eo. Since t wo eld s of a vid eo
fr ame are spaced 1/ 60t h of a second apar t in t ime, t he image oft en
shows much more coherence in t he hor izont al d irect ion, along t he scan-
line, t han in t he ver t ical. The lt er shown in Fig. 7 oft en wor ks well on
capt ured vid eo. Ver t ical lines are smoot hed , but hor izont al lines st ay
d ist inct .
Smoot h i n g r ed u ces n oi se by spreading it out over a l ar ger ar ea,
making it more d iffuse. This also has t he same effect on any shar p
t r ansit ions in a source image. Some d et ail will be lost by smoot hing, so
you must t ake care in how you apply t his oper at ion. Smoot hing wor ks
best on images where t he smallest d et ail of int erest is at least as large as
t he lt er ing ker nel, such as t he 3 3 pixels in t he examples given t hus
far. Smoot hing also can be used t o improve t he per for mance of some
compression and d it her ing algor it hms, by making t he changes in t he
pixels values more gr ad ual.
On t he ot her hand , t here are many t imes when we would r at her per for m
t he inver se of smoot hing t o shar pen an image, at t empt ing t o br ing out
d et ails t hat are ind ist inct . Int erest ingly enough, it is possible t o d o exact ly
t hat wit h a carefully chosen lt er ing ker nel.
If we look at smoot hing as a way of enhancing t he similar it y bet ween
near by pixels, shar pening should enhance t he d ifferences. If we t ake a
weight ed aver age of t he pixels sur round ing a given pixel, exclud ing t he
cent r al pixel (as in Fig. 3), and t ake t hat aver age away from t he value of
t he cent r al pixel, we enhance t he d ifference bet ween t hat pixel and it s
neighborhood . The ker nel in Fig. 9, somet imes called a discret e lapla-
cian lt er, comput es t his d ifference. By weight ing t he neighbor ing pixels
negat ively, we t ake t heir value away r at her t han ad d it t o t he cent r al pixel.
This prod uces t he d esired ed ge-shar pening effect . Not e t hat t he weight of
t he cent r al pixel is 1 great er t han t he sum of t he negat ive weight s. If t his
lt er is applied t o a large area of all t he same value, t he weight of t he
neighbor s cancels four t imes t he cent er value, leaving one t imes t he
cent er value remaining, and t he pixel t hus ret ains it s or iginal value.
If we want our sharpening lter to have a little larger radius, we need to
d ene a larger ker nel. The ker nel shown in Fig. 10 is t he shar pening
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 4
Figure 8. Smoot hed t est image.
Figure 9. Figur e 10. Figure 11.
Figure 12. Id eal t est image.
0 1 0
1 5 1
0 1 0
1 2 1
2 13 2
1 2 1
1 2 1
2 16 2
1 2 1
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 5
(a) Or iginal image, (b) processed ver sion.
Figur e 13.
count er par t of t he gaussian ker nel in Fig. 6. The cent er weight again is 1
minus t he sum of t he neighbor s weight s.
Somet imes, t he shar pening effect of t he previous t wo ker nels is a bit
t oo har sh, and may overemphasize some high-frequency noise in t he
image. In t hat case, we want t o mod er at e t he shar pening somewhat . This
can be d one by weight ing t he cent er pixel higher t han simply required t o
offset t he negat ive weight s, as shown in Fig. 11. This essent ially gives a
lit t le more weight t o t he cur rent pixel value ver sus t he value d er ived by
t he ed ge-shar pening comput at ion. None of t hese convolut ions can exact ly
recover t he id eal image (Fig. 12) from t he smoot hed image (Fig. 8), but
t hey go a long way t oward t hat goal.
Now, t est images are ne and can show quit e clear ly how t he var ious
convolut ions oper at e on ext reme cond it ions, but how well d oes t his wor k
in p r act ice? Figu res 13 and 14 show some r eal-wor ld examp les of
ed ge-shar pening convolut ions. In each case, t he (a) gure is t he or iginal
image and t he (b) gure is t he processed ver sion. Alt hough it may seem
like it , t he or iginal images are not out of focus.
The examples of convolu t ion ker nels shown here all hap p en t o be
3 3 mat r ices; however, t his by no means is required . Larger mat r ices
t ake propor t ionally longer t o convolve an image, and basically are ext en-
sions of t he pr inciples shown here. The pr imar y reason t o use a larger
II.1 IMAGE SMOOTHING AND SHARPENING BY DISCRETE CONVOLUTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 6
(a) Or iginal image, (b) processed ver sion.
Figure 14.
mat r ix is t o cause wid er effect s. Wit h a 3 3 mat r ix, pixels t wo or more
unit s away will have no effect on t he cur rent pixel.
There are a large number of useful ways t o apply d iscret e convolut ion
for image enhancement . I have t ou ched on only a few of t he basic
build ing blocks. Creat ive combinat ions of t hese t echniques, par t icular ly
cond it ional applicat ion of var ious lt er s, will great ly enr ich your image
p r ocessing cap acit y. Books by Gonzalez and Wint z (1987) and Pr at t
(1978) cont ain much more infor mat ion about d iscret e image lt er ing and
many ot her t opics. Also, bot h books go int o far great er d ept h explaining
t he mat hemat ics behind t hese oper at ions.
Se e a l s o ( 166) S moot hi n g En l arged Mon ochrome I mages,
John Olsen; (171) Median Finding on a 3 3 Grid, A lan
W. Paet h
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 7
l l .2 l l .2 l l .2 l l .2 l l .2
A AA AA COMPARISON OF DIGITAL COMPARISON OF DIGITAL COMPARISON OF DIGITAL COMPARISON OF DIGITAL COMPARISON OF DIGITAL
HALFTONING TECHNIQUES HALFTONING TECHNIQUES HALFTONING TECHNIQUES HALFTONING TECHNIQUES HALFTONING TECHNIQUES
Dale A. Schumacher
St Paul, Minnesot a
Digit al halft oning is a process t hat allows us t o t r ad e spat ial resolut ion
for gr ayscale resolut ion in an image. Typically, t his is used t o d isplay an
image wit h a large number of gr ayscale values on a d evice t hat suppor t s
signicant ly fewer d ist inct gr ayscale valu es. In many cases, su ch as
t ypical pr int ing d evices, t he d evice can represent only t he t wo levels,
black and whit e. On su ch d evices, we give t he illu sion of d iffer ing
gr ayscale values by prod ucing pat t er ns wit h t he values available. The
perceived gr ayscale value is propor t ional t o t he d ensit y of such pat t er ns
Many halft oning t echniqu es can be gener alized t o t hr eshold ing an
image wit h a pat t ern mask. This pat t er n mask is a mat r ix of t hreshold
values t hat d ene which of t wo ad jacent out put gr ayscale values will be
assigned t o a pixel based on t he posit ion and value of t hat pixel. Since t he
t hreshold ing mat r ix near ly always is much smaller t han t he image it self,
t he t hreshold ing values are t iled over t he image area. This is equivalent
t o saying t hat t he t hreshold ing value used for a given pixel is t aken from
t he t hreshold ing mat r ix by comput ing t he mod ulo of t he pixel locat ion
wit h t he size of t he mat r ix. The following pseud o-cod e shows how a
t hreshold ing mat r ix is applied t o an image t o creat e a black-and -whit e
halft one.
input : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
out put : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
t hreshold : array [1..mat r ix_wid t h] of array [1..mat r ix_height ] of pi xel ;
t : pi xel ;
i, j: i nteger;
t hreshold _d it her ; {dit her t o BLACK and WHITE}
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 8
begi n
for y: i nteger 1, y y + 1, y < = image_height do
j ((y 1) mod mat r ix_height ) + 1;
for x: i nteger 1, x x + 1, x < = image_wid t h do
i ((x 1) mod mat r ix_wid t h) + 1;
i f input [x][y] > t hreshold [i][j] then
out put [x][y] WHITE_PIXEL;
el se
out put [x][y] BLACK_PIXEL;
endl oop;
endl oop;
end;
For t his d iscussion, we will use oat ing point values in t he t hreshold ing
mat r ix, and we will assume t hat image d at a is in t he r ange [0.0, 1.0], wit h
black being 0.0 and whit e being 1.0. Many implement at ions will use t he
int eger r ange [0, 255] for processing efciency.
Thr eshol d Di t her i ng Thr eshol d Di t her i ng Thr eshol d Di t her i ng Thr eshol d Di t her i ng Thr eshol d Di t her i ng
We now can d ene halft ones by t heir t hreshold ing mat r ix. Let us st ar t
wit h a halft one so simple it usually is not even t hought of as a halft one
at allt he single element mat r ix [.44]. This halft oning mat r ix simply will
apply t he same t hreshold t o all pixels in t he image, result ing in an out put
image like Fig. 2. This is equivalent t o quant izing t he image t o t wo
levels, assigning each pixel t o t he nearest of t he t wo possible out put
values.
Now let us t ake a slight ly more complex mat r ix, as shown in Fig. 3b.
This is called a 2 2 ordered dit her. This mat r ix r esult s in ve d ist inct
gr ayscale pat t er ns, t hus ve apparent out put gr ayscale levels. As long as
all element s of a halft one mat r ix are d ifferent , t he number of apparent
gr ayscale levels creat ed is (N M) + 1, where N and M d ene t he size
of t he mat r ix.
A larger ver sion of t he ord ered d it her mat r ix is shown in Fig. 4b. Since
t his is a 4 4 mat r ix, it creat es 17 out put levels. The int ent of t he
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 5 9
Figure 1. Or iginal image. Figure 2. Single t hreshold .
ord ered d it her is t o fill t he mat r ix evenly, red ucing t he amount of aliasing
int rod uced by pat t er ns in t he halft one mat r ix. Ar bit r ar y sized ord ered
d it her ing mat r ices can be creat ed t hrough a simple recur sive algor it hm
(Hawley, 1990). The act ual t hreshold values are evenly spaced int er vals
bet ween 0.0 and 1.0. The mat r ix in Fig. 4c represent s t he ll order of
t he mat r ix in Fig. 4b. This is t he ord er in which pixels are set wit hin t he
.2 .6
.8 .4
(a) (b)
Figure 3. 2 2 ord ered d it her.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 0
(a)
.06 .53 .18 .65 1 9 3 11
.76 .30 .88 .41 13 5 15 7
.24 .71 .12 .59 4 12 2 10
.94 .47 .82 .35 16 8 14 6
(b) (c)
Figure 4. 4 4 ord ered d it her.
mat r ix as t he gr ayscale value of t he cor respond ing source pixel increases.
It oft en is useful, for analysis, t o separ at e t he ll ord er from t he act ual
t hreshold values, alt hough when t he algor it hm is implement ed , we most
oft en want t o combine t he t wo t o save processing t ime.
As seen from t he preced ing, t he pat t er ns creat ed by a halft one mat r ix
can be d ened simply by a ll ord er ind epend ent of t he t hreshold values.
Anot her halft one mat r ix, which shows t he effect s of st rong pat t er ns in t he
halft one mat r ix on t he result ant image, is given by t he ll-ord er mat r ix in
Fig. 5b. This mat r ix creat es st rong hor izont al lines in t he out put image.
On t he ot her end of t he spect rum, t he mat r ix in Fig. 6b t akes a d ifferent
ap p r oach t o mi n i mi zi n g t h e al i asi n g effect . Th i s i s a magic-square
d it her, since t he ll-ord er values for m a magic square. Since a magic
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 1
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
(a) (b)
Figure 5. 4 4 hor izont al lines.
1 7 10 16
12 14 3 5
8 2 15 9
13 11 6 4
(a)
Figur e 6. 4 4 magic square.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 2
(a)
30 19 13 20 31 35
18 8 5 9 21 29
12 4 1 2 10 28
17 7 3 6 14 27
26 16 11 15 22 32
34 25 24 23 33 36
(a) (b)
Figure 7. 6 6 90 halft one.
15 9 17 32 22 30
7 1 3 19 35 23
13 5 11 27 26 33
31 21 29 16 10 18
20 36 24 8 2 4
28 25 34 14 6 12
(a) (b)
Figure 8. 6 6 45 halft one.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 3
square sums t o equal values along all rows, columns, and d iagonals, t his
ll ord er should be id eal in lling t he pixels in such a way t hat t he number
of d ot s along any row, column, or d iagonal will be approximat ely equal.
On many out put d evices, smear ing, var iance in d ot size, blur r ing, and
ot her similar effect s make t he use of pat t er ns like t he preced ing impr act i-
cal, since t hose p at t er ns rely on being able t o image single p ixels
accu r at ely and consist ent ly. On d evices where su ch p recision is not
pr act ical, a clust ered-dot d it her may be more appropr iat e. Clust ered -d ot
d it her s cr eat e p at t er ns ver y similar t o t hose creat ed by t he op t ical
halft oning process used t o pr int phot ogr aphs in books, magazines, and
newspaper s.
Figures 7b and 8b give t wo examples of such a halft one mat r ix. In
phot ogr aphic halft oning, t hese pat t er ns are creat ed by a screen consist ing
of small t r ansparent d ot s on an opaque eld . The spacing of t hese d ot s,
d escr ibed in lines (of d ot s) per inch, and t he angle along which t hese lines
run d enes by t he par amet er s of t he screen. The mat r ix in Fig. 7b act s
like a 90-d egree screen, wit h t he lines per inch propor t ional t o t he pixels
per inch in t he source image. The mat r ix in Fig. 8b act s like t he more
commonly used 45-d egree screen.
Cont r ast Adj ust ment dur i ng Hal f t oni ng Cont r ast Adj ust ment dur i ng Hal f t oni ng Cont r ast Adj ust ment dur i ng Hal f t oni ng Cont r ast Adj ust ment dur i ng Hal f t oni ng Cont r ast Adj ust ment dur i ng Hal f t oni ng
The perceived br ight ness of var ious halft one pat t er ns d iffer s, even at t he
same d ot d ensit y. Also, all halft oning seems t o red uce cont r ast . Due t o
t hese effect s, it oft en is d esir able t o ap p ly a cont r ast enhancement
t r ansfor m t o an image while halft oning. Going back t o t he separ at ion
bet ween t hreshold levels and ll ord er, we nd t he means t o accomplish
t he cont r ast ad just ment essent ially for free while halft oning. The key is
t o incor por at e t he t r ansfor m int o t he t hreshold levels. Figure 9b shows
t he nor mal case, a linear t r ansfor m, wit h four t hreshold ing levels, as
would be required by a 2 2 mat r ix. Figure 9d shows t he same four
t hreshold levels as d er ived from a cont r ast -enhancement t r ansfor m cur ve.
Not e t hat t he t hreshold levels are nonlinear ly spaced t o make t he t r ans-
for med out put levels linear.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 4
(a) (b)
(c) (d )
Figure 9. (a) 2 2 linear d it her, (b) linear t r ansfor m (c) 2 2 cont r ast -enhanced d it her,
(d ) cont r ast enhancement t r ansfor m.
Hal f t oni ng t o Mul t i pl e Out put Level s Hal f t oni ng t o Mul t i pl e Out put Level s Hal f t oni ng t o Mul t i pl e Out put Level s Hal f t oni ng t o Mul t i pl e Out put Level s Hal f t oni ng t o Mul t i pl e Out put Level s
Thus far, we have assumed t hat t he out put of our halft oning process was
st r ict ly black or whit e, which is t rue for a large number of out put d evices.
However, t here is consid er able usefulness in halft oning t o mult iple out put
levels. Ext end ing t he var ious t hreshold met hod s t o mult iple out put levels
consist s of r st picking t he nearest pair of out put values for a given input ,
t hen using t he t hreshold mat r ix t o d et er mine which of t he t wo out put
(a)
(c)
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 5
values t o use, consid er ing t he r ange [lower _value, higher _value] t o map t o
t he nor malized [0.0, 1.0] in t he t hreshold mat r ix. The following pseud o-
cod e gives t he gener al algor it hm for applying t hreshold d it her ing t o
mult iple out put levels.
input : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
out put : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
t hreshold : array [1..mat r ix_wid t h] of array [1..mat r ix_height ] of pi xel ;
r ange: pi xel ; dist ance bet ween out put levels
base: pi xel ; lower end of t arget range
i, j; i nteger;
t hreshold _d it her (n: i nteger); dit her t o n out put levels
begi n
n n 1 convert number of levels t o number
of ranges
r ange (1.0/ n);
for y: i nteger 1, y y + 1, y < = image_height do
j ((y 1) mod mat r ix_height ) + 1;
for x: i nteger 1, x x + 1, x < = image_wid t h do
i ((x 1) mod mat r ix_wid t h) + 1;
base oor (input [x][y]/ r ange) r ange;
i f (input [x][y] base) > (t hreshold [i][j] r ange) then
out put [x][y] base + r ange;
el se
out put [x][y] base;
endl oop;
endl oop;
end;
Er r or Di f f usi on Di t her i ng Er r or Di f f usi on Di t her i ng Er r or Di f f usi on Di t her i ng Er r or Di f f usi on Di t her i ng Er r or Di f f usi on Di t her i ng
An ent irely d ifferent approach t o halft oning is a group of algor it hms
known as error diffusion met hod s. Since d it her ing must approximat e a
d esired out put level by creat ing pat t er ns wit h t he available out put levels,
t here is a cer t ain quant iable er ror in t he approximat ion at a given pixel.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 6
Er ror d iffusion car r ies t hat er ror over t o bias t he values of near by pixels
t o balance out t he er ror. This spread s t he er ror out over a small area,
creat ing a d iffusion effect . The spread of t he er ror is cont rolled by a
weight ing mat r ix such t hat a fr act ion of t he er ror is applied t o some
number of near by pixels. Since t he image is processed in t he nor mal
left -t o-r ight and t op-t o-bot t om ord er, and pixel values are not changed
once assigned , t he weight ing mat r ix can d ist r ibut e t he er ror only t o
unassigned out put locat ions. The following pseud o-cod e illust r at es t he
gener al algor it hm. The special-case processing required t o hand le ed ges
proper ly is omit t ed here for simplicit y.
input : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
out put : array [1..image_wid t h] of array [1..image_height ] of pi xel ;
weight : array [lt er _d x.. + lt er _d x] of
array [lt er _d y.. + lt er _d y] of i nteger;
sum: i nteger; sum of values in weight ing lt er
value: pi xel ; value chosen for a pixel
er ror : pi xel ; quant izat ion error for a pixel
r ange: pi xel ; dist ance bet ween out put levels
base: pi xel ; lower end of t arget range
d iffusion_d it her (n: i nteger); d it her t o n out put levels
begi n
n n 1 convert number of levels t o number
of ranges
r ange (1.0/ n);
sum 0;
for j: i nteger lt er _d y, j j + 1, j < = +lt er _d y do
for i: i nteger lt er _d x, i i + 1, i < = +lt er _d x do
sum sum + weight [i][j];
endl oop;
endl oop;
for y: i nteger 1, y y + 1, y < = image_height do
for x: i nteger 1, x x + 1, x < = image_wid t h do
d it her _pixel(x, y);
endl oop;
endl oop;
end;
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 7
d it her _pixel (x: i nteger, y: i nteger); det ermine pixel values, spread error
begi n
i f (input [x][y] < 0.0) then
value 0.0;
el se i f (input [x][y] > 1.0) then
value 1.0;
el se begi n
base oor (input [x][y]/ r ange) r ange;
i f (input [x][y] base) > (0.5 r ange) then
value base + r ange;
el se
value base;
end;
out put [x][y] value;
er ror input [x][y] value;
for j: i nteger lt er _d y, j j + 1, j < = +lt er _d y do
for i: i nteger lt er _d x, i i + 1, i < = +lt er _d x do
i f weight [i][j] 0 then
input [x + i][y + j] input [x + i][y + j]
+ (er ror weight [i][j]/ sum);
endl oop;
endl oop;
end;
The classic weight ing mat r ix is shown in Fig. 10b (Floyd and St einberg,
1975). Ot her useful lt er s are shown in Figs. 11b (Jar vis et al. 1976) and
12b (St ucki, 1981).
Ulichney (1987) present s an excellent analysis of t he halft oning pro-
cess and su ggest s sever al imp rovement s t o t he p reced ing algor it hm.
Fir st , some und esir able aliasing effect s are prod uced by t he r ast er scan-
ning pat t er n inherent in t his d it her ing process. One way t o red uce t his
effect is t o t r aver se t he image wit h a serpent ine r ast er pat t er n. St ar t
scanning left t o r ight on t he r st scanline, as usual, t hen rever se t he
scanning d irect ion and t r aver se t he next scanline r ight t o left . Cont inue
alt er nat ing scanning d irect ions on each scanline. Remember t hat t he
weight ing mat r ix also will need t o be left / r ight -rever sed . Figures 13 and
14 cont r ast nor mal r ast er and ser pent ine r ast er scanning met hod s.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 8
0 0 0
0 0 7
3 5 1
(a) (b)
Figure 10. Floyd -St einber g filt er.
0 0 0 0 0
0 0 0 0 0
0 0 0 7 5
3 5 7 5 3
1 3 5 3 1
(a) (b)
Figure 11. Jar vis, Jud ice, and Ninke lt er .
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 6 9
0 0 0 0 0
0 0 0 0 0
0 0 0 8 4
2 4 8 4 2
1 2 4 2 1
(a) (b)
Figur e 12. St ucki lt er.
A useful suggest ion from Ulichney is t o int rod uce some r and om noise
in t he d it her ing process. This noise, which should have unifor m probabil-
it y d ensit y (whit e noise), can be ad d ed in any of sever al st ages of t he
d it her ing process, and t he amount of noise can be ad just ed for best effect .
Fir st , t he t hreshold value (a const ant 0.5 in t he pseud o-cod e example)
can be r and omly ad ju st ed u p or d own. Second , t he p osit ion of t he
d iffusion weight can be chosen r and omly using t he lt er weight s t o bias
Figure 13. Nor mal r ast er. Figure 14. Ser pent ine r ast er.
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 0
Figure 15. Blue noise ad d ed .
t he select ion of a posit ion for a single er ror d iffusion weight . Finally, t he
weight s t hemselves can be alt ered r and omly. If noise is ad d ed t o t he
weight values, it must be account ed for eit her by ad just ing t he lt er sum,
t o ensure unit y gain, or by ad just ing t wo weight s, wit h t he same init ial
values, in equal and opposit e d irect ions. Var iat ion of t he t hreshold value
combined wit h var iat ion in weight s was used t o prod uce Fig. 15.
One nal improvement t o t he d it her ing process is t o account for it s
inherent d isper sion. Since we are t r ad ing spat ial resolut ion for gr ayscale
resolut ion, it is nat ur al t hat we will lose some of t he high spat ial fre-
Figure 16. Ed ge-enhanced .
II.2 A COMPARISON OF DIGITAL HALFTONING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 1
quency component s of t he source image. It only makes sense t hat we
could compensat e somewhat by emphasizing such component s before
halft oning. Figure 16 was creat ed using t he same met hod as in Fig. 15,
except t hat t he source image had an ed ge-shar pening convolut ion applied
before halft oning. This sor t of processing is d iscussed fur t her in t he
preced ing gem in t his book.
Concl usi on Concl usi on Concl usi on Concl usi on Concl usi on
Proper use of d igit al halft oning met hod s can result in excellent reprod uc-
t ion of images wit h much higher gr ayscale resolut ion t han t hat available
on a par t icular d isplay d evice. This gem is meant t o give a pr act ical
int rod uct ion and compar at ive guid e t o some of t he halft oning met hod s in
use t od ay. Ulichneys book (1987) is an excellent next st ep for t hose
int er est ed in fu r t her comp ar at ive analysis and d iscu ssion of d igit al
halft oning t echniques.
See also II.1 Image Smoot hing and Shar p ening by Discr et e
Convolut ion, Dale A. Schumacher ; II.3 Color Dit her ing, Spencer
W. Thomas, Rod ney G. Bogar t ; III.1 Efcient Inver se Color map
Comput at ion, Spencer W. Thomas; III.2 Efcient St at ist ic Com-
put at ions for Opt imal Color Quant izat ion, Xiaolin Wu; (176)
Ordered Dit hering, St ephen Hawley ; (196) Useful 1-t o-1
Pixel Transforms, Dale A. Schumacher.
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 2
II.3 II.3 II.3 II.3 II.3
C CC CCOLOR DITHERING OLOR DITHERING OLOR DITHERING OLOR DITHERING OLOR DITHERING
Spencer W. Thomas, Rod G. Bogart
Universit y of Michigan
Ann Arbor, Michigan
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Alt hough sever al sources d iscuss d it her ing t o a binar y image (Ulichney,
1988; Hawley, 1990), t here appar ent ly is no wid ely available lit er at ure on
d it her ing t o a mu lt ilevel color image. This gem d iscu sses t wo color
d it her ing t echniques, a simple ord ered d it her and an er ror-propagat ion
d it her based on t he Floyd -St einberg met hod (Floyd and St einberg, 1975).
Convent i ons Convent i ons Convent i ons Convent i ons Convent i ons
Throughout t his d iscussion, we will assume t hat color values are in t he
r ange 0.01.0, u nless it is st at ed exp licit ly ot her wise. Mat hemat ical
expressions oper at ing on color s will be wr it t en wit h scalar var iables;
however, you can assume t hat t he oper at ion should be applied separ at ely
and simult aneously t o t he red , gr een, and blue component s of t he color.
Gamma Cor r ect i on Gamma Cor r ect i on Gamma Cor r ect i on Gamma Cor r ect i on Gamma Cor r ect i on
To get t he proper visual effect , t he d it her ing process assumes t hat t he
input and out put values are linear in t he image br ight ness; i.e., a number
t wice as large as anot her prod uces a pixel t wice as br ight . This is almost
never t rue for d isplay d evices, and may not be t rue of input les. Thus,
bot h t h e i n p u t a n d ou t p u t va l u es mu st be gamma-correct ed
(Schu macher, 1990; Hall, 1990; Foley et al., 1990) for op t imal visu al
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 3
per for mance. Input gamma cor rect ion maps t he input values t o a linear
scale. Out put gamma cor rect ion affect s t he values t hat are load ed int o t he
out put color t able, but has no effect on t he d it her ing process or t he
result ing pixel values.
If t he input image has a gamma of
i
, t hen each input pixel value x (in
t he r ange 01) must be mapped by t he funct ion f(x) = x
1/
i
. Similar ly,
t o d isplay an image on a d isplay wit h a gamma of
d
, each value c must
be map p ed t o t he act u al ou t p u t valu e by g(c) = c
1/
d
. However, for
er ror-propagat ion d it her ing, t he uncompensat ed out put value must be
used t o comput e t he er ror. The d iscussions t hat follow will assume t hat
any gamma cor rect ion necessar y has been d one, and t herefore, will
oper at e solely in t he linear d omain.
Or der ed Di t her i ng Or der ed Di t her i ng Or der ed Di t her i ng Or der ed Di t her i ng Or der ed Di t her i ng
The simplest for m of d it her ing is ordered dit hering. In t he bilevel case,
a funct ion d(x, y) is used t o d et er mine whet her t he out put value v is a 0
or a 1 by compar ing it wit h t he pixel value c:

v =
1 c > d(x, y),
0 c d(x, y).

'

Usually, t he funct ion d(x, y) is implement ed using an m n mat r ix:


d(x, y) = M[y mod m][x mod n].
Dit her ing t o a mult ilevel d isplay is only slight ly more complex. If t he
out put will have l + 1 d ist inct levels (i.e., t he out put r ange is 0..l), t hen
t he d it her ing funct ion is

v = floor(l c) +
1, frac(l c) > d(x, y),
0, frac(l c) d(x, y).

'

If c is an int eger in t he r an ge 0..cmax, t h en , let t in g k = cmax/ l,


t h e oor a n d fr a c fu n ct i on s ca n be r ep l a ced by oor ( c/ k) a n d
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 4
c oor (k oor (c/ k)). The funct ion d(x, y) should prod uce an int eger
in t he r ange 0..(k 1).
1
What should d(x, y) look like? It will be implement ed as a mat r ix, as
suggest ed previously. Hawley (1990) suggest s one way t o build such a
mat r ix.
The cod e includ ed here uses a slight ly d ifferent met hod . It always
comput es a 16 16 mat r ix. Wit h 256 ent r ies in t he mat r ix, it would be
possible t o get 257 out put levels, cer t ainly sufcient for any (8-bit ) input
image, even if t he out put image is bilevel. The mat r ix is a magic square
const r uct ed as t he out er product of a 4 4 magic square wit h it self. The
ent r ies in t he square are scaled int o t he r ange 0..k (cmax = 255 in t he C
Implement at ion).
The C cod e (Ap p end ix 2) assu mes t hat t he inp u t valu es are 8-bit
unsigned int eger s. For efciency, t o avoid repeat ed ly using t he divide
and mod oper at or s, ar r ays of 256 ent r ies are built , such t hat divN[c] =
oor(c/ k) an d modN[c] = c oor(k divN[c]). We t h en can wr i t e
t he d it her ing funct ion as a macro:
macro d it her (x, y, c)
(d ivN[c] + (i f mod N[c] > M[y bi t-and 15][x bi t-and 15]
then 1
el se 0))
The only remaining t ask is d ecid ing what t he out put color set should be.
It is easiest t o d it her wit h t he same number of levels of each pr imar y
color, and t he result ing image will look bet t er t han if d iffer ing number s of
levels were used for t he d ifferent pr imar ies.
2
If 256 ent r ies are available
in t he color t able of t he out put d evice, set t ing l = 5 (k = 51) prod uces
1
The ast ut e read er will not e t hat , if d(x, y) = (k 1), 1 never will be ad d ed at t he
pixel (x, y). This is cor rect . Suppose k = 128. Then if c = 127, t he out put value will be
1, except when d(x, y) = 127. If d(x, y) is unifor mly d ist r ibut ed , 127 out of 128 pixels
will be 1, and t he 128t h will be 0, giving an aver age out put value of 127/ 128, exact ly
what is d esired . To get all t he pixels t o have a value of 1, c should be 128.
2
I have t r ied t he vaunt ed 3-3-2 allocat ion of bit s (3 t o red , 3 t o gr een, and 2 t o blue).
The assumpt ion behind t his is t hat t he eye is less sensit ive t o blue, so not as many levels
of blue are needed. However, the eye is quite sensitive to color variation in something that
should be gray, and that is what you get with this setup. There are eight levels of red and
green {0,1/ 7,2/ 7,3/ 7,4/ 7,5/ 7,6/ 7,1}, and fou r levels of blu e {0,1/ 3,2/ 3,1}. These
set s coincid e only at whit e and black.
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 5
six out put levels per pr imar y and uses 216 ent r ies in t he color t able.
3
The
40 left over can be u sed for ot her p u r p oses (somet imes a d enit e
ad vant age). If we can assign t he value (r k, g k, b k) (wit h r, g, b in
t he r ange 0..5) t o t he cell 36 r + 6 g + b, t he mapping from d it hered
color t o color t able ind ex is t r ivial. If t his is not possible (for example, if
t he color t able belongs t o an X ser ver ), t hen an int er med iat e mapping
t able, T[0..5][0..5][0..5], must be built , such t hat T[r][g][b] cont ains t he
appropr iat e color t able ind ex.
A sample image d it hered wit h ord ered d it her is shown in Fig. 1 (see
color inser t ).
Er r or - Pr opagat i on Di t her i ng Er r or - Pr opagat i on Di t her i ng Er r or - Pr opagat i on Di t her i ng Er r or - Pr opagat i on Di t her i ng Er r or - Pr opagat i on Di t her i ng
The main d r awback wit h ord ered d it her can be seen from t he aforemen-
t ioned example. The d it her pat t er n is quit e evid ent in t he result . Error-
propagat ion dit hering t ech n i qu es r ed u ce t h e ap p ar en t p at t er n i n g by
making t he d ot placement appear more r and om. The basic id ea is t his: At
each pixel, choose t he best out put color for t he given input color. Then
comput e t he er ror (d ifference) bet ween t he chosen out put color and t he
input color. Spread t he er ror out near by pixels t hat have not yet been
out put . A number schemes exist for d ist r ibut ing t he er ror. The Floyd -
St einberg met hod gives 7/ 16 t o t he next pixel t o t he r ight (assuming
scanning from left t o r ight along a scanline), 3/ 16 t o t he previous pixel
on t he next scanline, 5/ 16 t o t he ad jacent pixel on t he next scanline, and
1/ 16 t o t he next pixel on t he next scanline. (See Fig. 2.) Not e t hat t he
er ror propagat ion can result in color values t hat are out of t heir allowed
r ange, so t he cod e must be careful t o clamp t he values before t r ying t o
comput e an out put color.
An ad vant age of er ror-propagat ion d it her over ord ered d it her is t hat it
can use an ar bit r ar y color t able. The problem of choosing an out put
color, given an ar bit r ar y RGB color, is solved easily by using an inver se
color map, as d escr ibed in t he r st gem of Par t III in t his book, Efcient
Compu t at ion of Inver se Color maps. Not e t hat t he inver se color map
should be comput ed before any out put gamma compensat ion is applied
t o t he color t able, and t he er ror values also should be comput ed from t he
uncompensat ed t able. The best result s will be obt ained if t he input color s
3
The C Implement at ion in Append ix 2 allows any value of l 1.
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 6
Figure 2. Floyd -St einberg er ror propagat ion. Direct ion of processing is left t o
r ight , bot t om t o t op.
lie wit hin t he convex hull of t he color t able. Ot her wise, some er ror could
be lost when out -of-r ange values are clamped .
Type color is equivalent t o array[1..3] of real
f uncti on fsd it her (t hisrow, next row:array[0..511] of col or;
x:i nteger):i nteger;
begi n
Current ent ry may have accumulat ed error; clamp it .
f or c 1 to 3 do
t hisrow[x][c] clamp(t hisrow[x][c], 0, 1);
Find closest represent at ive color, get it s index.
color _ind ex closest _color (t hisrow[i]);
Propagat e t he error.
color_map is a global array of t he out put colors.
f or c 1 to 3 do
begi n
er r t hisrow[ind ex][c] color _map[color _ind ex][c];
i f x < 511 then
begi n
t hisrow[x + 1][c] t hisrow[x + 1][c] + 7*er r / 16;
next row[x + 1][c] next row[x + 1][c] + er r / 16;
end;
next row[x][c] next row[x][c] + 5*er r / 16;
i f x > 0 then
next row[x 1][c] next row[x 1][c] + 3*er r / 16;
II.3 COLOR DITHERING
GRAPHICS GEMS II Edit ed by JAMES ARVO 7 7
end;
return color _ind ex;
end;
A complet e C Implement at ion of t his algor it hm includ ing opt ional ed ge
enhancement , is includ ed in t he freely d ist r ibut ed Ut ah Rast er Toolkit .
(Cont act one of t he aut hor s of t his gem for d et ails.)
Figure 3 (see color inser t ) shows an example of t he applicat ion of t his
d it her algor it hm.
See also II.2 A Compar ison of Digit al Halft oning Techniques,
Dale A. Schumacher ; III.1 Efcient Inver se Color map Comput a-
t ion, Spencer W. Thomas; III.2 Efcient St at ist ic Comput at ions
for Op t imal Color Qu ant izat ion, Xiaolin Wu ; (176) Ordered
Dit hering, St ephen Hawley
Figure 1. A multilevel image dithered with ordered
dither.
Figure 3. A sample image dithered to the ordered
dither colormap, using multilevel error-propagation
dither
7 8
II.4 FAST ANAMORPHIC IMAGE SCALING
GRAPHICS GEMS II Edit ed by DAVID KIRK 7 8
II.4 II.4 II.4 II.4 II.4
F FF FFAST ANAMORPHIC AST ANAMORPHIC AST ANAMORPHIC AST ANAMORPHIC AST ANAMORPHIC
I II IIMAGE SCALING MAGE SCALING MAGE SCALING MAGE SCALING MAGE SCALING
Dale A. Schumacher
St Paul, Minnesot a
There are many ways t o rescale an image t o t he d esired size. Some are
consid er ably more accur at e t han ot her s, and t he more accur at e met hod s
gener ally are more comput at ionally int ensive. The met hod I will present
is not par t icular ly accur at e, but it can be accomplished quit e quickly and
prod uces gener ally accept able result s. Bet t er, but slower, met hod s exist
involving lt er ing and are signicant ly more complicat ed .
Pixel r emap p ing op er at ions like st ret ching, r ot at ion, skewing, and
rescaling ar e oft en t hought of, and t hus oft en implement ed , as mappings
from posit ions in t he source image t o posit ions in t he d est inat ion image.
This approach, however, oft en leaves holes in t he d est inat ion d ue t o
round ing er ror in t he comput at ion of t he d est inat ion posit ion or t he fact
t hat t here is not a one-t o-one mapping bet ween source pixels and d est ina-
t ion pixels.
Taking a d ifferent approach t o t he problem can eliminat e t hese er ror s.
Think of t he remap p ing as d ening which sou rce p ixel a p ar t icu lar
d est inat ion pixel is t aken from. This maps posit ions in t he d est inat ion
from p osit ions in t he sou r ce. The p r ocessing loop t hen is over t he
d est inat ion pixels r at her t han t he source pixels, and t hus, each pixel in
t he d est inat ion is assigned a value, even if more t han one d est inat ion
pixel maps from t he same source pixel. This met hod may skip some of
t he source pixels, not using t heir value at all, but in t he previous met hod ,
t hat would cor respond t o more t han one source pixel mapping t o t he
same d est inat ion, which poses t he problem of how t o choose which
source pixels set t he value of t he d est inat ion. This met hod avoid s t hat
conict by choosing only one source pixel, always t he most cor rect for a
given mapping.
7 9
II.4 FAST ANAMORPHIC IMAGE SCALING
GRAPHICS GEMS II Edit ed by DAVID KIRK 7 9
Applying his me hod o image rescaling, we loop over he d es ina ion
pixels, d e er mining a each loca ion which source pixel lend s i s value o
t hat d est inat ion pixel. This allows anamor phic scaling, since t he hor izon-
t al and ver t ical mappings need not be t he same. This allows bot h expan-
sion of an image, where mult iple d est inat ion pixels are mapped from t he
same sou rce pixel, and red u ct ion of an image, where some ad jacent
d est inat ion pixels are mapped from nonad jacent sou r ce pixels. These
expansion and red uct ion met hod s oft en are refer red t o as pixel replica-
t ion and pixel sub-sampling, respect ively.
In t he following pseud o-cod e, t he scaling is convenient ly d ened in
t er ms of t he d esired d est inat ion image size.
src_x_size: i nteger; source image widt h
src_y_size: i nteger; source image height
source: array [0..src_x_size-1] of array [0..src_y_size-1] of pi xel ;
d st _x_size: i nteger; dest inat ion image widt h
d st _y_size: i nteger; dest inat ion image height
d est inat ion: array [0..d st _x_size-1] of array [0..d st _y_size-1] of pi xel ;
sx, sy, d x, d y: i nteger; source and dest inat ion
coordinat es
begi n
d y 0;
whi l e d y < d st _y_size do
sy ((d y*src_y_size)/ d st _y_size);
d x 0;
whi l e d x < d st _x_size do
sx ((d x*sr c_x_size)/ d st _x_size);
d est inat ion[d x][d y] source[sx][sy];
d x d x + 1;
endl oop:
d y d y + 1;
endl oop;
end;
8 0
II.5 REAL PIXELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 0
II.5 II.5 II.5 II.5 II.5
REAL PIXELS REAL PIXELS REAL PIXELS REAL PIXELS REAL PIXELS
Greg Ward
Lawrence Berkeley Laborat ory
Berkeley, Calif ornia
Many progr ams use oat ing point color represent at ions int er nally, only t o
conver t t o 24-bit int eger values when wr it ing t he result s t o a le. This
saves d isk sp ace, bu t at t he exp ense of accu r acy and t he abilit y t o
read ju st t he exposu re or per for m ot her op er at ions t hat requ ire wid e
d ynamic r ange. Fur t her more, if a linear mapping is u sed , 24 bit s is
inad equat e for high-qualit y out put and causes visible quant izat ion con-
t our s in t he d ar ker regions of a pr int or slid e.
An imp r oved linear map p ing from r eal color sp ace t o byt es u ses
r and om round ing as a for m of pred it her ing:
Convert a primary using random rounding:
i f r val > = 1.0
then ival 255;
el se ival 255*r val + r and om( );
This met hod was suggest ed by Rob Cook sever al year s ago, alt hough it
may have been oat ing around for some t ime.
It is bet t er st ill t o st ore gamma-cor rect ed byt es r at her t han linear ones,
since t his will give t he pixels great er d ynamic r ange wit hout sacr icing
accur acy. Here is a simple t able look-up rout ine for accomplishing t his
t r ansfor mat ion:
Init ialize of gamma t able:
gamt ab: array [0..1023] of byte;
8 1
II.5 REAL PIXELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 1
for i: i nteger 0 to 1023, i i + 1 do
gamt ab[i] 256.0*((i + .5)/ 1024) (1.0/ gamma);
To convert each pixel primary:
i f r val > = 1.0
then ival 255;
el se ival gamt ab[oor (1024.*r val)];
It is impor t ant t o use a large enough t able t hat accur acy will not be
compromised for smaller values. An alt er nat ive met hod is t o rever se t he
look-up and use a 256-ent r y t able of oat ing point values wit h a binar y
search rout ine t o nd t he closest value, but t his approach t akes consid er-
ably longer and probably is not wor t h t he small improvement in accur acy.
The ult imat e solut ion t o t he problem of accur at e pixel st or age is t o use
a oat ing point pixel for mat , which is t he real subject of t his gem. The
simplest approach is t o st ore a shor t oat for each of t he t hree pr imar ies
at each pixel. On most machines, t his t r anslat es t o 96 unport able bit s
per pixel. Many people have used t his for mat , but nobod y is br agging
about it .
For t unat ely, t here is a bet t er oat ing point for mat t hat only requires 32
bit s per pixel and is complet ely por t able bet ween machine archit ect ures.
The id ea is simple: Use an 8-bit mant issa for each pr imar y and follow it
wit h a single 8-bit exponent . In most oat ing point for mat s, t he mant issa
is nor malized t o lie bet ween .5 and 1. Since t his for mat uses t he same
exponent for t hree mant issas, only t he largest value is guar ant eed t his
nor malizat ion, and t he ot her t wo may be less t han .5.
For example, t he color
[.3 .02 .1]
would be conver t ed t o
[.6 .04 .2]*2
l
,
or, in 32-bit oat ing point for mat ,
[153 10 51 127].
Not ice t hat t he exponent value 1 t r anslat ed t o 127. It is necessar y t o
ad d an offset t o t he unsigned value t o get a signed exponent . In t his case,
we have chosen t o ad d 128, giving our color s a more or less even r ange
8 2
II.5 REAL PIXELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 2
bet ween values great er t han 1 and less t han 1. Select ing a smaller offset
would favor larger values, and a larger offset would favor smaller values,
but since 2
127
is about 10
38
, it hard ly seems wor t h t he wor r y.
It appear s t hat t his for mat favor s t he largest pr imar y value at t he
expense of accur acy in t he ot her t wo pr imar ies. This is t rue, but it also is
t rue t hat t he largest value d ominat es t he d isplayed pixel color so t hat t he
ot her p r imar ies become less not iceable. The 32-bit real p ixel for mat
present ed here preser ves t he bit s t hat are most significant , which is t he
gener al goal of any float ing point for mat .
Conver sion t o and from t his for mat relies heavily on t he mat h rout ines
frex p a n d ldex p. Frex p t a kes a r ea l va l u e a n d r et u r n s a ma n t i ssa
bet ween .5 and 1 and an int eger exponent . Ldexp per for ms t he rever se
oper at ion, mult iplying a real value by t wo t o t he power of an int eger
exponent .
1
Thus, conver t ing from t he int er nal oat ing point color repre-
sent at ion involves picking t he largest pr imar y value, t hen calling frexp.
To convert from machine oat t o 32-bit real pixel:
r f, gf, bf: real ; machine red, green and blue values
r m, gm, bm, ex: i nteger; red, green, and blue mant issas + exponent
r f max(r f,max(gf,bf));
i f v < 1e-32
then begi n
r m 0;
gm 0;
bm 0;
ex 0;
end;
el se begi n
v frexp(v, e)*256./ v; e is ret urned exponent
r m r f*v;
gm gf*v;
bm bf*v;
ex e + 128;
end;
1
Ideally, these functions would be implemented as bit operations specic to the oating
point archit ect ure, but t hey are wr it t en more t ypically as por t able C rout ines.
8 3
II.5 REAL PIXELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 3
Not e t hat t here is a special case for zero. This case also is t est ed in t he
conver sion back t o machine oat ing point wit h ldexp, as follows:
To convert from 32-bit real pixel t o machine oat :
i f ex = 0
then begi n
r f 0.;
gf 0.;
bf 0.;
end;
el se begi n
v ld exp(1./ 256., ex-128);
r f (r m + .5)*v;
gf (gm + .5)*v;
bf (bm + .5)*v;
end;
Besid es t he abilit y t o per for m more gener al image processing wit hout
losing accur acy, real pixels are great for r ad iosit y and ot her light ing
simulat ion progr ams, since t he result s can be evaluat ed numer ically well
out sid e t he d ynamic r ange of t he d isplay. For example, an ofce space
wit h a wind ow may have r ad iosit ies t hat var y over a r ange of 1000 : 1. It
is impossible t o st ore such values using an int eger pixel for mat , but when
t he p ixels ar e real, t he image can be analyzed in many ways. The
exposure can be r aised and lowered d ynamically, t he br ight nesses can be
compressed , cont our lines can be d r awn, and values can be d isplayed as
number s over t heir posit ions on t he screen. These capabilit ies can be of
immense help t o light ing d esigner s and archit ect s t r ying t o evaluat e a
simulat ed scene for visual comfor t , and t hey are impossible wit h any of
t he st and ard image st or age for mat s.
In t he end , one ext r a byt e per pixel is not t hat much t o pay for t he
benet s associat ed wit h t ru e oat ing p oint color. Also, convent ional
compression t echniqu es su ch as r u n-lengt h encod ing and Lempel-Ziv
wor k ver y well wit h t his 4-byt e for mat much bet t er t han machine oat
values, which t end t o look like r and om bit s. Thus, t he image les t ake up
only a lit t le more space t han t heir 24-bit count er par t s.
8 4
II.6 A FAST 90-DEGREE BITMAP ROTATOR
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 4
II.6 II.6 II.6 II.6 II.6
A FAST 90- A FAST 90- A FAST 90- A FAST 90- A FAST 90-DEGREE BITMAP DEGREE BITMAP DEGREE BITMAP DEGREE BITMAP DEGREE BITMAP
ROTATOR ROTATOR ROTATOR ROTATOR ROTATOR
Sue-Ken Yap
CSIRO DIT
Canberra, Aust ralia
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
This is a rout ine t hat rot at es an 8 8 d ept h 1-bit map clockwise by t able
look-up. Larger bit maps can be rot at ed by d ivision d own t o 8 8 t iles.
Separ at e st r id es (ad d ress d ifference bet ween successive rows in bit maps)
can be specied for source and d est inat ion so t hat t he result can be
wr it t en d irect ly int o t he d est inat ion bit map.
Pr i nci pl e Pr i nci pl e Pr i nci pl e Pr i nci pl e Pr i nci pl e
The source t ile is viewed as eight rows of byt es. Each byt e maps ont o
cer t ain bit s in t he d est inat ion t ile viewed as a 64-bit longword whose bit s
run row-wise. Eight t able look-up and bit -or oper at ions const r uct t his
longword . Finally, t he longword is unpacked int o 8 byt es at t he d est ina-
t ion.
The act ual algor it hm is mod ied slight ly t o wor k wit h nybbles and t o
prod uce t wo 32-bit word s inst ead of one 64-bit longword . This red uces
t he size of each of t he eight look-up t ables from 256 64 bit s t o 16 32
bit s.
Var i at i ons Var i at i ons Var i at i ons Var i at i ons Var i at i ons
Eit her t r ansposit ion or rot at ion is possible, since t he rot at or allows an
ar bit r ar y swizzle of it s input bit s. For example, a d ifferent look-up t able
8 5
II.6 A FAST 90-DEGREE BITMAP ROTATOR
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 5
can rot at e count erclockwise. Bit map complement at ion can be d one si-
mult aneously by complement ing t he t ables, changing t he init ial cond it ion
of t he longword t o all ones, and using bit -and oper at ions in t he ext r ac-
t ion. This follows from d e Morgans t heorem. This is impor t ant as t he
0 = black, 1 = whit e convent ions of d igit al phot omet r y oft en are violat ed
by xerogr aphic pr int er s, which regard 1 mar k black.
Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s
The id ea for t his gem was su ggest ed by Alan Paet h (Univer sit y of
Wat er loo) and implement ed by t he aut hor while at t he Univer sit y of
Rochest er. The rot at or was used r st in a TeX DVI t o r ast er conver t er
d escr ibed in TUGboat 11(2).
See also II.7 Rot at ion of Run-Lengt h Encod ed Image Dat a, Jeff
Hol t , (179) A Fast A lgorit hm for General Rast er Rot at ion,
Alan W. Paet h
8 6
II.7 ROTATION OF RUN-LENGTH ENCODED IMAGE DATA
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 6
II.7 II.7 II.7 II.7 II.7
ROTATION OF RUN-LENGTH ROTATION OF RUN-LENGTH ROTATION OF RUN-LENGTH ROTATION OF RUN-LENGTH ROTATION OF RUN-LENGTH
ENCODED IMAGE DATA ENCODED IMAGE DATA ENCODED IMAGE DATA ENCODED IMAGE DATA ENCODED IMAGE DATA
Jef f Holt
Int ergraph Corporat ion
Hunt sville, Alabama
A lot of applicat ions require rot at ing r ast er images by 90 d egrees. For
example, if an image has been scanned in column major ord er, most
soft ware requires it t o be in row major ord er t o d isplayi.e., t he image
must be t r ansposed . This cor respond s t o a 90-d egree rot at ion, followed
by inver t ing t he ord er in which t he lines are st ored .
In gen er al , 90-d egr ee r ot at i on an d / or col u mn -major -t o-r ow major
t r ansposit ion is easy if t he d at a is in expand ed for mat i.e., unencod ed . If
t he image is in r u n-lengt h encod ed for mat , t he image need s t o be
expand ed complet ely in memor y and t hen reconver t ed t o ru n-lengt h
for mat . If t he expand ed image is larger t han available memor y, per for-
mance will be t er r ible, even on vir t ual memor y syst ems, because t here is
no ad d ress coherency when read ing out t he image in rot at ed ord er.
This gem d escr ibes a simple algor it hm t o rot at e a run-lengt h encod ed
image d irect ly. It has good per for manceit has been found t o be as good
as or bet t er t han algor it hms t hat expand t he d at a before rot at ing, and
requires much less memor y. The ver sion given rot at es 16-bit d at a. At t he
end of t his gem, var iat ions t o t he algor it hm are given for ot her d at a t ypes,
as well as some not es on per for mance enhancement s.
The algor it hm oper at es as follows. A st ruct ure called t he edge st ruc-
t ure is allocat ed for each line in t he out put (rot at ed ) image. The ed ge
st ruct ure is used t o accumulat e run-lengt hs for t he out put image. It
cont ains:
acc_valuet he pixel value being accumulat ed ,
acc_rlt he cur rent r un-lengt h of t he value being accumulat ed (act u-
ally one less t han t he cur rent run-lengt h),
infor mat ion t o manage a linked list of buffer s,
t he number of r un-lengt hs gener at ed for t he line.
8 7
II.7 ROTATION OF RUN-LENGTH ENCODED IMAGE DATA
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 7
The r st line of t he input image is used t o prime t he set of ed ge
st r uct ures by set t ing t he acc_value t o t he cor rect value for t he r st pixel
of t hat line, and t o init ialize acc_rl.
Then, for each line of r ast er d at a in t he inp u t image, p ixels are
gener at ed sequent ially. These cor respond t o pixels in sequent ial lines of
t he out put image. The gener at ed pixel is compared wit h t he acc_value in
t he ed ge st ruct ure for t hat line in t he out put imaget he value of t he
run-lengt h being accumulat ed for t hat line. If t hey are t he same, t he
run-lengt h value is increment ed . If t hey are d ifferent , t he value-r un-lengt h
pair is ad d ed t o t he list of value-r un-lengt hs and acc_value set t o t he
cur rent pixel, and acc_rl is init ialized .
Var i at i ons on t he Al gor i t hm Var i at i ons on t he Al gor i t hm Var i at i ons on t he Al gor i t hm Var i at i ons on t he Al gor i t hm Var i at i ons on t he Al gor i t hm
The C cod e (Append ix 2) has a slight mod icat ion t o t he preced ing
algor it hm. Inst ead of init ializing t he current _run t o 1, it is init ialized t o
zero, and always is increment ed r at her t han being increment ed only if t he
inp u t and cu r rent color are t he same. This will remove one br anch
inst ruct ion fr om t he inner loop.
The main per for mance enhancement s t hat can be mad e revolve around
increasing cache per for mance. Inst ead of st or ing t he cur rent value and
run being accumulat ed in t he ed ge st ruct ure, t hey can be st ored in a
sep ar at e ar r ay. Then t he only sect ion of t he memor y u su ally being
accessed is t his ar r ay of num_out put _lines
*
4 byt es (ap ar t fr om t he
input d at a, of cour se). The larger ar r ay of ed ge st ruct ures and t he list of
value-runs of t he out put image are accessed only when a value changes
in a line of t he out put image. This means t he cache is less likely t o t hr ash.
Anot her per for mance gain from t his change d epend s on t he st r uct ure
of t he cache on some machines. When a cache hit occu r s, a cer t ain
amount of d at a is read out a cache line of d at a. For example, in t he
clipper chip, 16 byt es are read int o a cache line buffer. A subsequent
access t o t he d at a in t he line gives even fast er access t han a cache hit .
This means t hat while we are processing a single run-lengt h, and hence
d o not need t o go t o memor y except for t he preced ing ar r ayand if t his
ar r ay is in cache, only one in four accesses even will require a cache read
t he rest will be ext remely efcient line hit s.
This id ea can be ext end ed for rot at ing binar y d at a, if t he out put image
has less t han 32K pixels per line.
8 8
II.7 ROTATION OF RUN-LENGTH ENCODED IMAGE DATA
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 8
Inst ead of st or ing value-run pair s for each out put image line, st ore a
single 16-bit int eger where t he bot t om 15 bit s represent t he r un-lengt h,
and t he MS bit represent s t he color being accumulat ed i.e., 0 or 1. As
cur_value, use 0 or 1.
Then t o t est , d o an XOR oper at ion bet ween acc_run and cur_value
if t he result is negat ive, t hen t he pixel has changed . Of cour se, you must
mask off t he t op bit before st or ing it in t he run lengt h list , which just
consist s of an ar r ay of r un-lenght s, wit h an implied t oggle bet ween runs.
This met hod of rot at ion obviously can be gener alized for any size d at a
it em. For example, for 8-bit RGB d at a, use a longword t o st ore t he RGB
values so t he compare can be d one by a single inst ruct ion. Larger d at a
t ypes may require mult iple compares.
See also II.6 A Fast 90-Degree Bit map Rot at or, Sue-Ken Yap;
II.8 Ad apt ive Run-Lengt h Encod ing, And rew S. Glassner ; (179)
A Fast A lgorit hm for General Rast er Rot at ion, A lan W.
Paet h
8 9
II.8 ADAPTIVE RUN-LENGTH ENCODING
GRAPHICS GEMS II Edit ed by JAMES ARVO 8 9
II.8 II.8 II.8 II.8 II.8
A AA AADAPTIVE RUN-LENGTH DAPTIVE RUN-LENGTH DAPTIVE RUN-LENGTH DAPTIVE RUN-LENGTH DAPTIVE RUN-LENGTH
E EE EENCODING NCODING NCODING NCODING NCODING
Andrew S. Glassner
Xerox PARC
Palo Alt o, Calif ornia
Many gr aphics progr ammer s nd t hat much of t heir d isks are occupied by
images. Consid er t hat a st r aight for ward , byt e-by-byt e represent at ion of a
512-by-512 image consist ing of t hree byt es per pixel (a raw dump of an
image) occupies 3*2
18
byt es, or about 0.75 megabyt es. If many images
are t o be st ored , it seems reasonable t o t r y t o red uce t he d isk space
required by each image.
One approach is t o use a gener al-pur pose compact ion algor it hm, such
as t he UNIX compress ut ilit y. Such pr ogr ams ind eed may achieve high
compression, but it is d ifcult t o wor k wit h t he compressed d at a d irect ly.
If an image is t o be composit ed wit h anot her, or one only wishes t o
ext r act a small por t ion, t he ent ire image t ypically must be d ecod ed r st ,
at consid er able space and t ime penalt y.
Some compression t echniques wor k in t wo d imensions, st or ing regions
of t he p ict u r e in a d at a st r u ct u re su ch as a qu ad t r ee. Again, high
compression can be achieved t his way for some images, but nd ing t he
best d ecomposit ion of t he image can be d ifcult , and fast d ecompression
of select ed regions also can be hard .
A less sophist icat ed but simpler image st or age t echnique is known as
run-lengt h encoding. Consid er a gr ay-level image wit h a scanline con-
sist ing of t he following 10 values:
(15, 15, 15, 15, 15, 15, 25, 25, 25, 25).
Suppose we ad opt a for mat consist ing of pair s of byt es: a count and a
value. The count t ells how many t imes t o repeat t he immed iat ely follow-
ing gr ay value. Then t his line could be encod ed wit h t he four byt es
9 0
II.8 ADAPTIVE RUN-LENGTH ENCODING
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 0
(6, 15, 4, 25). This run-lengt h for m required only 4 byt es r at her t han 10.
Since t he count is only 1 byt e long, we can st ore runs from lengt hs 1 t o
255. We can squeeze a single ext r a st ep out of t he run by realizing t hat
we never will encod e runs of lengt h zero. So, red ene t he count byt e t o
represent one less t han t he act ual run lengt h; a count of 0 is a run of
lengt h 1, and 255 is a run of lengt h 256. Thus we need only t wo pair s t o
st ore a 512-byt e-wid e scanline of const ant color.
This scheme is not efcient for images where t he color s change quickly.
If each pixel in a scanline is d ifferent t han t he preced ing pixel, t hen
run-lengt h encod ing act ually will d ouble t he size of t he le relat ive t o a
st r aight for ward d ump, since each pixel will be preced ed by a count byt e
wit h value 0 (represent ing a r un of lengt h 1).
To hand le t his sit u at ion, r ed ene t he cou nt byt e as a signed 8-bit
int eger. If t he value is zero or posit ive, t hen it ind icat es a r un of lengt h
one more t han it s value, as d escr ibed ear lier ; but if t he count is negat ive,
t hen it means t hat what follows is a d ump: a pixel-by-pixel list ing of t he
next few pixels, as many as t he absolut e value of count . This is called
adapt iv e run-lengt h encoding. For exa mp l e, con si d er t h e fol l owi n g
scanline:
(200, 200, 200, 200, 190, 189, 180, 180, 180, 180).
One way t o represent t his is as a 10-byt e d ump, requir ing 11 byt es:
(10, 200, 200, 200, 200, 190, 189, 180, 180, 180, 180).
It would be more efcient t o mix r uns and d umps, requir ing only 7 byt es:
(3, 200, 2, 190, 189, 3, 180).
If you are wor king wit h color d at a, t hen you can consid er each pixel t o
be a single composit e color value, consist ing of red , green, and blue
component s. Thus, r at her t han st or ing just a single byt e aft er each count ,
you can st ore t he 3 byt es encod ing t he red , green, and blue component s.
Test s for equalit y and runs all use t he ent ire RGB pixel. If t hree pixels are
t o be d umped , t hen t he d ump count is st ill 3 (meaning t hree pixels), but
9 1
II.8 ADAPTIVE RUN-LENGTH ENCODING
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 1
9 byt es of d at a follow. Alt er nat ively, you may choose t o encod e t he red ,
green, and blue channels separ at ely, and compress t he t hree channels
ind epend ent ly.
A st r aight for ward applicat ion of t his t echnique usually will prod uce a
smaller le t han a r aw d ump, but not always. For t he following d iscus-
sion, C represent s t he lengt h of a cod e, and P t he lengt h of a pixel value,
bot h in byt es. C always is 1, but P is 1 for gr ayscale pict ures and 3 for
color images.
Consid er t he wor st case for ad apt ive run-lengt h encod ing: a repeat ing
pat t er n of t wo pixel values p
1
and p
2
in t he sequence (p
1
, p
2
, p
2
). St or ing
t his as a r aw pixel-by-pixel d ump requires 3P byt es. An ad apt ive r un-
lengt h encod ing gives (1, p
1
, 1, p
2
), requir ing 2(C + P) byt es. In gen-
er al, if t he pat t er n is repeat ed n t imes, a r aw d ump requires 3Pn byt es,
and an ad apt ive run-lengt h encod ing requires 2n(C + P) byt es. If t he
image is gr ayscale, t hen an ent ire le mad e up of t his pat t er n will require
4n byt es r at her t han 3n for a r aw d ump, expand ing t he le size by 4/ 3.
Happily, color pict ures d o not suffer, since t hey encod e int o 8n byt es
r at her t han t he 9n required by a r aw d ump, a savings of 8/ 9. You can
d ream up ot her pat t er ns t hat cost more in t he encod ed for m t han a r aw
d ump, but unless such pat t er ns d ominat e an image, you will save in t he
long run. Where you lose is wit h any pict ure where t here are no runs at
all; t hen you effect ively end up saving a r aw d ump, but you pay for t he
ext r a, useless cod e byt es.
I recommend t hat you encod e wit h a greed y algor it hm: Any t ime you
nd t wo or more pixels of t he same color in a row, encod e t hem as a run.
If t he nal encod ed pict ure is larger t han a r aw byt e-by-byt e d ump, t hen
forget about it and st ore just t he r aw le. I have found t his sit uat ion t o be
sufcient ly r are t hat I d o not bot her wit h t he t est .
You can make encod ed les easier t o use if you encod e each scanline
ind ivid ually, r at her t han t r ying t o t ie t oget her t he end of one line wit h t he
st ar t of t he next . You lose a lit t le bit of compression t his way, but you
save in speed when you want d irect access t o some par t of t he image. In
my implement at ion, I also st ore a head er block at t he t op of each le,
giving t he offset in byt es from t he st ar t of t he le t o t he st ar t of each
scanline. This makes it easy t o quickly ext r act and d ecod e small regions
of t he image on t he y. A 32-bit offset for each of s scanlines requires
only 4s byt es of head er, a classic space-t ime t r ad e-off t hat buys you fast
r and om access at t he cost of a bit of ext r a le st or age.
9 2
II.8 ADAPTIVE RUN-LENGTH ENCODING
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 2
Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s Acknowl edgment s
I r st saw ad apt ive run-lengt h encod ing in a progr am wr it t en by Ephr aim
Cohen at t he NYIT Comput er Gr aphics Lab. Greg Abr am helped me wr it e
t he Ikonas microcod e t o encod e and d ecod e images at UNC-Chapel Hill.
See also II.7 Rot at ion of Run-Lengt h Encod ed Image Dat a, Jeff
Holt ; II.9 Image File Compression Mad e Easy, Alan W. Paet h
9 3
II.9 IMAGE FILE COMPRESSION MADE EASY
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 3
II.9 II.9 II.9 II.9 II.9
IMAGE IMAGE IMAGE IMAGE IMAGE FILE COMPRESSION FILE COMPRESSION FILE COMPRESSION FILE COMPRESSION FILE COMPRESSION
MADE EASY MADE EASY MADE EASY MADE EASY MADE EASY
Alan W. Paet h
NeuralWare, Inc.
Pit t sburgh, Pennsylvania
A simple pred ict ive-cor rect ive cod ing lt er is d er ived t hrough empir ical
and analyt ical means. Passing a 2D image t hrough t his cod er in byt e-ser ial
ord er yield s a highly red und ant d at a st ream well-suit ed t o subsequent
ser ial compression, as by 1D Lempel-Ziv or Huffman cod er s. When used
t o process 2D images compact ed und er t he well-known Unix compress
t ool, t reat ed les t ypically show an ad d it ional 30% red uct ion in size.
Compared t o unt reat ed or iginals, cumulat ive compression r at ios of 4 : 1
are t ypical. The lt er is d emonst r ably lossless and is specically cr aft ed
for st or age red uct ion on r ast er d at a set s of ar bit r ar y bit precision (Paet h,
1986, 1987).
As seen in Fig. 1a, PC cod ing est imat es t he value of t he cur rent input
d at um by making a pred ict ion based on t he past hist or y of t he d at a
st ream. A d ifference signal bet ween t he guess and t he cur rent value
represent s t he cor rect ion t o t he pred ict ed value. Given an id eal pred ict or,
t he cor rect or out put is zero. For pr act ical pred ict or s, t he out put values
are clust ered about zero in symmet r ic fashion, leaving a d at a st ream
suit able for subsequent encod ing. The efciency of t he cod er may be
char act er ized by t he creat ion of a hist ogr am (Fig. 2). Unlike ot her
common schemes, such as Vit er bi encod ing, PC cod ing is near ly it s own
inver se. As seen in Fig. 1b, a pred ict ionnow based on t he d ecod ed
out put t hat has reconst ruct ed t he or iginalis used t o provid e t he cor rec-
t ion implicit wit h t he cur rent inpu t valu e. Thu s, a minor change in
int er nal progr am st ruct ure allows t he same cod e t o ser ve as bot h d ecod er
and encod er. Not e t hat t he pred ict or input always must be d er ived from
previously occur r ing values, as t he out put half of t he syst em ot her wise
would violat e causalit y.
9 4
II.9 IMAGE FILE COMPRESSION MADE EASY
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 4
Figure 1. Pred ict ion-cor rect ion cod ing.
PC cod er s ar e a br oad family. Adapt ive (APC) cod er s may learn
based on t he t rue value of t he next input ; t he ad just ment most oft en is a
weight ed linear aver age. For 2D signals, t he past st at e may be repre-
sent ed as a t emplat e of values t hat preface t he cur rent pixel (in t r ansmis-
sion ord er ) in bot h X and Y. Implement at ion of a simple, ad apt ive 2D
lt er for binar y images is st r aight for ward : The st at e of a t emplat e of N
cells for ms an N-bit int eger, which ind exes a t able of pred ict ions cont ain-
ing 2
N
1-bit ent r ies. Each ent r y record s t he last out put seen. Thus, any
Figur e 2. Dat a hist ogr am: (a) r aw, (b) t reat ed .
9 8
II.9 IMAGE FILE COMPRESSION MADE EASY
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 8
Figure 4. Compression r at ios.
(a) Or iginal
Figur e 5.
9 9
II.9 IMAGE FILE COMPRESSION MADE EASY
GRAPHICS GEMS II Edit ed by JAMES ARVO 9 9
(b) Pred ict ion
(c) Cor rect ion
Figure 5. (Cont inued)
100
II.9 IMAGE FILE COMPRESSION MADE EASY
GRAPHICS GEMS II Edit ed by JAMES ARVO 100
The accur acy of t he hybr id pred ict or may be t est ed by pit t ing it against
a p er fect oracle, which p eeks at t he next inp u t valu e (
*
) p r ior t o
making it s pred ict ion on set {a, b, c}. (Peeking is a t imewor n t r ad it ion for
all successful or acles.) Also t est ed is a t r ivial 2D pred ict or t hat consid er s
merely t he input set (b); t hat is, t he previous column element is chosen.
This met hod sat ises rules [1, 2, 4], but not [3]. It places an ad d ed burd en
on t he subsequent 1D cod ing st ep: Long runs of similar out put value are
possible, but are not necessar ily clust ered about zero, d egr ad ing encod -
ing efciency. However, ad apt ive 1D cod er s (Unix Compress) oft en can
d o well. In cont r ast , t he t wo-st ep p r ed ict ion scheme p resent ed her e
suppor t s a simplied post -cod ing, as by skip compression of runs of
zeros. Encod ing r at ios are illust r at ed in Fig. 4; t he t r ad it ional Huffman-
d er ived ent ropy measure is supplant ed by a le-size r at io for nal sizes
und er Unix Compress. Figures 5a t hrough c snow t he oper at ion of t he
non-ad apt ive 2D lt er at t he respect ive st ages of input , pred ict ion, and
cor rect ion.
In summar y, a met hod for efcient , nonlinear, algebr aic pred ict ion of
2D images is d emonst r at ed . The met hod is bot h lossless and par t icular ly
well-suit ed t o t he encod ing of bot h synt het ic and scanned r ast er images
of ar bit r ar y precision.
See also II.8 Ad apt ive Run-Lengt h Encod ing, And rew S. Glassner
101
II.10 AN OPTIMAL FILTER FOR IMAGE RECONSTRUCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 101
II.10 II.10 II.10 II.10 II.10
AN AN AN AN AN OPTIMAL FILTER FOR OPTIMAL FILTER FOR OPTIMAL FILTER FOR OPTIMAL FILTER FOR OPTIMAL FILTER FOR
IMAGE IMAGE IMAGE IMAGE IMAGE RECONSTRUCTION RECONSTRUCTION RECONSTRUCTION RECONSTRUCTION RECONSTRUCTION
Nelson Max
Lawrence Livermore Nat ional Laborat ory
Livermore, Calif ornia
In a p reviou s gem, Mar k Pavicic d iscu ssed r ad ially symmet r ic lt er
funct ions, opt imized for sever al funct ional for ms. Here, I propose anot her
funct ional for m, meet ing somewhat d ifferent cr it er ia.
For t he pur poses of image reconst ruct ion from a sampled r ast er, it is
impor t ant t hat t he lt er be at least C
1
smoot h, so t hat t he reconst ruct ed
image will not have Mach band s. Pavicics lt er s are not C
1
, r esult ing in
creases in t he sum of t he lt er s, visible in his gures. Also, Pavicic
rest r ict ed himself t o r ad ial lt er funct ions f(r), which are zero for r 1.
I d o not make t his rest r ict ion.
I want ed a funct ion t hat was easily comput ed , and chose t o use a
nonunifor m quad r at ic spline g(r), of t he for m shown in Fig. 1. It consist s
of d ownward cur ving par abola for 0 r s, and an upward cur ving
par abola for s r t , which meet smoot hly at r = s, and has t he
proper t ies g(0) = 1, g' (0) = 0, g(t ) = 0, and g' (t ) = 0.
The funct ion t hat sat ises t hese cond it ions is

g r ( )
1
r
2
st
0 r s,
(t r)
2
t(t s)
s r t ,
0 t r.

'

102
II.10 AN OPTIMAL FILTER FOR IMAGE RECONSTRUCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 102
Figur e 1.
The volume V und er t his lt er is comput ed as a solid of revolut ion,

V = 2 rf (r) dr
0

= 2 r
r
3
st
|
.

`
,

dr + 2
r(t r)
2
t(t s)
s
t

dr
0
s

= 2
s
2
2

s
4
4st
+
t
4
12t(t s)

s
2
t
2
2t(t s)
|
.

+
2s
3
t
3t(t s)

s
4
4t(t s)
`
,

.
The lt er f(r) =

1
V
g(r), nor malized t o have unit volume, t hus can be
found in t er ms of t he t wo par amet er s, s and t .
A funct ion wit h const ant value 1, sampled on t he int eger lat t ice {(i, j)},
will be reconst ruct ed as

h(x, y) = f (x i)
2
+ (y j)
2
( )
j =

i =

.
One cond it ion for opt imalit y is t o minimize t he d ifference d bet ween t he
103
II.10 AN OPTIMAL FILTER FOR IMAGE RECONSTRUCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 103
maximum value M and t he minimum value m of h. This d ifference can
become ar bit r ar ily small as s and t approach innit y, so I limit ed t t o be
less t han 2. Because of symmet r y and t he limit ed size r ange I allowed
for t ,

M = max
0 x .5
0 y .5
f (x i)
2
+ (y j)
2
( )
j = 1
2

i = 1
2

.
Figur e 2.
104
II.10 AN OPTIMAL FILTER FOR IMAGE RECONSTRUCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 104
For each xed s and t , I found t he cr it ical point s of h(x, y) by solving
t he equat ions

h
x
= 0 and

h
y
= 0, using 2D Newt on it er at ion, st ar t ing at
all init ial cond it ions in a 26 26 ar r ay of point s insid e t he square of sid e
1/ 2, and t ook d t o be t he d ifference bet ween t he maximum and mini-
mum cr it ical value.
The minimum d, equal t o .885 percent , was found at s = .4848 and
t = 1.3778. The RMS er ror bet ween h(x, y) and 1 was .261 percent , and
t he er ror volume,

abs(h(x, y) 1) dxdy
0
1

0
1

,
used by Pavicic was .232 percent . Figure 2 shows a r ast er int ensit y image
of t his h(x, y) for x and y bet ween 0 and 2, wit h t he cont r ast amplied
by a fact or of 100. Alt hough t here is clear ly visible per iod ic st ruct ure, t he
int ensit y var ies smoot hly.
The minimum RMS er ror of .245 percent is at t ained when s = .4810
and t = 1.3712, and t he minimu m er r or volu me of .210 p ercent is
at t ained when s = .4792 and t = 1.3682.
This wor k was per for med und er t he auspices of t he U.S. Depar t ment of
Energy by t he Lawrence Liver more Nat ional Labor at or y und er cont r act
number W-7405-Eng-48.
See a l so (144) Conv enient A nt i-A liasing Filt ers t hat Mini-
miz e Bumpy Sampling, Mark J. Pav icic; (147) Filt ers
for Common Resampling Tasks, Ken Turkouski
105
II.11 NOISE THRESHOLDING IN EDGE IMAGES
GRAPHICS GEMS II Edit ed by JAMES ARVO 105
II.11 II.11 II.11 II.11 II.11
NOISE NOISE NOISE NOISE NOISE THRESHOLDING IN THRESHOLDING IN THRESHOLDING IN THRESHOLDING IN THRESHOLDING IN
EDGE EDGE EDGE EDGE EDGE IMAGES IMAGES IMAGES IMAGES IMAGES
John Schlag
MacroMind, Inc.
San Francisco, Calif ornia
This is act ually more of a vision gem t han a gr aphics gem, but since
image processing is so oft en useful in comput er gr aphics, t his seems
apropos.
First deriv at iv e lt ers (oft en ca l l ed edge det ect ors i n t h e vi si on
lit er at ure) are oft en used t o shar pen d igit ized images, or t o prod uce a
cand id at e set of point s at which t o evaluat e some ot her oper at or. They
also are used t o obt ain a sur face nor mal per t ur bat ion from an image for
bump mapping. Digit ized images are t ypically noisy. Fir st d er ivat ive
est imat or s such as t he Sobel and Prewit t operat ors (see below) accent u-
at e t his noise. Hence, it oft en is necessar y t o t hreshold t he result of t he
ed ge oper at or t o lt er out t he noise. The quest ion t hen is how t o pick t he
t hreshold . For t hose who nd ar bit r ar y (t weak) par amet er s d ist ast eful,
her e is a way t o at least t ie t he t hreshold t o a d iscer nible syst em
par amet er.
The t wo most common r st d er ivat ive ed ge d et ect or s are t he Sobel and
Prewit t oper at or s:

Sobel: i
x
(p)
1 0 1
2 0 2
1 0 1

]
]
]
]
]
i
y
(p)
1 2 1
0 0 0
1 2 1

]
]
]
]
]
,
Prewitt: i
x
(p)
1 0 1
1 0 1
1 0 1

]
]
]
]
]
i
y
(p)
1 1 1
0 0 0
1 1 1

]
]
]
]
]
,
The 3-by-3 convolut ion masks are evaluat ed at each pixel t o prod uce
est imat es of t he par t ial d er ivat ives of t he image fu nct ion. The ed ge
funct ion E(p) prod uces an est imat e of t he magnit ud e of t he gr ad ient .
The t hreshold can be based on an evaluat ion of t he noise in t he gr ad ient

E(p) = i
x
2
+ i
y
2
.
106
II.11 NOISE THRESHOLDING IN EDGE IMAGES
GRAPHICS GEMS II Edit ed by JAMES ARVO 106
Figur e 1. The Rayleigh probabilit y d ensit y funct ion.
d omain. Assume t hat t he noise in t he input image is nor mal wit h mean
zero and var iance

n
2
. Each mask for ms a linear combinat ion of t he
neighborhood pixels, so t he noise d ist r ibu t ion in each of t he par t ial
d er ivat ive est imat es also is nor mal. Since t he var iances of ind epend ent
var iables ad d as t he squares of t heir coefcient s, t he noise var iance in
each est i mat e wi l l be

x
2
=
y
2
= 12
n
2
(for t h e Sobel masks). Fr om
probabilit y t heor y (Papoulis, 1965, p. 195), t he noise d ist r ibut ion in t he
ed ge funct ion has a Rayleigh d ist r ibut ion wit h par amet er
x
:

p(z) =
z

x
2
exp
z
2
2
x
2
|
.

`
,

for z 0.
The t hreshold T can be placed t o eliminat e a given percent age of t he
d ist r ibut ion. Int egr at ing t he d ensit y funct ion and solving for t he t hreshold
gives

T = 2
x
2
ln(1/ 1 k) , wher e k is t he fr act ion of t he d ist r ibu t ion
t o be eliminat ed . If t he var iance

n
2
of t he input noise is not known a
priori, it can be measured easily from a blank image, or a at region of
an image. Alt er nat ively, we can examine t he hist ogr am of an unt hresh-
old ed ed ge image t o nd
x
d irect ly. Not ice t hat we are playing fast and
loose wit h assumpt ions of st at ist ical ind epend ence, since t he convolut ion
masks are using t he same pixels. Exper iment conr ms however, t hat t he
ed ge funct ion d ist r ibut ion is as expect ed .
Similar reasoning ap p lies in t he case of bump mapping, where t he
est imat es of t he par t ials i
x
and i
y
, are used t o per t ur b a sur face nor mal.
In t his case, E(p) is never calculat ed , and all one need wor r y about is t he
noise d ist r ibut ion of t he par t ials.
107
II.12 COMPUTING THE AREA, THE CIRCUMFERENCE, AND THE GENUS OF A BINARY DIGITAL IMAGE
GRAPHICS GEMS II Edit ed by JAMES ARVO 107
II.12 II.12 II.12 II.12 II.12
COMPUTING COMPUTING COMPUTING COMPUTING COMPUTING THE AREA, THE THE AREA, THE THE AREA, THE THE AREA, THE THE AREA, THE
CIRCUMFERENCE CIRCUMFERENCE CIRCUMFERENCE CIRCUMFERENCE CIRCUMFERENCE, AND THE , AND THE , AND THE , AND THE , AND THE
GENUS GENUS GENUS GENUS GENUS OF A BINARY OF A BINARY OF A BINARY OF A BINARY OF A BINARY
DIGITAL DIGITAL DIGITAL DIGITAL DIGITAL IMAGE IMAGE IMAGE IMAGE IMAGE
Hanspet er Bieri, Andreas Kohler
Universit y of Berne
Berne, Swit zerland
An Exampl e An Exampl e An Exampl e An Exampl e An Exampl e
Figu r e 1 shows a small binary digit al image of resolut ion 8
*
7 consist -
ing of 31 black and 25 whit e pixels. Pixels are consid ered here t o be
closed unit squares, alt hough we will assume t hem t o be implement ed as
element s of a binar y mat r ix, as is oft en t he case. The set union of t he
black pixels will be called t he gure of t he image, and comput ing t he
area, t h e circumference, a n d t h e genus (or Euler number) of t h e
image more precisely shall mean comput ing t hese t hree impor t ant prop-
er t ies for t he gure.
Using element ar y geomet r y, we easily ver ify t hat t he area of t he image
in Fig. 1 is 31 and t he circumference is 62. The genus of a binar y d igit al
image oft en is d ened as t he number of connect ed component s of t he
gure minus t he number of holes. (These are t he connect ed component s
of t he set complement of t he gure which d o not meet t he bord er of t he
image.) Obviously, t he image of Fig. 1 has t wo black connect ed compo-
nent s and t hree holes; t herefore, it s genus is 1.
The Met hod The Met hod The Met hod The Met hod The Met hod
In Fig. 2, t he d igit al image of Fig. 1 is represent ed in a slight ly d ifferent
way, which makes it easy t o recognize t he vert ices, sides, and (quad r at ic)
ext ent s of all it s pixels. The main t ask of t he met hod we are going t o
present is count ing t he number of ver t ices, sid es, and ext ent s of t he black
pixels in an image. Because ver t ices are zero-d imensional, sid es one-
108
II.12 COMPUTING THE AREA, THE CIRCUMFERENCE, AND THE GENUS OF A BINARY DIGITAL IMAGE
GRAPHICS GEMS II Edit ed by JAMES ARVO 108
Figure 1. A binar y d igit al image.
d imensional and ext ent s t wo-d imensional, we d enot e t hese number s by
n
0
, n
1
, and n
2
, respect ively. For our example, we get n
0
= 61, n
1
= 93,
n
2
= 31. Knowing t hese number s for a given image I, it is ver y easy t o
comp u t e t he area A, t he circu mference C and t he genu s G of I by
applying t he following for mulas:
A(I) = n
2
,
C(I) = 2
*
n
1
4
*
n
2
,
G(I) = n
0
n
1
+ n
2
.
Now, assuming t hat I has resolut ion m
*
n and is pr ovid ed as a binar y
m
*
n -mat r ix M, we can comput e n
0
, n
1
, and n
2
simult aneously in one
single scan of M, e.g., row by row and from left t o r ight . Then we only
have t o evaluat e t he t hree preced ing for mulas t o d et er mine A(I), C(I)
and G(I).
109
II.12 COMPUTING THE AREA, THE CIRCUMFERENCE, AND THE GENUS OF A BINARY DIGITAL IMAGE
GRAPHICS GEMS II Edit ed by JAMES ARVO 109
Figure 2. The ver t ices, sid es, and ext ent s of all pixels in t he image.
For an explanat ion of t his met hod which is based on t he fact t hat
area, circumference, and genus can be und er st ood as ad d it ive funct ionals
t he int erest ed read er is refer red t o Bier i and Nef (1984), where t he
d-d imensional case is t reat ed and where more refer ences (sever al in
Ger man) are list ed .
The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm
To nd n
0
, n
1
, and n
2
fast and elegant ly, we ad d an auxiliar y row and an
auxiliar y column of zeros t o M and imagine t he cor respond ing image
part it ioned in a way shown in Fig. 3. By t his par t it ioning, ever y pixel
ver t ex, pixel sid e, and pixel ext ent of I is associat ed wit h exact ly one
element of t he (enlarged ) mat r ix M. For each mat r ix element M
i, j
, we
call t he associat ed ver t ex, hor izont al sid e, ver t ical sid e, and pixel ext ent
t he pixel component s at p osit ion (i, j) and d enot e t hem by P
i, j
, H
i, j
,
V
i, j
and E
i, j
, respect ively (Fig. 4).
110
II.12 COMPUTING THE AREA, THE CIRCUMFERENCE, AND THE GENUS OF A BINARY DIGITAL IMAGE
GRAPHICS GEMS II Edit ed by JAMES ARVO 110
Figure 3. All pixel component s belonging t o t he enlarged mat r ix.
Figur e 4. Five neighbor ing pixel component s are blackened.
111
II.12 COMPUTING THE AREA, THE CIRCUMFERENCE, AND THE GENUS OF A BINARY DIGITAL IMAGE
GRAPHICS GEMS II Edit ed by JAMES ARVO 111
Now let us consid er an element M
i, j
d ur ing t he scan of t he mat r ix M
(0 i m 1, 0 j n 1). The following pseud o-cod e d escr ibes
how our algor it hm upd at es n
0
, n
1
, and n
2
at t his posit ion and how it
blackens cer t ain neighbor ing pixel component s in case M
i, j
represent s a
black pixel (Fig. 4). (For i = m or j = n, only t he upd at e of n
0
, n
1
, and
n
2
is necessar y, of cour se.)
i f M[i][j] = 1 black pixel
then begi n
N[0] N[0] + 1;
N[1] N[1] + 2;
N[2] N[2] + 1;
P[i][j + 1] 1;
V[i][j + 1] 1;
P[i + 1][j] 1;
H[i + 1][j] 1;
P[i + 1][j + 1] 1;
end;
el se begi n whit e pixel
i f P[i][j] = 1
then N[0] N[0] + 1;
i f H[i][j] = 1
then N[1] N[1] + 1;
i f V[i][j] = 1
then N[1] N[1] + 1;
end;
Large d igit al images oft en are st ored in rast er represent at ion, i.e., as a
sequent ial le where row i preced es row i + 1. In Append ix 2, t he C
Implementation of our algorithm assumes the given binary digital image I
t o be provid ed in t his way.
III
FRAME BUFFER
TECHNIQUES
115
FRAME BUFFER TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 115
III III III III III
F FF FFRAME BUFFER RAME BUFFER RAME BUFFER RAME BUFFER RAME BUFFER
TECHNIQUES TECHNIQUES TECHNIQUES TECHNIQUES TECHNIQUES
A frame buffer is t he piece of hard war e at t he hear t of most gr aphics
d isplay t asks. To t he comput er, t his d evice appear s essent ially as a large
chunk of memor y, while t o t he user, it is t he vehicle for perceiving t he
und er lying d at a visually. This mapping from d at a t o image is car r ied out
by alt er ing t he appear ance of a t wo-d imensional ar r ay of d iscret e pict ure
element s, or pixels, accord ing t o t he cont ent s of cor respond ing memor y
locat ions. Thus, t he role of mod er n fr ame buffer s is t o t ake t he nor mally
invisible cont ent s of comput er memor y and present t hem in a visual for m.
Because it is a physical piece of hard war e, t he fr ame buffer possesses
cer t ain limit at ions t hat t he gr aphics progr ammer must t ake int o account ,
such as resolut ion in pixels and t he number of d iscret e color s each of
t hese pixels can assume. Given t he d iver sit y and impor t ance of t hese
d evices, it is not sur pr ising t hat many t echniques have been d eveloped t o
make t he most of t heir capabilit ies. All of t he gems of t his Par t d eal wit h
some aspect of color as it per t ains t o a fr ame buffer.
There are many similar it ies bet ween t he t echniques explored in t his
Par t and t hose of t he previous Par t on image processing. These similar i-
t ies st em from t he fact t hat bot h fr ame buffer t echniques and image
processing are int imat ely linked wit h manipulat ing rect angular ar r ays of
d iscret e pixels.
116
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 116
III.1 III.1 III.1 III.1 III.1
E EE EEFFICIENT INVERSE COLOR FFICIENT INVERSE COLOR FFICIENT INVERSE COLOR FFICIENT INVERSE COLOR FFICIENT INVERSE COLOR
M MM MMAP COMPUTATION AP COMPUTATION AP COMPUTATION AP COMPUTATION AP COMPUTATION
Spencer W. Thomas
Universit y of Michigan
Ann Arbor, Michigan
An inverse color map is used t o t r anslat e full (RGB) color s int o a limit ed
set of color s. It might be used t o d r ive an 8-bit color d isplay (Apple,
1988), t o per for m er ror-propagat ion d it her ing (e.g., Floyd -St einberg) in
color (as in Gem II.3, Color Dit her ing, by Spencer Thomas), or for t he
out put phase of a color quant izat ion algor it hm (Heckber t , 1982; Ger vaut z
and Pu rgat hofer, 1990). Pu blished met hod s for compu t ing su ch color
maps seem t o be few and far bet ween, and eit her are relat ively inefcient
or inexact . This gem d escr ibes a simple and efcient met hod for comput -
ing inver se color maps.
A represent at ive color is one of t he color s in t he limit ed set . There are
n represent at ive color s. RGB color s are quant ized t o k bit s by t aking
t he t op k bit s of each pr imar y as an int eger in t he r ange 0..2
k
. A inverse
color map is a cu bi cal ar r ay, 2
k
on each si d e, t h at i s i n d exed by
qu ant ized red , gr een, and blu e valu es t o obt ain a color ind ex t hat
represent s t he closest (wit hin t he limit s of t he quant izat ion) represent a-
t ive color t o t he given RGB color.
Two ver sions of t he algor it hm will be d escr ibed . The r st is simple, and
illust r at es t he basic pr inciple as well. It also is fair ly efcient , t aking
approximat ely 24 second s t o complet ely ll an inver se color map (k = 5
and n = 256) on a SUN 3/ 60 comput er. The asympt ot ic behavior of t his
algor it hm is O(n 2
3k
), which is achieved for relat ively small values of 1
and n (on a SUN 3/ 60, t he const ant of propor t ionalit y is 2.8 sec).
The second ver sion is signicant ly more complex, but much more ef-
cient for large color maps, t aking approximat ely 3.2 second s t o ll t he
same map. The asympt ot ic behavior of t his algor it hm is expect ed t o be
O(log(n) 2:
3k
), but t his limit is not reached in pr act ice. St ill, t he speed up
117
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 117
ver si on 2 over ver si on 1 i s si gn i can t , an d i mp r oves as n an d k
increase.
The C Implement at ion for bot h ver sions is includ ed in Append ix 2. It
also is d ist r ibut ed freely as par t of t he Ut ah Rast er Toolkit .
Incr ement al Di st ance Cal cul at i on Incr ement al Di st ance Cal cul at i on Incr ement al Di st ance Cal cul at i on Incr ement al Di st ance Cal cul at i on Incr ement al Di st ance Cal cul at i on
This algor it hm is based on t he following obser vat ions:
The regions of RGB space t hat map t o a given represent at ive color
compr ise exact ly t hose point s t hat are closer t o t he given represent a-
t ive t han t o any ot her. This gives r ise t o a st ruct ure known as a
Voronoi diagram (Prep ar at a and Shamos, 1985) in t he t hree-d imen-
sional RGB space. Figure 1 (see color inser t ) shows one of t hese as a
set of slices per pend icular t o t he red axis.
A d ept h-buffered image of cones aligned wit h t he Z axis result s in a
pict ure of a 2D Voronoi d iagr am. Each region consist s of t he point s
t hat are closest t o t he project ion of t he apex of a single cone.
In fact , t he dept h of a point on t he cone is propor t ional t o t he d ist ance
of t he screen point from t he project ed apex of t he cone. Thus, we
might call t he d ept h buffer a d ist ance buffer inst ead .
A 3D image of t he RGB Voronoi d iagr am can be obt ained by using a
3D d ist ance buffer t o rend er hypercones whose apices coincid e wit h
t he represent at ive color s.
Since t he d ecision t o color a given voxel is based only on t he relat ive
magnit ud e of t he d ist ances involved , it wor ks just as well t o use t he
d ist ance squared r at her t han t he act ual Euclid ean d ist ance.
The d ist ance squared easily can be comput ed increment ally using only
int eger ad d it ion and subt r act ion oper at ions.
Fi n al l y, for ver si on 2, we obser ve t h at t h e r egi on s ar e con vex.
The squ ar e of t he Eu clid ean d ist ance from a color (r, g, b) t o a
represent at ive color (r
i
, g
i
,b
i
) is
d(r, g, b) = (r r
i
)
2
+ (g g
i
)
2
+ (b b
i
)
2
.
118
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 118
The effect of increment ing one color component , say b, by a quant it y x
yield s

b
(r,g,b) = d(r,g,b + x) d(r,g,b) = x
2
2b
i
x + 2bx.
The second d ifference,


b
2
(r, g, b) =
b
(r, g, b + x)
b
(r, g, b) = 2x
2
,
is a const ant , assuming x is const ant . Not e, t oo, t hat t hese d epend only
on b, an d so ar e i n d ep en d en t of t h e val u es of r an d g. For t h e
pseud o-cod e, we assume t hat t he input RGB values are represent ed wit h
8 bit s per pr imar y, and t hat x = 2
8k
, Dist ances are measured t o t he
cent er of each quant ized cell, so x/2 is used as t he st ar t ing point inst ead
of 0.
dist buf is a 3D array of 32-bit int egers 2
k
on a side. All it s element s are
init ialized t o 2
31
1.
mapbuf is a 3D array of 8-bit index values of t he same size.
x lshift (1, 8k);
xsqr lshift (x, 8k);
t xsqr xsqr *2;
The following code is execut ed for each color in t he (forward) color map.
The variable color_index is t he corresponding index.
Thus, (ri,gi,bi)= color map[color_index], rdist , gdist , bdist are t he com-
put ed dist ances for t he respect ive nest ed loops
rd ist (r i x/ 2)
2
+ (gi x/ 2)
2
+ (bi x/ 2)
2
;
rinc, ginc, binc are t he init ial increment s for rdist , gdist , bdist
(i.e., for r = g = b = x/2)
r inc 2*x*(ri x);
ginc 2*x*(gi x);
binc 2*x*(b x);
rxx, gxx, bxx are t he current increment values for rdist , gdist , bdist
r xx r inc;
rq, gq, bq are t he quant ized versions of r, g, b
119
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 119
f or rq 0 to 2
k
1 do
gd ist rd ist ;
gxx ginc;
f or gq 0 to 2
k
1 do
bd ist gd ist ;
bxx binc;
f or bq 0 to 2
k
1 do
i f d ist buf[rq][gq][bq] > bd ist then
begi n
Not e t hat in C, t he subscript ing is done efcient ly
wit h point ers. E.g., inst ead of dist buf, use a point er
dist p, init ialized t o dist buf, and increment ed
each t ime t hrough t he blue loop.
d ist buf[rq] [gq] [bq] bd ist ;
mapbuf[rq] [gq] [bq] color _ind ex;
end;
bd ist bd ist + bxx;
bxx bxx + t xsqr ;
endl oop;
gd ist gd ist + gxx;
gxx gxx + t xsqr ;
endl oop;
rd ist rd ist + r xx;
r xx r xx + t xsqr ;
endl oop;
This cod e visit s ever y cell in t he inver se color map for each represent a-
t ive color. The cost of changing a cell is not t hat much higher t han t he
cost of visit ing it in t he r st place. Therefore, t he t ime t o run will be
propor t ional t o t he prod uct of t he number of represent at ives and t he
number of cells, or n 2
3k
. This is bor ne out by exper iment for values of
k in t he r ange 46.
Taki ng Advant age of Convexi t y Taki ng Advant age of Convexi t y Taki ng Advant age of Convexi t y Taki ng Advant age of Convexi t y Taki ng Advant age of Convexi t y
The r st ver sion of t he algor it hm, while quit e simple, visit s many inver se
color map cells t hat it d oes not change because t hey are t oo far from t he
120
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 120
represent at ive. The color s t hat map t o a given represent at ive lie wit hin a
convex polyhed ron. We can t ake ad vant age of t his fact t o visit fewer cells
per represent at ive and t hereby speed up t he algor it hm. The basic id ea is
simple: St ar t at t he represent at ive color and scan out ward s unt il cells not
in t he region are encount ered , t hen st op. In one d imension, t his result s in
t he following pseud o-cod e. The d et ails of t he increment al d ist ance com-
put at ion are not repeat ed .
d et ect ed _some fal se;
Not e: quant ize(b) = rshift (b,8 k)
for bq quant ize(bi) t o 2
k
1 do
i f d ist buf[bq] < bd ist then
begi n
i f d et ect ed _some then
exit ;
end;
el se begi n
d et ect ed _some t r ue;
d ist buf[bq] bd ist ;
mapbuf[bq] color _ind ex;
end;
for bq quant ize(bi) 1 to 0 step 1 do
Pret t y much t he same code goes in here as in t he preceding.
Because of going down inst ead of up, reverse t he order of increment ing:
bxx bxx t xsqr;
bdist bdist bxx;
The mult id imensional scan essent ially is t he same, except t hat for t he
green and red levels, t he inequalit y t est and changes t o t he buffer are
replaced by a call on t he next inner loop. The value of d et ect ed _some
from t he lower-level loop is used t o d et er mine whet her a change was
mad e, and t hus whet her t o set d et ect ed _some for t he higher-level loop.
Ad d it ional complexit y is int rod uced when we realize t hat as green, say,
scans away from t he represent at ive color, t he act ive segment of a blue
scanline might not over lap t he blue value of t he represent at ive color (Fig.
2). Thus, we really should upd at e t he blue st ar t ing point so t hat it has a
good chance of being close t o t he segment on t he next scanline. Of
cour se, t his st ar t -point t r acking need s t o be reset at t he st ar t of t he next
121
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 121
green loop (when green st ar t s scanning d own, for example, or when red
has just been increment ed t o t he next scan-plane). There ar e a number of
var iables (such as t he init ial d ist ance and it s increment ) t hat are associ-
at ed wit h t he st ar t ing point ; t hese must be upd at ed as well.
1
The preced -
ing cod e changes t o look like t his:
The variable names starting with c are the original values of these variables
at t he blue cent er (quant ize(B)). They are used t o reinit ialize t he variables
when green st art s a new loop.
i f new_green_loop then
begi n
here = quant ize(B);
binc = cbinc;
bd ist gd ist ;

end;
d et ect ed _some false;
for bq here to 2
k
1 do
i f d ist buf[bq] < bd ist then
This is t he same as above.
el se begi n
i f not d et ect ed _some and bq > here then
First t ime on t his scan-line, updat e here if necessary.
here bq;
binc bxx;
gd ist bd ist ;

end;
This is t he same as above.
end;
for bq here 1 to 0 step 1 do
essent ially same code goes in here as above.
1
In t he green loop , t wo set s of some of t hese valu es (e.g., gd ist ) mu st be maint ained . One set is
u p d at ed fr om below by t he blu e loop , and t he second set is u sed t o u p d at e t he red loop when t he
green st ar t ing p oint is changed .
122
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 122
Figure 2. A sample d omain in a blue-green plane, showing t hat t he st ar t ing point of
t he blue scanlines may shift t o t he sid e. The solid lines ind icat e t he changed segment
(scanning up from t he blue axis), and t he boxes ind icat e t he st ar t ing point of each
segment .
This prod uces a reasonable speed up (about 7 for a map wit h k = 5),
but more is possible. When t he scan encount er s a scanline or scan-plane
on which t here are no cells for t he represent at ive, it must look at all t he
cells on t hat line or plane. This causes a large number of cells t o be
examined uselessly. The minimum and maximum values reached d ur ing a
previous scan somet imes can be used t o pred ict t he r ange wit hin which
any cells found on t he next scan must lie. In par t icular, if t he minimum is
increasing, or t he maximum d ecreasing, t hen t he new scan cannot over-
lap t he previous scan on t hat end (Fig. 3). This is a consequence of t he
convexit y of t he region. The min/ max t r acking is includ ed in t he C
Implement at ion (Append ix 2), but will not be elabor at ed on here. This
ver sion showed a speed up of about 9 for a 5-bit map, and about 25
for a 6-bit map (ver sus 15 for t he ver sion wit hout min/ max t r acking).
A nal opt imizat ion split s t he blue scanning loops int o t wo halves t o
avoid t he if d et ect ed _some t est in t he inner loop. The r st loop nd s
t he beginning of t he segment and t he second loop lls it .
123
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 123
Figure 3. Adjusting the minimum and maximum for blue scanlines. The boxes show the
minimum and maximum value set on each scanline, and used for the next scanline up.
What shou ld t he asymp t ot ic behavior of t his algor it hm be? In t he
aver age case, wit h r and omly d ist r ibut ed represent at ive color s, t he mt h
represent at ive will mod ify approximat ely 1/ m of t he cells in t he map.
The expect ed number of cells mod ied , t herefore, is

2
3k 1
m
1
n

O(2
3k
log(n)).
The algor it hm st ill visit s an appreciable nu mber of u nmod ied cells
(presumably propor t ional t o 2
2k
), so t his number for ms a lower bound on
t he t ime complexit y, and t he obser ved t imes for n < 256 and k 7 d o
not follow t his r ule.
Unfor t unat ely, ver sion 2 of t he algor it hm d oes not prod uce id ent ical
result s t o ver sion 1, because of an aliasing problem. If a d omain is ver y
nar row, it may be missed on some scanlines. Since t he ver sion 2 cod e
exit s as soon as a scanline (for t he green loop) is empt y, any cells lying
past t he empt y scanline will be missed , and will be assigned t o a d ifferent
represent at ive. However, t he nar r owness of t he region t hat caused t he
124
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 124
Figure 4. Aliasing of nar row d omains can cause some cells t o be miscolored by ver sion
2 of the algorithm. On the left is the correct set of pixels in the domain. On the right is the
set of pixels found by version 2. It stops scanning after reaching the rst blank line,
missing t he last pixel at t he t op.
aliasing means t hat t his ot her represent at ive is almost as close as t he
or iginal, so t he effect is negligible. The aliasing problem is illust r at ed in
Figure 4.
Col or map Or der i ng Col or map Or der i ng Col or map Or der i ng Col or map Or der i ng Col or map Or der i ng
Ver sion 2 of t he algor it hm is sensit ive t o t he ord er ing of t he input color s.
2
For example, if t he input color map consist ed solely of gr ays in ord er of
increasing br ight ness, t he loop for each represent at ive would be expect ed
t o visit (m 1)/ m cells, yield ing a t ime complexit y of O(n 2
3k
). The
2
This is similar t o t he anomalous behavior shown by t he Quicksor t algor it hm on
sor t ed input .
125
III.1 EFFICIENT INVERSE COLOR MAP COMPUTATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 125
solut ion is simple: Rand omize t he input values. The shufe algor it hm in
Mor t on (1990) provid es exact ly t he effect need ed here.
Resul t s Resul t s Resul t s Resul t s Resul t s
Figure 5 (see color inser t ) shows a sample comput er-gener at ed image.
The color s in t his image were quant ized t o 256 represent at ive color s. The
cor respond ing inver se color map (k = 6, n = 256) is shown in Figure 1.
See also II.2 A Compar ison of Digit al Halft oning Techniques,
Dale A. Schumacher; II.3 Color Dit hering, Spencer W. Thomas,
Rod ney G. Bogar t ; III.2 Efcient St at ist ic Comput at ions for
Opt imal Color Quant izat ion, Xiaolin Wu; (287) A Simple
Met hod for Color Quant iz at ion: Oct ree Quant iz at ion,
Michael Gervaut z, Werner Purgat hofer
3.1 Figure 1. A color Voronoi diagram. The colors
were derived by quantizing the Christmas tree im-
age in Fig. 5.
3.1 Figure 5. A test image. (See Fig. 1.)
126
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 126
1 k K c S
k
III.2 III.2 III.2 III.2 III.2
E EE EEFFICIENT STATISTICAL FFICIENT STATISTICAL FFICIENT STATISTICAL FFICIENT STATISTICAL FFICIENT STATISTICAL
C CC CCOMPUTATIONS FOR OPTIMAL OMPUTATIONS FOR OPTIMAL OMPUTATIONS FOR OPTIMAL OMPUTATIONS FOR OPTIMAL OMPUTATIONS FOR OPTIMAL
C CC CCOLOR QUANTIZATION OLOR QUANTIZATION OLOR QUANTIZATION OLOR QUANTIZATION OLOR QUANTIZATION
Xiaolin Wu
Universit y of West ern Ont ario
London , Ont ario, Canada
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Color qu ant izat ion is a mu st when u sing an inexp ensive 8-bit color
d isplay t o d isplay high-qualit y color images. Even when 24-bit full color
d isplays become commonplace in t he fut ure, quant izat ion st ill is impor-
t ant because it lead s t o signicant image d at a compression, making ext r a
fr ame buffer available for animat ion and red ucing band wid t h require-
ment s (a bot t leneck when we go for HDTV).
Color quant izat ion is a 3D clust er ing process. A color image in an RGB
mod e cor respond s t o a t hree-d imensional d iscret e d ensit y P(c), where
c = (c
r
, c
g
, c
b
) in RGB space. The int ensit y of each pr imar y color oft en is
d iscret e and encod ed by m bit s; hence, P(c) is d ened on a cubic lat t ice
S of 2
m
2
m
2
m
point s. In color image quant izat ion, t he point set S is
par t it ioned int o K subset s S
k
, 1 k K,

cS
k
P(c) (c) 0,
U

1 < k < k
S
k
=
S, S
j

I
jk
S
k
= , and all color s c S
k
are mapped t o a represent at ive
color, q
k
= (q
kr
,q
kg
,q
kb
) Given su ch a p ar t it ion, t he exp ect ed qu ant iza-
t ion er ror is d ened as
E(S
1
, S
2
,, S
K
) =



P(c)

(c q
k
), (1)
where

is a d issimilar it y measure bet ween c and q


k
. A suit able

for
human percept ion of color s is a research t opic beyond t he scope of t his
127
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 127
paper. The ubiquit ous mean-square er ror measure is used in t he following
d evelopment ; but t est images, not just numer ical er ror s, are used for t he
read er t o jud ge t he image qualit y.
Id eally, one would like t o minimize Eq. (1) for given P(c),

, and K.
The fact t hat t here are approaching K
| S|
d ifferent par t it ions (And er berg,
1973) makes opt imal quant izat ion a challenging problem for algor it hm
d esign. Many heur ist ic algor it hms were pr oposed for color quant izat ion:
Heckber t s med ian-cut algor it hm (1982), t he Wu-Wit t en (1985) and Wan
et al. (1988) var iance-based algor it hms, and t he Ger vaut z-Purgat hofer
oct ree-based algor it hm (1990). The med ian-cut algor it hm par t it ions t he
color sp ace int o K boxes, each of which cont ains ap p r oximat ely t he
same nu mber of p ixels. This ap p r oach is bet t er t han nave u nifor m
quant izat ion, but far from t he goal of minimizing Eq. (1). Int uit ively, for
t he same pixel populat ion, a large box should be allocat ed more repre-
sent at ive color s t han a small one; i.e., t he var iance shou ld p lay an
impor t ant role. Wu and Wit t en d eveloped a d ivid e-and -conquer st r at egy
t o minimize t he marginal var iance in par t it ioning t he color space, and t his
wor k was improved by Wan et al. However, t he sole reason for minimiz-
ing t he marginal var iance inst ead of t rue var iance was t hat we d id not
have an efcient way t o comput e t hree-d imensional color st at ist ics t hen.
This problem will be solved in t his gem, and consequent ly, opt imizing
color quant izat ion will become comput at ionally feasible.
Quant i zat i on Based on Var i ance Mi ni mi zat i on Quant i zat i on Based on Var i ance Mi ni mi zat i on Quant i zat i on Based on Var i ance Mi ni mi zat i on Quant i zat i on Based on Var i ance Mi ni mi zat i on Quant i zat i on Based on Var i ance Mi ni mi zat i on
Color quant izat ion is opt imized t hrough a linear search. We sweep a
cut t ing plane across t he RGB cube per pend icular ly t o t he R, G, B axes
separ at ely, and choose t he plane t hat minimizes t he sum of var iances at
bot h sid es t o cut t he cube int o t wo boxes. Next , t he box wit h t he larger
var iance is p ar t it ioned int o t wo smaller boxes by t he same cu t t ing
cr it er ion, and so for t h, unt il K boxes are for med . The K means (cent er s
of gr avit y) of t hose K boxes are select ed as K represent at ive color s.
In t he preced ing minimizat ion process, for each possible cut t ing posi-
t ion in ever y d irect ion, we need t o evaluat e t he var iances at bot h sid es.
Wit hout an efcient algor it hm for such st at ist ical evaluat ions, t he pro-
posed opt imizat ion is impr act ical.
128
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 128
Ef f i ci ent Comput at i ons of Col or St at i st i cs Ef f i ci ent Comput at i ons of Col or St at i st i cs Ef f i ci ent Comput at i ons of Col or St at i st i cs Ef f i ci ent Comput at i ons of Col or St at i st i cs Ef f i ci ent Comput at i ons of Col or St at i st i cs
In t his sect ion, we will show how t he mean and t he var iance of any
rect angu lar box cont aining n color point s may be compu t ed , respec-
t ively, in O(1) t ime wit h an O(|S|) t ime preprocessing.
Let c
i
= (c
ir
, c
ig
, c
ib
) and c
j
= (c
jr
, c
jg
, c
jb
) be t he t wo point s in t he
cu bic lat t ice S. We say t hat c
j
d ominat es c
i
, d enot ed by c
j


f ci, if
c
jr
> c
ir
, c
jg
> c
ig
, and c
jb
> c
ib
hold simu lt aneou sly. Any pair c
i
and
c
j
, wh er e c
j

f
c
i
, d en es a t h r ee-d i men si on a l box (c
i
, c
j
] i n t h e
d i scr et e col or sp a ce, wi t h i t s r, g, a n d b i n t er va l bei n g (c
ir
, c
jr
],
(c
ig
, c
jg
], and (c
ib
, c
jb
]. Not ice t hat t hese int er vals are open on t he left
but closed on t he r ight ; i.e., t he lower, left , and front faces of t he box are
exclud ed , while t he upper, r ight , and back faces are includ ed .
If all color s c (c
i
, c
j
] ar e quant ized t o q = (q
r
, q
g
, q
b
), t hen und er
t he mean-squ are er r or measu r e, t he exp ect ed qu ant izat ion er ror for

(c
i
, c
j
] is d ened by

E c
i
,
(
c
j
]
]
]
P

(c)(cq)
2
,
(2)
where (c q)
2
= (c q)(c q)
T
is t he squared Euclid ean d ist ance be-
t ween c and q. It is easy t o show t hat Eq. (2) is minimized if t he
represent at ive color q is set t o t he mean (c
i
, c
j
] of t he box(c
i
, c
j
], i.e.,
q = (c
i
,c
j
] =


c ( c
i
c
j
]

c ( c
i
c
j
]
Denot e t he eight ver t ices of t he box (c
i
, c
j
] by
v
0
= (c
ir
,c
ig
,c
ib
), v
4
= (c
jr
,c
ig
,c
ib
),
v
1
= (c
ir
,c
ig
,c
ib
), v
5
= (c
jr
,c
ig
,c
jb
),
v
2
= (c
ir
,c
jg
,c
ib
), v
6
= (c
jr
,c
jg
,c
ib
),
v
3
= (c
ir
,c
jg
,c
jb
), v
7
= (c
jr
,c
jg
,c
jb
,)

c ( c
i
c
j
]
. (3)
P(c)
cP(c)
129
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 129

(4)
(5)
(7)
(6)
f(c)P(c)
Then by t he basic rule of inclusion-exclusion of combinat or ics (Liu,
1968), we have
c ( c
i
, c
j
]

c (o, v
6
] c (o, v
6
] c (o, v
5
] c (o, v
4
]

c (o, v
3
] c (o, v
2
] c (o, v
1
] c (o, v
0
]
]
]
]
]
f(c)P(c).
In t he preced ing, vect or o is a reference point such t hat

c (, o]
P(c) 0.
A gr aphical explanat ion of Eq. (4) is given in Fig. 1.
Since P(c) is d ened on t he nit e lat t ice S, one can pre-comput e and
st ore t he quant it ies,

c (o, c
t
]
f (c)P(c),
for all c
t
S. Then t he su mmat ion

c c
i
, c
j ( ]
f (c)P(c) can be d one in
O(1) t ime by Eq. (4), ind epend ent of t he size of (c
i
, c
j
]. Now subst it ut e
f(c) wit h c
d
, d = 0, 1, 2, where c
0
= 1 and c
2
= cc
T
, and d ene

M
d
(c
t
)
c ( o , c
t
]
c
d
P(c).
Then, given a box (c
i
, c
j
], it s color populat ion w(c
i
, c
j
], mean (c
i
, c
j
],
130
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 130
Figur e 1. Inclusion-exclusion comput at ions in color space.
and quant izat ion er ror E(c
i
,c
j
] (t he weight ed var iance of t he box),

w(c
i
, c
j
]
c ( o
i
, c
j
]
P(c)

(c
i
, c
j ]

c ( o
i
, c
j
]
cP(c)
w(c
i
, c
j
]

E(c
i
, c
j
] c
2
P(c)
c(c
i
,c
j
]

cP(c)
c(c
i
,c
j
]

]
]
]
]
w(c
i
, c
j
]
2
(8)
(9)
(10)
131
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 131
can be comp u t ed in O(1) t ime u sing Eq. (4), p rovid ed t hat M
d
(c),
d = 0, 1, 2, t he cumulat ive dt h moment s of t he d iscret e d ensit y P(c)
against t he reference point o, are pre-comput ed and st ored for all |S| =
2
3m
lat t ice point s of S. Clear ly, t his preprocessing requires O(|S|) t ime
and space.
If t he or iginal 24-bit pixel image was quant ized d irect ly, t hen |S| = 2
24
,
invoking excessive if not prohibit ive cost s. Encour agingly, it was ob-
ser ved by p r eviou s resear cher s and by t he au t hor t hat color image
quant izat ion on a 32 32 32 rgb lat t ice yield s visually almost t he same
result as on a 256 256 256 lat t ice. Thus, t he preprocessing t ime and
space cost s can be red uced t o an accept able level of |S| = 2
15
wit hout
not iceable loss of d elit y.
Al gor i t hm Det ai l s and Anal ysi s Al gor i t hm Det ai l s and Anal ysi s Al gor i t hm Det ai l s and Anal ysi s Al gor i t hm Det ai l s and Anal ysi s Al gor i t hm Det ai l s and Anal ysi s
For mally, opt imizing t he cut t ing of t he box (c
i
, c
j
] is minimizing
E(c
i
, c] + E(c,c
j
],
subject t o
c {c
jr
c
jg
(c
ib
, c
Jb
]} {c
jr
(c
ig
, c
jg
] c
jb
}
{(c
ir
, c
jr
] c
jg
c
jb
}.
Wit h t he aid of t he proposed preprocessing, Eq. (11) can be evaluat ed
in O(1) t ime, given Q(c
i
,c
j
] and c. Then it can be easily shown t hat
p ar t it ioning S int o K boxes based on var iance minimizat ion need s
O(| S|
1/ 3
K) t ime in t he wor st case and O(| S|
1/ 3
K
2/ 3
) t ime
1
in t he aver age
case.
1
Obt ained by solving t he r ecu r r ence, T(n) = 2T(n/2) + 3n
1/3
, for t he bou nd ar y con-
d it ion T(| S| /K)= 0.
(11)
(12)
132
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 132
c (

c
i
, c
j
]
Not e, however, t hat t he preced ing analysis only gives t he ord er of t ime
complexit y of t he proposed algor it hm, wit h no consid er at ion of t he
coefficient before t he O not at ion. Direct ly minimizing Eq. (11) would
require as many as 76 ad d it ions, six mult iplicat ions, and t wo d ivisions for
a single c. However, since
E(c
i
,c] + E(c,c
j
] =

c
2
P(c)

cP(c)
c (c
i
, c]

]
]
]
2
w(c
i
, c]

cP(c)
c (c, c
j
]

]
]
]
w(c, c
j
]
, (13)
minimizing Eq. (11) is equivalent t o maximizing


cP(c)
c (c
i
, c]

]
]
]
2
w(c
i
, c]
+
cP(c)
c (c, c
j
]

]
]
]
w(c, c
j
]
2

cP(c)
c(c
i
,c]

]
]
]
]
2
w(c
i
,c]
+

cP(c)
c(c
i
,c]

cP(c)
c(c
i
,c]

]
]
]
]
w(c,c
j
]w(c
i
,c]
2
(14)
As w(c
i
,c
j
] and
c (

c
i
, c
j
]
cP(c) are const ant s for a fixed box (c
i
, c
j
],
we only need t o apply t he inclusion-exclusion rule Eq.(4) t o comput e t he
summat ions
c (

c
i
, c ]
cP(c) and w(c
i
,c] for c of Eq.(12) in t he process
of maximizing Eq.(14). Fur t her more, since four of eight M
d
(c) involved
in Eq.(4) d o not change when c t akes on d ifferent values in one of t hree
set s c
jr
c
jg
(c
ib
, c
jb
], c
jr
(c
ig
, c
jg
] c
jb
, and (c
ir
, c
jr
] c
jg

c
jb
only four ad d it ions are required by w(c
i
,c] and 12 ad d it ions by

c (

c
i
, c ]
cP(c). (Not e t hat t he lat t er is a 3-vect or ). Aft er t he preced ing
manipulat ions t he new algor it hm requires 25 ad d it ions, six mult iplica-
t ions, and t wo d ivisions per it er at ion.
133
III.2 EFFICIENT STATISTICAL COMPUTATIONS FOR OPTIMAL COLOR QUANTIZATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 133
Exper i ment al Resul t s Exper i ment al Resul t s Exper i ment al Resul t s Exper i ment al Resul t s Exper i ment al Resul t s
The new opt imal color quant izat ion algor it hm was implement ed on a SUN
3/ 80 wor kst at ion. It t ook only 10 second s t o qu ant ize a 256 256
image. The impact of opt imizing par t it ions is ver y posit ive. The new
algor it hm achieved , on aver age, one-t hird and one-nint h of mean-square
er ror s for t he med ian-cut and Wan et al. algor it hms respect ively.
Shown in Fig. 2 (see color inser t ) is a set of phot os of a quant ized ISO
color t est image. The pict ure in (a) has 256 color s and is quant ized by
t he proposed algor it hm. This image is vir t ually ind ist inguishable from t he
or iginal 24-bit pixel image. In (b) is t he 64-color image quant ized by t he
proposed algor it hm. It s qualit y is accept able. For compar ison, we also
show in (c) and (d ) t he 64-color images qu ant ized by t he Heckber t
med ian-cut and Wan et al. algor it hms. The improvement on image qualit y
by t he new algor it hm over t he previous algor it hms is evid ent .
See also II.2 A Compar ison of Digit al Halft oning Techniques,
Dale A. Schumacher ; II.3 Color Dit her ing, Spencer W. Thomas,
Rod ney G. Bogar t ; III.1 Efcient Inver se Color Map Comput a-
t ion, Spencer W. Thomas; (287) A Simple Met hod for Quant i-
z at ion: Oct ree Quant iz at ion, Michael Gerv aut z , Werner
Purgat hofer
3.2 Figure 2. (a) 256-color image quantized by Wus algorithm; (b) 64-color image quantized by Wus algo-
rithm; (c) 64-color image quantized by Heckberts algorithm; (d) 64-color image quanitized Wu the Wan et al.
algorithm.
(a)
(b)
(c)
(d)
134
III.3 A RANDOM COLOR MAP ANIMATION ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 134
III.3 III.3 III.3 III.3 III.3
A AA AA RANDOM COLOR MAP RANDOM COLOR MAP RANDOM COLOR MAP RANDOM COLOR MAP RANDOM COLOR MAP
A AA AANIMATION ALGORITHM NIMATION ALGORITHM NIMATION ALGORITHM NIMATION ALGORITHM NIMATION ALGORITHM
Ken Musgrave
Yale Universit y
New Haven, Connect icut
Color ing d et er minist ic fr act als such as Mand elbrot and Julia set s is a
t ime-consuming process. This process can be aut omat ed wit h a r and om
color map animat ion algor it hm t hat gives quit e st r iking result s as seen in
t h e col or p l a t es I. 7. 1 a n d I. 7. 2. Col or ma p a n i ma t i on ma kes
it er at ion-fr act al images come alive and ad d s consid er able viewing int er-
est ; applied t o more ord inar y images, it can give bizar re and ent er t aining
effect s and somet imes can reveal d at a not read ily apparent wit h a xed
color map.
The id ea behind t his algor it hm is simple: Gener at e r and om sawt oot h
waves in red , green, and blue on t he y (Fig. 1), and push t he result ing
color r amps t hrough t he color look-up t able. One can t hink of t he look-up
t able as a wind ow slid ing along t he t r ace of t he r and om RGB sawt oot h
waves. The power of t he algor it hm d er ives from t he fact t hat t he color
r amps are gener at ed on t he y, and t hus need not be st ored . User input is
limit ed t o a st ar t ing seed for t he und er lying r and om number gener at or
and par amet er s for t he st at ist ics of t he r and om r amps. (These par amet er s
can be built in, of cour se.) The progr amming wor k involves t he creat ion
of r and om-number gener at ion rout ines wit h specic st at ist ical char act er
t o be used in specifying t he color r amps, and t he int er polat ion of t he
r amps once end point s have been specied .
For a r st cut , ver y nice result s can be had by using unifor m r and om
number s t o specify t he r amp end point s, and linear int er polat ion for t he
r amps. In fact , one simply can per for m a r and om walk in color space
(cor respond ing, appropr iat ely enough, t o Brownian mot ion) and not have
t o per for m any int er polat ion at all. The choice of color space (e.g., RGB,
135
III.3 A RANDOM COLOR MAP ANIMATION ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 135
Figur e 1.
HLS, et c.) is up t o t he progr ammer ; we always have used t he RGB color
space. Linear int er polat ion of color r amps can be per for med efcient ly
using a bit of st and ard DDA cod e, which you alread y may have lying
around somewhere, or can easily lift from a basic comput er gr aphics t ext .
The algor it hm proceed s as follows:
0. Opt ionally, load a st ar t ing color map, such as a zebr a-st r iped grey
r amp.
1. Get values from t he r and om-number gener at or for r amp end point s.
Scale t h ese valu es t o r ep r esen t in t en sit y (i.e., 0255) an d r amp
lengt h. Maximum r amp lengt h is a user opt ion.
2. Assuming init ial r amps st ar t and zero int ensit y, shift [0, 0, 0] int o t he
low end of t he color map.
136
III.3 A RANDOM COLOR MAP ANIMATION ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 136
3. Unt il t he end of t he t ext (i.e., red , green, or blue) r amp is reached ,
shift next int er polat ed color t uple int o t he color map.
4. Choose end p oint for next r amp of t he color r amp t hat has been
exhaust ed , and go t o st ep 3. Int er polat e new r amp st ar t ing from t he
end point of t he last r amp.
Not e t hat you may wish t o leave t he bot t om or t op color map ent r y, which
color s t he int er ior of t he M-set or J-set , fixed at some color such as
black.
On mod er n hard ware, t he ent ire process oft en proceed s t oo r apid ly,
and some means, such as specificat ion of no-ops, must be found t o slow
t he animat ion d own t o a reasonable speed . A problem oft en encount ered
in implement at ion on a specific plat for m is sid e effect s from wr it ing t o t he
color look-up t able d ur ing nonver t ical-ret r ace t ime; t his will show up
t ypically as a flicker ing noise in t he d isplay. Thus, one may have t o go
int o low-level inst ruct ions for t he fr ame buffer hard ware t o find an
inst ruct ion t hat will assure t hat t he wr it ing occur s only d ur ing ver t ical
ret r ace t ime. Per sonal exper ience ind icat es t hat when such an inst ruct ion
exist s, it oft en d oes not wor k as ad ver t ised , and t hat inclusion of no-ops
t o slow t he execut ion usually d oes t he t r ick.
Fun can be had in playing wit h t he st at ist ics of t he r and om-number
gener at or. Tr y Gaussian r and om number s in t he int er val [0,255] wit h a
mean of 127 for a past el color map animat ion (more t ast eful, but less
spect acular ). Taking Gaussian r and om numbers in t he int er val
[ 256, 255] wit h mean 0 and ad d ing 256 t o negat ive inst ances gives a
loud , t ast eless, post mod er n animat ion. Tr y nonlinear, e.g., cubic spline,
int er polat ion of t he color r amps. (We have found t his gener ally less
visually st r iking t han linear int er polat ion.) Tr y rever sing t he d irect ion of
t he animat ion (r and omly). Tr y d ifferent st ar t ing mapsit t akes a while t o
fill t he color map wit h t he r and om animat ion, but t he built -in ant icipat ionis
a nice feat ure. A zebr a-st r iped gr ay r amp, wit h st r ipes of wid t h 2 or 3 is
nice. (A wid t h of 1 gener ally is ver y hard on t he eyes.)
While t he animat ion is, in pr inciple, per iod ic,t he per iod of t he se-
quence is on t he ord er of one d ay for a 16-bit r and om-number gener at or
and about 100 year s for a 32-bit gener at or.
137
III.3 A RANDOM COLOR MAP ANIMATION ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 137
Should libr ar y r and om-number gener at or s be unavailable or t oo slow,
here is one t hat wor ks ne:
#dene MULTIPLIER 25173
#dene INCREMENT 13849
#dene MODULUS 65535A
/ *
* pseudo-random number generat or; period 65536; requires seed bet ween
*/ 0 and 65535; ret ur ns r and om number s bet ween 0 and 65536.
#dene RANDOM(x) (x = (MULTIPLIER * x + INCREMENT) & MODU-
LUS)
138
III.4 A FAST APROACH TO PHIGS PLUS PSEUDO COLOR MAPPING
GRAPHICS GEMS II Edit ed by JAMES ARVO 138
III.4 III.4 III.4 III.4 III.4
A AA AA FAST APPROACH TO PHIGS FAST APPROACH TO PHIGS FAST APPROACH TO PHIGS FAST APPROACH TO PHIGS FAST APPROACH TO PHIGS
P PP PPLUS PSEUDO COLOR LUS PSEUDO COLOR LUS PSEUDO COLOR LUS PSEUDO COLOR LUS PSEUDO COLOR
M MM MMAPPING APPING APPING APPING APPING
James Hall and Terence Lindgren
Prime CV
Bedf ord, Massachuset t s
models: true color mapping, pseudo color mapping and pseudo N color
mapping. In all three cases, the color mapping stage receives primitives
from the lighting and depth cueing stages with a color vector per vertex.
Then, for int er ior shad ing met hod COLOR, t he color map p ing st age
interpolates the colors across the primitive and maps the resulting colors
accor d ing t o t he select ed color map p ing met hod . True color mapping
set s t he resu lt ing color u sing eit her a closest t , d it her ing, or d irect ly
set t ing t he color d ep end ing on t he p ixel d ep t h of t he machine. If we
assume that the colors are received in a normalized RGB format, then the
pseud o color mapping will map t he color vect or ont o an ind ex t hat is
used to select an entry from a list of colors. The major problem with this
scheme is t hat it u ses t hr ee int er p olat or s and combines t he r esu lt ing
colors into an index for each pixel as we traverse the primitive. We show
t hat it is possible by mapping t he color s at t he ver t ices r st t o simply
interpolate the indices at each vertex.
Pseudo Col or Mappi ng Pseudo Col or Mappi ng Pseudo Col or Mappi ng Pseudo Col or Mappi ng Pseudo Col or Mappi ng
Th e PHIGS PLUS sp eci ca t i on d en es pseudo color mapping a s a
met hod t hat conver t s color s int o a single int eger ind ex t hat is used t o
select a color from a list of specied color s in a d at a record . The d at a
record cont ains a weight ing vect or [Wl , W2, W3] (for RGB color for mat )
PHIGS PLUS allows an applicat ion t o select bet ween t hree color mapping
139
III.4 A FAST APROACH TO PHIGS PLUS PSEUDO COLOR MAPPING
GRAPHICS GEMS II Edit ed by JAMES ARVO 139
and a list of R color s. Not e t hat an ind ex of 1 cor respond s t o t he r st
color on t he list . Assuming an RGB color mod el for bot h t he rend er ing
color mod el and t he color mapping color mod el, t he mapping processmay
be d ened as follows:
1. Nor malize t he weight ing vect or W by d ivid ing it by t he sum of it s
component s. (This oper at ion is ind epend ent of t he int er polat ion pro-
cess and may be d one when t he weight ing vect or is d ened .)
2. Ca l cu l a t e J = r ou n d ((R1)(Wl *Cl + W2*C2 + W3*C3) + 1)
(where [Cl , C2, C3] = [red , green, blue])
3. Use J as an ind ex t o select one of t he ent r ies in t he list of color s.
4. The select ed color t hen is d isplayed on t he wor kst at ion as accur at ely
as possible.
How accur at ely t he color s are d isplayed on t he wor kst at ion is d et er mined
by t he capabilit ies of t he und er lying wor kst at ion. For t rue color wor kst a-
t ions, whose p ixel memor y is d isp layed d irect ly, map p ed color s are
refor mat t ed t o t he cor rect pixel layout and out put t o t he fr ame buffer. For
pseud o color wor kst at ions, wit h a smaller fr ame buffer resolut ion whose
out put is mapped t hrough a color look-up t able (LUT), it is more an issue
of how t he LUT is managed . Since we must suppor t bot h t rue and pseud o
color mapping, at least some par t of t he LUT must cont ain a color cube t o
suppor t eit her a closest -t or d it her scheme. If we creat e t he largest
possible color cube t hat t he LUT size will allow, t hen we will get a
higher-qualit y approximat ion of t rue color at t he cost of approximat ing
t he pseud o ent r ies. Consequent ly, aft er applying t he pseud o color map-
ping, we must get t he color from t he color list and approximat e it based
on t he cur rent color cube. We would obt ain much bet t er per for mance if
we d irect ly load t he color list s int o t he LUT so t hat t he color ind ices could
be wr it t en immed iat ely int o t he fr ame buffer. Most applicat ions t end t o
use only one of t he color mapping met hod s, so a reasonable approach
would be t o prescan t he wor kst at ion color mapping t able and load t he
pseud o color list s int o t he hard war e LUT, and use t he remaining space t o
t a color cube. In t his fashion, if no pseud o color mappings are used , we
would get a large color cube and a higher-qualit y t rue color approxima-
140
III.4 A FAST APROACH TO PHIGS PLUS PSEUDO COLOR MAPPING
GRAPHICS GEMS II Edit ed by JAMES ARVO 140
t ion. As t he number of pseud o color mappings increases, t he qualit y of
t he t rue color emulat ion would d ecrease (as well as t he likelihood t hat it
would be used ).
Pseudo Col or Int er pol at i on Pseudo Col or Int er pol at i on Pseudo Col or Int er pol at i on Pseudo Col or Int er pol at i on Pseudo Col or Int er pol at i on
In t his sect ion, we d escr ibe t he int er polat ion of color s along a line and
show t hat it is possible t o map t he color s at t he end point s pr ior t o
int er polat ion, inst ead of int er polat ing t he end point color s and t hen map-
ping. We not e t hat t his process can be ext end ed t o ll areas (polygons) by
int er polat ing t he mapped color s along t he polygon ed ges and per for ming
scanline int er polat ion bet ween t hem. We can d escr ibe t he int er polat ion of
color s along a line wit h end point s P1 (x1, y1, C1) and P2(x2, y2, C2)
by:
C = t *C1 + (1 t )*C2, (1)
where
Cl = [r1, g1, b1] and C2 = [r2, g2, b2].
The color mapping process t hen is d ened by:
i = round ((R 1)(W1*r + W2*g + W3*b) + 1).
We can swit ch t o vect or not at ion and incor por at e (R 1) int o W,
W = W*(R 1),
i = round ((W, C)) + 1 , (2)
i = round ((W, t *C1 + (1 t )*C2) + 1 ,
i = round (t *(W, C1) + (1 t )*(W, C2)) + 1 (3)
This shows t hat mapping t he color s pr ior t o int er polat ion is id ent ical t o
combining Eqs. (1) and (2),
d ist r ibut ing
141
III.4 A FAST APROACH TO PHIGS PLUS PSEUDO COLOR MAPPING
GRAPHICS GEMS II Edit ed by JAMES ARVO 141
int er polat ing t he color s and t hen per for ming t he pseud o color mapping;
which means t hat we can swit ch accur at ely t o a single int er polat ion
var iable for t he pseud o color int er polat ion process.
The opt imizat ion out lined saves for each pixel four ad d it ions and t hree
mult iplicat ions, where t wo of t he ad d it ions are associat ed wit h upd at ing
t he t wo ext r a int er polat ion var iables and t he ot her t wo are associat ed
wit h t he mapping oper at ion. Moreover, we eliminat e t wo d ivid es associ-
at ed wit h t he t wo ext r a int er polat ion d er ivat ives.
Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on
An implement at ion of t his scheme might prescan t he wor kst at ion color
mapping t able and load t he color list s int o t he hard ware look-up t able.
This r equ ir es associat ing wit h each color map p ing met hod ent r y a
lut _st art d escr ibing where in t he LUT t he color list was load ed . Relocat -
ing t he list in t his fashion allows us t o d rop t he +1 in Eq. (3), since t he
r st ent r y in t he list now is at lut _st art . Ad d it ionally inst ead of represent -
ing t he ind ex values as real and round ing when per for ming t he or iginal
mapping of t he ver t ices, we scaled t he values by 4096.0 and round ed so
t hat t he ind ices were in an 8.12-int eger for mat . This allows us t o subst i-
t ut e t he round in Eq. (3) wit h a shift r ight by 12, fur t her increasing t he
per for mance. The following pseud o-cod e gives a gener al over view of an
implement at ion:
assume we haue a current color mapping st at e wit h t he following
format
Record color _mapping_t able_ent r y
begi n
w1, w2, w3: real ; weight ing vect or wit h (R 1) incorpo-
rat ed
st ar t _lut : i nteger st art ing lut index
end;
shaded_l i ne(x1, y1, x2, y2, c1, c2) assuming x is t he major axis
where (x1, y1) and (x2, y2) are t he endpoint s of t he line and c1
and c2 are t he colors (red, green, blue) at t hose point s
142
III.4 A FAST APROACH TO PHIGS PLUS PSEUDO COLOR MAPPING
GRAPHICS GEMS II Edit ed by JAMES ARVO 142
begi n
map t he color at t he input endpoint s
i1 st ar t _lut *4096 + (w1*c1.red + w2*c1.green + w3*c1.blue)*4096;
i2 st ar t _lut *4096 + (w1*c2.red + w2*c2.green + w3*c2.blue)*4096;
d id x (i2i1)/ (x2 x1); comput e color derivat ive
i round (i1); comput e st art ing color
for each pixel
begi n
plot (x, y, shift _r ight (i,12)); plot t he current color
i i + d id x; updat e for next pixel
end
end
143
III.5 MAPPING RGB TRIPLES ONTO 16 DISTINCT VALUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 143
III.5 III.5 III.5 III.5 III.5
M MM MMAPPING RGB TRIPLES ONTO APPING RGB TRIPLES ONTO APPING RGB TRIPLES ONTO APPING RGB TRIPLES ONTO APPING RGB TRIPLES ONTO
1 6 1 6 1 6 1 6 1 6 DISTINCT VALUES DISTINCT VALUES DISTINCT VALUES DISTINCT VALUES DISTINCT VALUES
Alan W. Paet h
NeuralWare, Inc.
Pit t sburgh, Pennsylvania
A previous gem by t he aut hor (Paet h, 1990a) d escr ibed a high-speed
mapping from ar bit r ar y RGB color d escr ipt or s ont o one of 14 values,
useful for creat ing four-bit pixel ind ices. This ent r y ext end s t he t echnique
in compat ible fashion t o 16 values by placing t wo mid -level gr ay values.
The d er ivat ion once again t akes ad vant age of d escr ipt ive solid geomet r y
in locat ing t he nearest (Euclid ean) t arget point t o input point . Figure 1
illust r at es t he par t it ioning of 3-space int o 16 regions. Figure 2 illust r at es
t he quant izat ion of color t r iples und er t he algor it hm.
High-speed mapping ont o a small set of t hree-component d escr ipt or s
may be achieved by t he par t it ioning of t he unit cube int o subregions. This
has a gener al applicat ion in recod ing 3-vect or s (color t r iples, sur face
nor mals) at red uced precision in symmet r ic fashion. Specically, planes
nor mal t o t he cubes four bod y d iagonals (Paet h, 1990e, Fig. 6b) for m 14
space par t it ions.
As t hese planes are par allel neit her t o t he axes nor t o each ot her,
axis-separ able algebr aic met hod s (Paet h, 1990f, p. 254), which are con-
vent ionally used for quant izat ion of larger color spaces (Ger vaut z and
Purgat hofer, 1990), must yield t o non-Car t esian mod els, t he lat t er easily
represent ed geomet r ically. This d issect ion is relat ed t o t he face locat ions
of t he cuboct ahed ron. (The lat t er are present ed in Gem Exact Met r ics
for Regular Convex Solid s, lat er in t his book (Paet h, IV.3).)
The ver t ices of t he for mer solid are ret ained t o allow upward com-
pat ibilit y. This preser ves t he pr imar y color s of t he cubes ver t ices at
(
t
1,
t
1,
t
1), which are essent ial t o many algor it hms. (See also Paet h
(1990f, Fig. 9).) Unfor t u nat ely, sp ace p ar t it ioning by p roject ion ont o
spher ical polyhed r a places no int er ior point s: Gr ays in par t icular are
144
III.5 MAPPING RGB TRIPLES ONTO 16 DISTINCT VALUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 144
absent . Wor se, St einer s t heorem from 1888 (republished in 1971) ind i-
cat es t hat four ar bit r ar y skew planes may for m no more t han 15 3-space
par t it ions: P
3
(n) = 1/ 6 [n
3
+ 5n + 6].
The ad d it ion of t wo gr ay point s ext end s t he d escr ipt or t able usefully: A
unifor m, linear set of four achromat ic values allows t he d irect rend er ing
of monochromat ic images of t wo bit s, plus t heir mult iples (Paet h, 1990b,
p . 250). Th e i n t er i or cod es a r e a t

1
3

1
3

1
3
( )
a n d

2
3

2
3

2
3
( )
Ta bl e I i s t h e
upd at ed color d escr ipt or t able.
Table 1.
Cod e Name Red Green Blue Volume
0000 black 0 0 0 1/ 48
0001 olive 1/ 2 1/ 2 0 1/ 12
0010 pur ple 1/ 2 0 1/ 2 1/ 12
0011 red 1 0 0 1/ 16
0100 aqua 0 1/ 2 1/ 2 1/ 12
0101 green 0 1 0 1/ 16
0110 blue 0 0 1 1/ 16
0111 l t gray 1/3 1/3 1/3 1/24
1000 dk gray 2/3 2/3 2/3 1/24
1001 yellow 1 1 0 1/ 16
1010 magent a 1 0 1 1/ 16
1011 pink 1 1/ 2 1/ 2 1/ 12
1100 cyan 0 1 1 1/ 16
1101 lime 1/ 2 1 1/ 12 1/ 12
1110 sky 1/ 2 1/ 2 1 1/ 12
1111 whit e 1 1 1 1/ 48
Comput at ion of t he nearest axial gr ay d escr ipt or

c
3

c
3

c
3
( )
for any point
in RGB space uses t he equat ion, c = 1/ 3

(R + G + B + .5)

]
]
] , valid for all
space. This resembles t he r st half-plane equat ion of t he previous algo-
r it hm: t he t est used t o bisect t he gr ay axis. To ext end t hat algor it hm, t he
bi t-oring op er at ions t hat r ecord fou r fold half-sp ace member ship are
per mut ed (wit h t he t est s not being coupled ), placing t he gr ay t est in
fou r t h posit ion. When t he t hree preced ing boolean t est s for cod e-bit
posit ions 2
0
2
1
and 2
2
yield like sign, t he nal t est wit h boolean result in
145
III.5 MAPPING RGB TRIPLES ONTO 16 DISTINCT VALUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 145
bit 2
3
may be omit t ed : Cod e word s 0000 (black) and 1111 (whit e)
must result ; cod es 1000 and 0111 are inad missible. In cases of like
sign, t he t est point is localized t o t he black or whit e par t it ion at t he
conclusion of t he t hird t est .
When t hese cond it ions ar ise, t he four t h half-plane t est may be ad just ed
(at execut ion t ime) by par allel d isplacement , recast ing it in t he for m of a
t wo-bit gr ay axis quant izat ion t est . Point s lying t oward t he int er ior are
p l a ced i n d a r k gr a y-l i gh t gr a y su br egi on s sp l i t fr om t h e p a r en t
black-whit e volumes. These are represent ed convenient ly by t he previ-
ously unoccupied cod e word s. Cond it ional execut ion of t he ad just ment
st ep pr ior t o t he four t h plane t est provid es opt ional run-t ime back-compa-
t ibilit y, as seen in t he following pseud o-cod e. (See also t he C Implement a-
t ion in Append ix 2.)
i nteger funct ion remap16(R, G, B, R, G, B: real )
r val, gval, bval,: array [0..15] of real ;
r val {0.,.5 ,.5, 1.,0., 0., 0.,.333, .667, 1., 1., 1., 0.,.5 ,.5,1.}
gval {0.,.5, 0., 0.,.5, 1., 0.,.333, .667, 1., 0.,.5, 1., 1.,.5,1.}
bval {0., 0.,.5, 0.,.5, 0., 1.,.333, .667, 0., 1.,.5, 1.,.5,1.,1.}
d ist : real 0.5;
cod e, mask: i nteger 0;
i f R + G B > d ist then cod e cod e bi t-or 1
i f R G + B > d ist then cod e cod e bi t-or 2
i f R + G + B > d ist then cod e cod e bi t-or 4
d ist 1.5; mask 8;
The next t wo lines updat e t he algorit hm and may be compiled
or execut ed condit ionally t o provide back-compat ibilit y:
i f (cod e = 0) then {d ist .5; mask 7;}
el se i f (cod e = 7) then {cod e 8; d ist 2.5; mask 7;}
i f R + G + B > d ist then cod e cod e bi t-or mask;
R = r val[cod e]
G = gval[cod e]
B = bval[cod e]
return[cod e]
146
III.5 MAPPING RGB TRIPLES ONTO 16 DISTINCT VALUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 146
This yield s an upward -compat ible algor it hm useful wit h old d at a set s.
As before, monochromat ic t r iples (c, c, c) yield monochromat ic out put .
No cent r al gr ay color is present : Innit esimal t est excur sions away from
t he cubess cent er at (1/ 2, 1/ 2, 1/ 2) yield 14 d ist inct color s, includ ing
t wo gr aysonly full black and full whit e are not represent ed .
A valuable geomet r ic proper t y of t his space par t it ioning is t hat t he t wo
gr ay planes int rod uced are coincid ent wit h faces of t he und er lying cuboc-
t ahed ron. These cut t he gr ay bod y d iagonal at 1/ 6 and 5/ 6 of it s t ot al
lengt h. This cu be p ar t it ioning is closely relat ed t o t he d issect ion of
Eu clid ean 3-sp ace int o cu boct ahed r a and oct ahed r a. An oct ahed ron
(whose faces are pr imar y color s) may be split in Car t esian fashion int o
eight r ight -angled corner pyr amid s. At t aching each t o t he eight und er ly-
ing t r iangular faces of a cuboct ahed r al core for ms t he color cube of t he
previous algor it hm. In t he present case, t he int er ior, regular t et r ahed r a
beneat h t he black and whit e cor ner pyr amid s ret ain int er med iat e gr ay
values (Fig. l see color inser t ).
Int erest ingly, alt hough many ed ge and face d imensions of t he unit color
cube have ir r at ional measure, t he d issect ion volumes d o not : They are
reciprocals of int eger s (Table 1). Moreover, t he eight pr imar y color s,
which occupy half of t he d escr ipt or t able, likewise account for half of t he
cubes par t it ioned volume. Finally, t he four achromat ic volumes are in
1 : 2 : 2 : 1 propor t ion. Precisely t he same r at ios result when gr ay quant i-
zat ion ont o t wo bit s is per for med along a one-d imensional axis, in a
manner p r eviou sly ad vocat ed (Paet h, 1990f, p p . 250-251). Fou r half-
plane t est s (t he minimum) sufce in par t it ioning t he (color ) cube int o 16
regions, t hough t wo compar isons are required t o est ablish t he d isplace-
ment const ant employed by t he four t h t est .
See also (233) Mapping RGB Triples ont o Four Bit s, Alan W. Paet h
3.5 Figure 2. Quantization of color triples under the algorithm.
3.5 Figure 1 Partioning of 3-space into 16 regions.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 147
III.6 III.6 III.6 III.6 III.6
T TT TTELEVISION COLOR ELEVISION COLOR ELEVISION COLOR ELEVISION COLOR ELEVISION COLOR
E EE EENCODING AND HOT NCODING AND HOT NCODING AND HOT NCODING AND HOT NCODING AND HOT
B BB BBROADCAST COLORS ROADCAST COLORS ROADCAST COLORS ROADCAST COLORS ROADCAST COLORS
David Mart indale Alan W. Paet h
Imax Corp. and NeuralWare, Inc.
Toront o, Ont ario, Canada Pit t sburgh, Pennsylvania
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Television camer as and receiver s are RGB d evices: They d eal wit h color
using t hree signals represent ing t he int ensit y of red , green, and blue at
each point in t he image. However, t elevision signals are not broad cast in
RGB for m. RGB is encod ed int o one luminance and t wo color-d ifference
signals for t r ansmission, and a color receiver d ecod es t hese signals back
int o RGB for d isplay. The color-d ifference signals t hen may be t r ansmit -
t ed wit h less band wid t h t han t he luminance signal, since t he human visual
syst em has poorer spat ial resolut ion for color var iat ion t han it has for
lu minance var iat ion. Also, t his encod ing t echniqu e p rovid es a signal
compat ible wit h black-and -whit e receiver s t hat have no color d ecod ing
circuit r y.
Mat hemat ically, t he t r ansfor mat ion from RGB int o a luminance-color
d ifference space is a linear change of basis, and is lossless and inver t ible.
In t he real wor ld of t elevision, t hough, t he signals are represent ed by
volt ages t hat have maximum limit s, and some RGB t r iples t r ansfor m int o
signals t hat cannot be broad cast . These unencod able RGB values all
are high-int ensit y, high-sat ur at ion color s t hat seld om occur in nat ure, but
easily can be present in synt het ic images. We call t hem hot color s.
We d iscu ss t he color encod ing p rocess t o clar ify why t he p roblem
exist s. Then we d iscuss an algor it hm for efcient ly d et ect ing hot pixels in
an image, and t wo t echniques for cooling t hem. A per son select ing
color s for an image may use t his as a t ool t o avoid hot color s ent irely. It
also can be used t o x up alread y rend ered images before record ing t hem
on vid eo.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 148
N NN NNTSC TSC TSC TSC TSC Encodi ng Basi cs Encodi ng Basi cs Encodi ng Basi cs Encodi ng Basi cs Encodi ng Basi cs
The Amer ican broad cast color t elevision st and ard was d eveloped by a
group of ind ust r y exper t s called t he Nat ional Television Syst ems Commit -
t ee. The acronym NTSC is used now for bot h t he commit t ee and t he
st and ard it self.
Any color t elevision st and ard must begin by specifying t he chromat ici-
t ies of t he t hree pr imar y color s t hat will for m t he color reference frame
for t he syst em. The act ual spect r al sensit ivit ies of t he sensor s in t he
camer a may not mat ch t hese reference pr imar ies, but in t hat case, t he
camer a will per for m a color space t r ansfor m t o express t he color cont ent
of t he scene in t er ms of amplit ud es of t he reference pr imar ies, not t he
act ual image sensor out put s. Similar ly, if t he receiver uses phosphor s
wit h chromat icit ies d ifferent from t he reference pr imar ies, it also will
per for m a color space t r ansfor m t o mat ch t he color t hat would have been
prod uced wit h t he reference pr imar ies. (Well, t hat is t he t heor y. Pr act ice
oft en d iffer s from t heor y.)
For it s reference pr imar ies, t he NTSC select ed t he chromat icit ies id en-
t ied as NTSC in Table 1. For t he lu minance (Y) signal t o r eect
accur at ely t he luminance cont ent of a scene, it must be calculat ed as a
weight ed sum of RGB, where t he weight s represent t he act ual cont r ibu-
t ions of each of t he reference pr imar ies t oward s t he luminance of a
reference whit e value. Fir st , a r eference whit e must be select ed ; t he NTSC
specied CIE St andard Illuminant C (Table 2). Then we must nd t he
linear combinat ion of t he reference pr imar ies t hat gives reference whit e
by solving t he following set of equat ions. Here, t he columns of t he r st
mat r ix are t he chromat icit ies of t he reference pr imar ies, t he Js are t he
Table 1. Pr imar y Color Chromat icit ies.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 149
Table 2. Whit e Point Chromat icit ies.
unknowns, and t he r ight -hand mat r ix cont ains t he chromat icit y of refer-
ence whit e nor malized so it s y component is 1:

x
r
x
g
x
b
y
r
y
g
y
b
z
r
z
g
z
b

]
]
]
]
]

J
r
J
g
J
b

]
]
]
]
]

x
w
y
w
1
z
w
y
w

]
]
]
]
]
]
.
When t his has been solved , t he relat ive luminance cont r ibut ions of t he
RGB pr imar ies t o reference whit e t hen are J
r
y
r
, J
g
y
g
, and J
b
y
b
.
For t he NTSC pr imar ies and Illuminant C whit e point , t he weight s are
0.299, 0.587, an d 0.114 t o t h r ee sign ican t gu r es. Th e u biqu it ou s
equat ion Y = .30R + .59G + .11B, seen so oft en in comput er gr aphics,
is bor rowed d irect ly from t he NTSC st and ard . Not e t hat t hese values are
cor rect only for t he NTSC pr imar y chromat icit ies and whit e point ; t hey
are not cor rect for most mod er n RGB monit or s.
In ad d it ion t o t he Y signal, t here are t wo color d ifference values t o be
d ened . (B Y) and (R Y) are used , since t hey have t he nice proper t y
of going t o zero on any gr ays in t he scene, and (G Y) is less suit able
because of t he large amount of green in Y. The result ing values t hen must
be scaled by some fact or t o keep t heir amplit ud es wit hin a r ange where
t hey can be super imposed on t he luminance signal wit hout requir ing
more t ot al volt age r ange. Somewhat ar bit r ar ily, t he NTSC d ecid ed t o
calculat e t he scaling fact or s so t hat any color whose RGB amplit ud es all
are less t han or equal t o 0.75 (aft er gamma cor rect ion) will be encod ed
int o a composit e signal whose peak amplit ud e never exceed s t hat of
full-int ensit y whit e. The t wo wor st -case color s are fully sat ur at ed yellow
and cyan, and expressions for t he encod ed composit e signal for t hese t wo
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 150
color s yield t wo linear equat ions in t wo unknowns. Solving t hem yield s
t he need ed scaling fact or s, and we now can d ene t wo signals, U = 0.493
(B Y) and V = 0.877 (R Y). These t wo signals car r y all of t he color
infor mat ion, and collect ively are known as chrominance.
The I and Q signals t hat are broad cast are d er ived from U and V via a
simple linear change of basis cor respond ing t o rot at ing t he coord inat e
syst em 33: I = V cos(33) U sin(33), Q = V sin(33) + U cos(33).
This posit ions t he Q axis so it car r ies t he color s for which t he eye has t he
poorest spat ial resolut ion, t hus minimizing t he pict ure d egr ad at ion caused
by t r ansmit t ing t he Q signal wit h less band wid t h t han I.
Ever y component of t his sequence of oper at ion (Y ext r act ion, color
d ifference ext r act ion and scaling, and 33 change of chrominance basis
vect or s) is linear, so we can express t he ent ire t r ansfor mat ion as a single
mat r ix. The NTSC t r ansfor mat ion and it s inver se are:

Y
I
Q

]
]
]
]
]

0. 2989 0. 5866 0.1144
0. 5959 0. 2741 0. 3218
0. 2113 0. 5227 0. 3113

]
]
]
]
]

R
G
B

]
]
]
]
]
,

R
G
B

]
]
]
]
]

1. 0 0. 9562 0. 6210
1. 0 0. 2717 0. 6485
1. 0 1.1053 1.7020

]
]
]
]
]

Y
I
Q

]
]
]
]
]
The t hree signals must be combined int o a single composit e signal for
broad cast or t r ansmission over a single wire. This is d one by having I and
Q mod ulat e t wo high-frequency signals of t he same frequency but wit h a
90 phase d iffer ence bet ween t hem. This can be repr esent ed by C =
I cos(t ) + Q sin(t ), where = 2 F
SC
This sum is a single sine wave
of amplit ud e |C| = sqr t (I
2
+ Q
2
). When t his is ad d ed t o t he luminance
signal, t he peak posit ive and negat ive excur sions of t he composit e signal
are Y + |C| and Y |C|.
There is one ad d it ional d et ail t hat has been ignored so far. The RGB
signals being fed t o t he CRT in t he receiver must be gamma-cor rect ed t o
compensat e for t he nonlinear t r ansfer char act er ist ics of t he CRT. The
NTSC st and ard d enes t his gamma cor rect ion as being d one t o t he RGB
signals in t he camer a, before encod ing t o YIQ. As far as t he NTSC
encod ing hard ware is concer ned , your fr ame buffer is a camer a, so t he
signals coming from it also must includ e gamma cor rect ion. You may d o
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 151
t he gamma cor rect ion wit h hard ware or soft ware look-up t ables, have it
built int o your pixel quant izat ion met hod , or use any ot her met hod t hat
wor ks. You always shou ld u se an exponent of 0.45 when d oing t he
gamma cor rect ion, ignor ing t he act u al gamma of you r monit or. (The
NTSC st and ard sp ecies gamma cor r ect ion for an assu med receiver
gamma of 2.2.)
The act ual phosphor s used in t elevision CRTs have changed over t ime,
and t heir chromat icit ies have not been close t o t he NTSC r efer ence
pr imar ies for d ecad es. This var iat ion mad e it d ifcult t o evaluat e cr it ically
t he color in t elevision st ud ios, and t he Societ y of Mot ion Pict ure and
Television Engineer s (SMPTE) set u p sever al commit t ees t o d evelop
st and ard s for t hese pict ure monit or s. Event ually, recommend ed pr act ices
RP-37 and RP-145 (SMPTE, 1969, 1987) were p u blished . These d ocu -
ment s specify t he phosphor chromat icit ies called SMPTE in Table 1 and a
whit e reference of D65 (Table 2). See Zavad a (1988) for more infor mat ion
about t he hist or y of t hese st and ard s.
In t heor y, t hese pr act ices apply only t o monit or s used for evaluat ing
vid eo wit hin t elevision st u d ios, while camer as, t elecines
1
, and home
receiver s cont inue t o ad here t o t he or iginal st and ard . However, of t he
broad cast er s t hat bot her t o calibr at e t he color mat r ixing on t heir camer as
and t elecines, most use monit or s t hat confor m t o t hese st and ard s, so
t hese p ict u r e sou r ces are effect ively being calibr at ed t o t he SMPTE
st and ard s. Thus, alt hough t he ofcial st and ard has not changed , t here is
a new de fact o st and ar d for pr imar y chromat icit y.
The RGB-t o-YIQ encod ing st ill is d one accord ing t o t he or iginal st an-
d ard ; t he lu minance weight ing fact or s and chrominance scale fact or s
have not been changed t o cor respond t o t he alt ered phosphor s and whit e
point . As a result , t he mat r ix is not quit e cor rect for t he chromat icit ies
act ually used , t hough t his causes few problems in pr act ice.
If you have an image rend er ing syst em t hat can be t old t he chromat ici-
t ies of t he red , green, and blue pr imar ies of t he d isplay for which it is
rend er ing, you should specify chromat icit ies appropr iat e for broad cast ,
not t he ones appropr iat e for your par t icular RGB monit or. In t heor y, you
should use t he NTSC refer ence pr imar y chromat icit ies, but we recom-
1
A t elecine is a d evice for conver t ing a mot ion pict ure image record ed on phot ogr aphic
lm int o a t elevision signal.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 152
mend t hat you use t he SMPTE set inst ead . This is more likely t o give
color reprod uct ion t hat mat ches t hat of real object s phot ogr aphed in
mod er n st ud ios.
The Pr obl em The Pr obl em The Pr obl em The Pr obl em The Pr obl em
Because of t he par t icular way in which t he scale fact or s used in t he
calculat ion of U and V were chosen, some fully sat ur at ed color s wit h
int ensit ies great er t han 0.75 aft er gamma cor rect ion (0.53 before gamma
cor rect ion) will have composit e signal amplit ud es t hat go above maxi-
mum whit e. There is some leeway for signals t hat go above maximum
whit e, but not enough t o hand le all possible color s. The wor st case occur s
when eit her t he red or blue int ensit y is zero and t he ot her t wo compo-
nent s are at maximum. Such signals are unlikely t o be prod uced by vid eo
camer as, but fr ame buffer s will happily gener at e any combinat ion of R,
G, and B.
Vid eo signal amplit ud es usually are measured in IRE unit s, where 100
IRE is maximum whit e, 7.5 IRE is pict ure black, and 0 IRE is blanking
black. At an amplit ud e of 120 IRE, t he vid eo t r ansmit t er becomes over-
mod ulat ed , so t his for ms an absolut e upper limit for t he signal d ur ing
t r ansmission. Ot her vid eo equipment , t oo, may clip or d ist or t signals t hat
exceed 120 IRE, p ot ent ially r esu lt ing in d r ast ic color er r or s in t he
affect ed areas of t he image. Unfor t unat ely, full-int ensit y yellow and cyan
encod e t o signals t hat reach 131 IRE: such color s must be red uced in
int ensit y or sat ur at ion before t hey can be broad cast . To be conser vat ive,
we should limit t he peak amplit ud e t o about 110 IRE, so t hat even if it
grows a bit t hrough sever al st ages of processing, it will not reach t he 120
IRE hard limit . Limit ing t o 100 IRE is even safer, but und esir able because
it fur t her limit s t he color s available.
There is a second pot ent ial problem. Winkler (1990) d escr ibes how t he
chrominance component of an NTSC signal can be d isplayed on a vec-
t or scop e, and comment s t hat color s never shou ld be allowed t o go
out sid e t he out er circle of it s d isplay. On vect or scopes available t o t he
r st aut hor, t he posit ion of t he out er circle cor respond s t o a chroma
amplit ud e of 52 or 53 IRE unit s. To be safe, we should set t he chroma
amplit ud e limit t o 50 IRE.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 153
Alt hough no explanat ion of t his rest r ict ion is given by Winkler, and
anot her source d oes not consid er t his t o be a problem, it cost s almost
not hing t o check for t his cond it ion at t he same t ime t hat we check for
composit e signal amplit ud e. Thus, we provid e t he check; you can d elet e it
easily if you feel it is not required .
P PP PPAL AL AL AL AL Encodi ng Encodi ng Encodi ng Encodi ng Encodi ng
The d esigner s of t he PAL broad cast st and ard used t he NTSC st and ard as
a basis, changing only what t hey felt need ed changing for t heir environ-
ment . Many of t he changes were in areas t hat d o not concer n us here. We
will d iscuss only t he relevant ones.
Because more t ot al band wid t h was available, and because of t he phase
alt er nat ion t hat is u sed in PAL, bot h chrominance signals cou ld be
t r ansmit t ed wit h t he same band wid t h. Thus, t here was no reason for t he
color space t r ansfor mat ion from U, V t o I, Q, and it was d elet ed . The U
and V signals are used t o mod ulat e t he subcar r ier s d irect ly.
Inst ead of using t he NTSC reference pr imar ies, most PAL syst ems use
t he EBU reference pr imar ies list ed in Table 1. Thus, you should rend er
your images for t hese pr imar y chromat icit ies if t hey are d est ined for PAL
broad cast . PAL syst ems also use a D
65
whit e point inst ead of Illumi-
nant C.
Despit e t hese changes, PAL ret ains exact ly t he same luminance weight -
ing fact or s and U, V scaling fact or s t hat are used in NTSC. In mat r ix
for m, t he t r ansfor mat ion and it s inver se are:

Y
U
V

]
]
]
]
]

0. 2989 0. 5866 0.1144
0.1473 0. 2891 0. 4364
0. 6149 0. 5145 0.1004

]
]
]
]
]

R
G
B

]
]
]
]
]

R
G
B

]
]
]
]
]

1. 0 0. 0 1.1402
1. 0 0. 3959 0. 5810
1. 0 2. 0294 0. 0

]
]
]
]
]

Y
U
V

]
]
]
]
]
The only d ifference bet ween t he NTSC and PAL mat r ices is t he ad d it ional
33 rot at ion used t o gener at e I and Q in NTSC.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 154
You should d o gamma cor rect ion using an exponent of 0.45 (t he same
as NTSC).
Component Syst ems Component Syst ems Component Syst ems Component Syst ems Component Syst ems
There are sever al syst ems for processing and record ing vid eo images as
t hr ee sep ar at e signals t hat are not mixed t oget her ; t hese are called
component syst ems. Bet acam and M2 are analog comp onent syst ems,
while CCIR 601 is a st and ard d igit al comp onent syst em. These are
available for bot h NTSC and PAL st and ard s. Since t he luminance infor ma-
t ion is car r ied separ at ely from t he chrominance, t here are no problems
wit h t he sum of t he t wo being t oo large. In ad d it ion, t he chrominance
scale fact or s are d ened so t hat all RGB color s prod uce chrominance
signals t hat are wit hin t he d ened r ange. Finally, t he t wo chror mi-
nance signals are not ad d ed t oget her, so t he magnit ud e of t heir sum is not
a concer n eit her. See SMPTE RP-125 and 253 (1984, 1990b) for t he
d et ails.
Thu s, t here are no color r est r ict ions when you are r ecord ing t o a
component record er provid ed you will play back t he record ing only on
a component monit or. If t he signal will be encod ed t o composit e NTSC or
PAL at some point in t he fut ure, however, it may be ad vant ageous t o d o
hot -color processing before record ing, anyway.
H HH HHDTV DTV DTV DTV DTV
The SMPTE 240M d ocument (1988) d escr ibes an int er nat ional st and ard
for t he prod uct ion of HDTV images. It is a component vid eo st and ard ,
and has all t he ad vant ages of t he ot her component syst ems list ed previ-
ously.
Init ially, t he reference phosphor s are t he SMPTE set (Table 1). Event u-
ally, t he commit t ee member s hope t hat t he color imet r y can be based on
t he consid er ably wid er gamu t given by t he pr imar ies labeled HDTV
ideal. Not e t hat t he gamut of t hese pr imar ies is a super set of t he gamut s
of t he t hree ot her pr imar y set s list ed . For now, you should rend er for
SMPTE pr imar ies.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 155
The whit e point is D
65
. The gamma cor rect ion exponent is 0.45. The
luminance weight ing fact or s were calculat ed from t he pr imar ies and whit e
point specified , and so d iffer from t hose used in NTSC and PAL. The
chrominance scale fact or s were chosen so t hat t here are no hot color s. The
encod ing and d ecod ing mat r ices are:

Y
P
B
P
R

]
]
]
]
]

0. 2122 0.7013 0. 0865
0.1162 0. 3838 0. 5000
0. 5000 0. 4451 0. 0549

]
]
]
]
]

R
G
B

]
]
]
]
]
,


R
G
B

]
]
]
]
]

1. 0 0. 0 1. 5755
1. 0 0. 2254 0. 4768
1. 0 1. 8270 0. 0

]
]
]
]
]

Y
P
B
P
R

]
]
]
]
]
.
The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm
The hot -pixel t est must be d one on ever y pixel in an image, and t hus should
be fast . The repair sect ion of t he algor it hm is likely t o be used on a
relat ively small nu mber of p ixels, so it s sp eed is not of su ch great
concer n.
Calculat ion of YIQ for each pixel pot ent ially is quit e expensive. The
int eger RGB values fir st must be d ecod ed int o a float ing point number in
t he r ange [0,1]; t his may be cheap or expensive d epend ing on t he way t he
pixels are encod ed . Then t hese values must be gamma-cor rect ed , requir ing
t hree calls t o a mat h libr ar y funct ion. Finally, we mult iply by t he encod ing
mat r ix t o obt ain YIQ.
We can improve on t his consid er ably by build ing nine look-up t ables, one
for each coefficient in t he mat r ix. In each t able, for each possible RGB
component value, we conver t t he component value t o float , gamma-cor rect
it , t hen mult iply it by t he appropr iat e coefficient of t he encod ing mat r ix.
This red uces t he YIQ calculat ion t o nine ind exing oper at ions and six
ad d it ions.
Y = t ab
0, 0
[R] + t ab
0, 1
[G] + t ab
0, 2
[B],
I = t ab
1, 0
[R] + t ab
1, 1
[G] + t ab
1, 2
[B],
Q = t ab
2, 0
[R] + t ab
2, 1
[G] + t ab
2, 2
[B].
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 156
Calculat ion of chroma amplit ud e involves t aking a square root . Per -
for ming t he t est , t hou gh, only requ ir es comp ar ing t he sizes of t wo
expressions, so we can compare amplit ud e squared , and eliminat e t he
square root :

I
2
+ Q
2
( )
> limit
I
2
+ Q
2
> limit
2
The t est for composit e signal amplit ud e can be rear r anged in a similar way:
Y +

I
2
+ Q
2
( )
> limit

I
2
+ Q
2
( )
> limit Y
I
2
+ Q
2
> (limit Y)
2
The simple comput at ions just d escr ibed can be d one ent irely in scaled
int eger s, eliminat ing oat ing point ent irely. Since t he values of Y, I, and
Q always are wit hin t he r ange [1, 1], we can choose a scale fact or t hat
gives plent y of fr act ional bit s wit hout r isk of over ow, even on a 16-bit
machine. We d o have t o conver t t o 32 bit s t o hand le t he squares, t hough.
There are only t hree int eger mult iplicat ions plus seven ad d it ions, one
subt r act ion, and t wo compar isons necessar y in t he per-pixel loop. (One
squar ing oper at ion is d one on a const ant .) This is reasonably cheap.
Once you have found a hot pixel, you may wish t o ag it in a d ist inct ive
manner so t he user can see where it is. If your fr ame buffer d oes not have
over lay bit s, just set t ing t he pixel t o a d ist inct ive color will d o.
If you have t o repair hot pixels, t hen t he RGB values must be alt ered .
This involves calculat ing t he act ual chroma amplit ud e, which requires
t aking a square r oot or equivalent . The C Implement at ion t hat accompa-
nies t his gem (Append ix 2) just swit ches t o oat ing point for simplicit y.
However, if oat ing point is not available or is t oo slow, you can conver t
t he remaind er of t he cod e t o scaled int eger as well. The square root also
can be d one wit h int eger s using an approximat ion t echnique d escr ibed by
t he second aut hor (Paet h, 1990b). This t echnique is not exact , but always
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 157
er r s on t he sid e of overest imat ing t he result . When used in t his algor it hm,
it can result in cooling t he color a bit t oo much, which is har mless.
There are t wo plausible ways t o alt er t he RGB color t o br ing it wit hin
accept able bound s. Alt er ing t he hue of t he color could have ext remely
ugly result s, so we d o not consid er t his. That leaves sat ur at ion and
int ensit y (luminance) open for ad just ment . Changing luminance is easy.
Because t he color encod ing t r ansfor m is linear, mult iplying YIQ by a
scalar value is equivalent t o mult iplying RGB by t he same scalar. Gamma
cor rect ion ad d s a minor wr inkle: To mult iply t he gamma-cor rect ed RGB
values (and t hus YIQ values) by a fact or K, t he linear RGB values must
be mult iplied by a fact or of K
gamma
.
Alt er ing color sat ur at ion while leaving hue and luminance alone is only
a bit more d ifcult . In concept , we want t o scale I and Q equally by some
scale fact or s, while leaving Y unalt ered . If E is t he color encod ing mat r ix
and E
1
is it s inver se, we wish t o evaluat e:

R
G
B

]
]
]
]
]
E
1

]
]
]
]
]
1 0 0
0 s 0
0 0 s

]
]
]
]
]
E

]
]
]
]
]

R
G
B

]
]
]
]
]
If you mult iply out t he t hree 3 3 mat r ices, you will nd t hat t he
oper at ion per for med by t heir prod uct simply is:
R = (1 s)*Y + s*R R = Y + s*(R Y)
G = (1 s)*Y + s*G or G = Y + s*(G Y)
B = (1 s)*Y + s*B B = Y + s*(B Y)
In ot her word s, per for m a linear int er polat ion bet ween t he or iginal pixel
value and a monochrome pixel of t he same luminance. In pr act ice, t his
met hod looks awful when applied t o full-int ensit y color bar s, since t heir
sat ur at ion must be d ecreased so much. However, it might be accept able
when applied t o real images, and it has t he ad vant age t hat it preser ves t he
black-and -whit e component of t he image.
III.6 TELEVISION COLOR ENCODING AND HOT BROADCAST COLORS
GRAPHICS GEMS II Edit ed by JAMES ARVO 158
Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng
Winkler (1990) cont ains an int rod uct ion t o vid eo, plus much reference
mat er ial on calibr at ing your vid eo equipment if you d o not have a vid eo
engineer hand y. Hall (1989) cont ains ext ensive d iscussions about color
accur acy in rend er ing, and t r ansfor ming images t o a d ifferent color space.
It also cont ains a d iscussion on how t o hand le out -of-gamut color s t hat
goes beyond t he t wo simple t echniques d iscussed here. Amanat id es and
Mit chell (1990) provid e some int erest ing comment s about high-qualit y
rend er ing for t he int er laced vid eo for mat .
159
III.7 AN INEXPENSIVE METHOD OF SETTING THE MONITOR WHITE POINT
GRAPHICS GEMS II Edit ed by JAMES ARVO 159
III.7 III.7 III.7 III.7 III.7
A AA AAN INEXPENSIVE METHOD OF N INEXPENSIVE METHOD OF N INEXPENSIVE METHOD OF N INEXPENSIVE METHOD OF N INEXPENSIVE METHOD OF
S SS SSETTING THE MONITOR ETTING THE MONITOR ETTING THE MONITOR ETTING THE MONITOR ETTING THE MONITOR
W WW WWHITE POINT HITE POINT HITE POINT HITE POINT HITE POINT
Gary W. Meyer
Universit y of Oregon
Eugene, Oregon
Calibr at ing a color t elevision monit or in t er ms of t he CIE XYZ color
not at ion syst em has assumed an increasingly impor t ant role in comput er
gr aphics. This ad just ment has been shown t o be useful in applicat ions as
d iver se as t wo-d imensional page layout for t he gr aphic ar t s and t hree-
d imensional realist ic image synt hesis for commercial animat ion. Par t of
t he calibr at ion process involves set t ing t he ind ivid ual br ight ness and
cont r ast cont rols for t he t hree monit or guns so t hat a whit e color wit h
known chr omat icit y coor d inat es is p r od u ced whenever R = G = B
(Meyer, 1990). Typically, t his is t hought t o require an expensive color
measurement d evice, such as a color imet er or a color compar at or (SMPTE,
1977).
In t his gem, we show how a relat ively inexpensive luminance met er can
be used t o est ablish t his set up. We also show how t he luminance met er
may only need t o be used once if a simple light met er wit h ar bit r ar y
spect r al sensit ivit y but linear response is available. We have mad e use of
t his t echnique in our research for some t ime (Meyer, 1986). Recent ly, it
was shown how t his approach can be ad apt ed t o post pone t he need for a
complet e monit or calibr at ion (Lucassen and Walr aven, 1990).
To employ a luminance met er in set t ing t he monit or whit e point , t he
luminance r at io bet ween t he red , green, and blue monit or guns at equal
d r ive must be d et er mined . This r at io can be found by not ing t hat t he
following relat ionship hold s bet ween t he t r ist imulus values of t he whit e
point and t he component t r ist imulus values prod uced by each of t he
160
III.7 AN INEXPENSIVE METHOD OF SETTING THE MONITOR WHITE POINT
GRAPHICS GEMS II Edit ed by JAMES ARVO 160
guns,


X
R
Y
R
Z
R

]
]
]
]
+
X
G
Y
G
Z
G

]
]
]
]
+
X
B
Y
B
Z
B

]
]
]
]

X
W
Y
W
Z
W

]
]
]
]
.
Using t he fact t hat , for example,


X
G
Y
G
x
G
y
G
,
where x
G
and y
G
are t he chromat icit y coord inat es of t he green monit or
phosphor, t his can be rear r anged t o yield

x
R
/ y
R
x
G
/ y
G
x
B
/ y
B
1 1 1
z
R
/ y
R
z
G
/ y
G
z
B
/ y
B

]
]
]
]
Y
R
/ Y
W
Y
G
/ Y
W
Y
B
/ Y
W

]
]
]
]

x
W
/ y
W
1
z
W
/ y
W

]
]
]
]
,
where x
w
, y
w
, and z
w
ar e t he whit e-point chromat icit y coord inat es and
Y
w
is t he whit e-point luminance. From t his expression, t he required r at io
bet ween t he gun luminances can be d et er mined . A luminance met er can
be used t o set t he ind ivid ual br ight ness and cont r ast cont rols for each
monit or gun so t hat t he preced ing luminance r at io is achieved .
A luminance met er may not always be available t o est ablish t hese
set t ings and , even if it is, it may not have t he necessar ysensit ivit y (d u e t o
it s phot opic response) t o make t hese ad just ment s over t he ent ire d ynamic
r ange of each monit or gu n. It is p ossible, however, t o make t hese
measurement s wit h a light sensing d evice of ar bit r ar y spect r al sensit ivit y
as long as t he d evice respond s linear ly t o changes in int ensit y, t he d evice
has a response t ime appropr iat e for t he monit or refresh r at e, and a
luminance met er is available t o calibr at e init ially t he light sensing d evice.
To see how t his is possible, consid er t he spect r al emission cur ve KP

( )
for one of t h e mon i t or phosphor s, where P

( ) is a relat ive spect r al
161
III.7 AN INEXPENSIVE METHOD OF SETTING THE MONITOR WHITE POINT
GRAPHICS GEMS II Edit ed by JAMES ARVO 161
energy d ist r ibut ion cur ve t hat has t he proper t y,
P( ) d = 1,
and K is a const ant wit h unit s wat t s m
-2
sr
1
t hat scales P( ) t o creat e
an absolut e spect r al energy d ist r ibut ion. A luminance met er has spect r al
sensit ivit y

y ( ) id ent ical t o t he human phot opic response cur ve and
per for ms t he following int egr at ion:
Y = KP( )

y ( ) d = K P( )

y ( ) d = KI
y
.
A light sensing d evice wit h ar bit r ar y spect r al sensit ivit y

a( ) per for ms t he
following int egr at ion:
A = KP( )

a( )d = K P( )

a( )d = KI
a
.
Divid ing t hese t wo expressions by one anot her and rear r anging, we see

Y
I
y
I
a
A.
The luminance of t he phosphor, t herefore, can be measured using t he
light sensing d evice wit h ar bit r ar y spect r al sensit ivit y as long as t he r at io
I
y
/I
a
has been d et er mined . This can be d one by t aking t he r at io of t he
t wo met er read ings at sever al xed phosphor int ensit ies and aver aging
t he result .
Given t he chromat icit y coord inat es of t he monit or phosphor s, a light
sensing d evice wit h linear response but ar bit r ar y spect r al sensit ivit y, and
t he shor t t er m loan of a luminance met er, it is possible t o calibr at e
complet ely a color t elevision monit or in t er ms of t he CIE XYZ syst em. As
was shown previously t he light sensing d evice can be used t o set t he
162
III.7 AN INEXPENSIVE METHOD OF SETTING THE MONITOR WHITE POINT
GRAPHICS GEMS II Edit ed by JAMES ARVO 162
monit or whit e point and balance t he monit or over it s ent ire d ynamic
r ange. A light sensing d evice wit h at spect r al sensit ivit y is prefer red even
over a lu minance met er in p er for ming t his op er at ion becau se of it s
great er sensit ivit y, par t icular ly for low blue phosphor int ensit ies. This
same light sensing d evice also can be used t o measure t he nonlinear
relat ionship t hat exist s bet ween t he volt age applied t o t he monit or guns
and t he amount of light t hat t he phosphor s emit (i.e., gamma correc-
t ion) (Cowan, 1983; Br ainard , 1989). In t his way, a complet e monit or
calibr at ion can be accomplished using one relat ively inexpensive light
measurement d evice.
163
III.8 SOME TIPS FOR MAKING COLOR HARDCOPY
GRAPHICS GEMS II Edit ed by JAMES ARVO 163
III.8 III.8 III.8 III.8 III.8
S SS SSOME TIPS FOR MAKING OME TIPS FOR MAKING OME TIPS FOR MAKING OME TIPS FOR MAKING OME TIPS FOR MAKING
C CC CCOLOR HARDCOPY OLOR HARDCOPY OLOR HARDCOPY OLOR HARDCOPY OLOR HARDCOPY
Ken Musgrave
Yale Universit y
New Haven, Connect icut
Obt aining high-qualit y color hard copy of d igit al images is st ill more an ar t
t han a science. It is an expensive process, fr au ght wit h pit falls and
requir ing much exper iment at ion. In t his gem, we seek t o convey some
useful knowled ge and t echniques. We ad d ress image qualit y and d elit y,
and archivabilit y and or iginalit y of comput er images as ar t wor ks; we d o
not ad d ress problems of color gamut mat ching.
The essent ial problem of color reprod uct ion in comput er images is t hat
of recreat ing one more or less ar bit r ar y mapping from number s t o color s
t he one per for med by what ever reference d evice is d eemed your nor m
on anot her d evice or med ium t hat has it s own and , invar iably, d ifferent
biases. While one can end eavor t o solve t his problem r igorously and
scient ically (St one, et al., 1988), for some of us, just get t ing a reprod uc-
t ion t hat is close t o t he original, and in a par t icular prefer red size and
for mat , wou ld be a boonesp ecially if it can be achieved wit hou t
expensive special hard ware.
The r st problem we encount er in swit ching reprod uct ion d evices or
med ia is d ynamic r ange and gamma mat ching (Cat mull, 1979; Bilson
et al., 1986). We have found t hat a reasonable r st -ord er approximat ion
can be had t hrough t he following pr ocess:
Out put a gr ay r amp, wit h visible t ic mar ks on t he ed ge at about ever y
ve gr ay levels. Not e where t he low ent r ies of your look-up t able all have
gone t o black, and where t he high values all have gone whit e. (Hopefully,
t his will not be complicat ed by signicant ly d ifferent values for red ,
green, and blue.) Then remap your image t o wit hin t he available cont r ast
r ange, t o avoid gaining cont r ast and pot ent ially losing d et ail in highlight s
and / or shad ows. This sor t of cont r ast gain oft en occur s when mapping t o
phot ogr aphic med ia, as when phot ogr aphing t he screen, making a C-Pr int
164
III.8 SOME TIPS FOR MAKING COLOR HARDCOPY
GRAPHICS GEMS II Edit ed by JAMES ARVO 164
or a Cibachrome pr int , or even when using a lm record er. Not e t hat you
may need t o use a d ifferent ASA or t ype of lm in a lm record er t han t hat
specied by t he manufact urer ; manufact urer s specicat ions somet imes
are ut t er ly apocr yphal.
The next st ep is t o reprod uce t he peculiar response cur ve of t he new
med ium on your st andard reference d evice. This means creat ing a gr ay
r amp t hat resembles your st andard gr ay r amp, as d isplayed on t he new
d evice. This new r amp may not be a gr ay r amp at all; it may go, for
inst ance, from black t hr ough shad es of brown t o whit e, or show some
ot her peculiar d ist or t ion. Reprod uce t his r amp on your reference d evice
hopefully, t his simply will require a separ at e gamma cor rect ion t o each
of red , green, and blue. Now inver t t he mapping required t o change your
or iginal gr ay r amp t o t his d ist or t ed r amp . (Inver sion of exp onent ial
mappings, such as gamma cor rect ions, just means using 1/ , wher e is
t he exponent used in t he gamma cor rect ion.) Apply t he inver se mapping
t o your d ynamic r ange-ad just ed image(s), which may now look r at her
hor r ible on your reference d evice. Pr int t he newly d ist or t ed images. A
good t est is t o apply t he ad just ment s t o your or iginal gr ay scale and
reimage it it should be much closer t o t he reference r amp now.
This proced ure can improve mar ked ly t he qualit y of r st -gener at ion
out put . This somet imes is not t he nal t arget , however. Somet imes, we
wish t o make a phot ogr aphic enlargement from, for inst ance, a color
t r ansparency. This will require a second it er at ion of t he proced ure, t o
ad just for t he second med ium. Not e t hat t he ad just ment s mad e t o your
images inevit ably will int rod uce quant izat ion er ror s. We employ t wo
t echniques in our rend erer t o combat quant izat ion er ror. Fir st , we ad d
whit e noise t o t he image while we have t he oat ing point values, i.e.,
before quant izat ion t o 8 bit s each for red , green, and blue. This has t he
effect of d it her ing t he quant izat ion lines and making t hem less visible and
offensive. It also plays mer r y hell wit h run-lengt h encod ing. Second , we
have built t he inver se-d ist or t ion mapping int o t he rend erer, as an opt ion
t o be invoked when rend er ing images specically for one of our favor it e
bogus out put d evices. Thus, aft er d eveloping an image on our reference
monit or, we can t oggle t he opt ion t o creat e images t hat are d ist or t ed on
ou r r eference monit or bu t mat ch it closely t o t he hard cop y d evice,
wit hout int rod ucing any ext r a quant izat ion ar t ifact s.
The nal t arget med ium may be a Dur at r ans, C-Pr int , Cibat r ans, or
Cibachrome phot ogr aphic pr int , or a four-color offset pr int . These med ia
are list ed in ord er of increasing longevit y. Wor ks proffered as ne ar t t o
165
III.8 SOME TIPS FOR MAKING COLOR HARDCOPY
GRAPHICS GEMS II Edit ed by JAMES ARVO 165
ser ious collect or s must be archival, t hat is, it should be expect ed t o last
about 100 year s wit hout ser ious fad ing or d egr ad at ion. No commonly
available color p hot ogr ap hic med iu m cu r rent ly is accep t ed as being
archival by museums and collect or s.
Cibachrome and Cibat r ans are posit ive-t o-posit ive color pr int ing med ia.
C-Pr int s and Dur at r ans are negat ive-t o-posit ive color pr int ing med ia, and
are more commonly available. C-Pr int and Cibachrome are opaque color
pr int s, while Dur at r ans and Cibat r ans are large-scale t r ansparencies meant
t o be d isplayed back-lit in light boxes. While back-lit t r ansparencies are a
luminous med ium, and t hus more like a CRT d isplay t han an opaque
reect ion pr int , t heir life expect ancy is subst ant ially shor t er, as t hey are
d irect ly exposed t o high levels of uv-r ich light from t he uorescent bulbs
in t he light box. Light boxes are r at her expensive as well. C-Pr int s are
r at her shor t -lived , d epend ing largely on exposure t o light . Cibachromes
are t out ed as being semi-archival, wit h good color fast ness and a life
expect ancy of over 50 year s. Not e, however, t hat glossy Cibachrome is
pur por t ed t o be longer-lived t han pear l-nish Cibachrome.
Four-color offset pr int s mad e on acid -free paper wit h non-fugit ive (i.e.,
color fast ) inks may be consid ered archival and can const it ut e ver y nice
reprod uct ions, t hough set up cost s are high (about one t o t hree t housand
d ollar s) and physical d imensions may be limit ed . Color separ at ions are
d one rout inely by scanning an or iginal image t o creat e a d igit al image,
from which t he sep ar at ions ar e cr eat ed . Wit h synt het ic images, t he
int er med iat e original har d cop y may be skip p ed , and t he sep ar at ions
mad e d irect ly from t he or iginal d igit al d at a. (Not e t hat med ium-mat ching,
as d escr ibed previously, may need t o be d one here.) As ar t wor k, t he
four-color offset pr int s now can be r ight ly viewed as originals, as no
ot her nonvolat ile visual represent at ions exist .
High-qualit y color pr int er s of var ious sor t s are being announced wit h
increasing frequency. While t he qualit y can be ver y good , t he longevit y of
t he pigment s oft en is r at her poor. These d evices remain r at her expensive
as well. If you cannot afford or just ify t he expense of such a d evice, look
for a service bureaut hese ar e commercial ou t t s t hat make a living
from t heir st able of such d evices. Whichever rout e you use, be prepared
t o pay and pay and payand t o weep over t he qualit y of your ear ly
result s.
I V
3D GEOMETRY
AND
ALGORITHMS
169
3D GEOMETRY AND ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 169
IV IV IV IV IV
3 33 33D GEOMETRY D GEOMETRY D GEOMETRY D GEOMETRY D GEOMETRY
A AA AAND ND ND ND ND
A AA AALGORITHMS LGORITHMS LGORITHMS LGORITHMS LGORITHMS
One of t he major uses of comput er gr aphics is t o prod uce visual repre-
sent at ions of vir t ual t hree-d imensional object s. Synt het ic images of hypo-
t het ical t hree-d imensional scenes are used in areas r anging from engi-
neer ing t o ent er t ainment . Consequent ly, much of comput er gr aphics is
concer ned wit h t hree-d imensional geomet r y. Wit hin t his broad subject ,
t here are many specic, smaller problems; mod eling, viewing, clipping,
and shad ing are among t hem. The gems of t his Par t are applicable t o
t hese problems and ot her s.
The r st t hree gems d eal wit h some basic proper t ies of polyhed r a and
sp heres, t wo ver y common t yp es of 3D object s. Mor e comp lex and
gen er al 3D geomet r i es ar e ad d r essed by t h e gems on winged-edge
mod els and t he const ruct ion of bound ar y represent at ions. Three-d imen-
sional clipping is t he focus of t he gem on t riangle st rips, an efcient and
exible grou p ing of ad jacent t r iangles. The p r oblem of sp ecifying a
viewing t r ansfor mat ion for t he creat ion of imageand t he inver se prob-
lem of infer r ing t he viewing t r ansfor mat ion from an imagefor m t he
basis of t he gems on a simple viewing geomet r y and view cor relat ion,
respect ively. The last gem in t his Par t int rod uces t he concept of Int er-
phong shad ing, a gener alizat ion of t he familiar t echniqu e of Phong
shad ing.
170
IV.1 AREA OF PLANAR POLYGONS AND VOLUME OF POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 170
IV.1 IV.1 IV.1 IV.1 IV.1
A AA AAREA OF PLANAR POLYGONS REA OF PLANAR POLYGONS REA OF PLANAR POLYGONS REA OF PLANAR POLYGONS REA OF PLANAR POLYGONS
A AA AAND VOLUME OF POLYHEDRA ND VOLUME OF POLYHEDRA ND VOLUME OF POLYHEDRA ND VOLUME OF POLYHEDRA ND VOLUME OF POLYHEDRA
Ronald N. Goldman
Rice Universit y
Houst on, Texas
Ar ea of a Pl anar Pol ygon Ar ea of a Pl anar Pol ygon Ar ea of a Pl anar Pol ygon Ar ea of a Pl anar Pol ygon Ar ea of a Pl anar Pol ygon
Consid er a planar polygon wit h ver t ices P
0
, . . . , P
n
. There is a simple
closed for mula for t he area of t he polygon. Let P
n+1
= P
0
. If t he point s
P
0
, . . . , P
n
lie in t he xy plane, t hen t he following for mula can be d er ived
from Greens t heorem:
Area(Polygon) =

1
2
P
k
P
k +1
k

.
If t he point s lie on some ar bit r ar y plane per pend icular t o a unit vect or N,
t hen from St okes Theorem:
Area(Polygon) =

1
2
N P
k
P
k +1
k

.
These t wo for mulas are valid even for nonconvex polygons.
Vol ume of a Pol yhedr on Vol ume of a Pol yhedr on Vol ume of a Pol yhedr on Vol ume of a Pol yhedr on Vol ume of a Pol yhedr on
Consid er a polyhed ron wit h planar polygonal faces S
0
, . . . , S
n
. There is
a simple closed for mula for t he volume of t he polyhed ron. Let
Q
j
= any point on S
j
,
N
j
= a unit out ward point ing vect or nor mal t o S
j
.
171
IV.1 AREA OF PLANAR POLYGONS AND VOLUME OF POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 171
Then t he following for mula can be d er ived from Gausss t heorem:
Volume(Polyhed ron) =

1
3
Q
j
N
j
( )
Area S
j
( )
j

.
Moreover, if P
0j
, . . . , P
mj
are t he ver t ices of S
j
or ient ed count erclock-
wise wit h respect t o t he out ward point ing nor mal of S
j
, t hen by our
previous result for polygons:
Area(S
j
) =

1
2
N
j
P
kj
P
k +1, j
k

'

'

.
Moreover, we now can t ake
Q
j
= P
0j
,
N
j
= {(P
1j
P
0j
) (P
2j
P
0j
)}/ |(P
1j
P
0j
) (P
2j
P
0j
)|
Put t ing t his all t oget her, we get t he for mula:
Volume(Polyhed ron) =

1
6
P
0 j
N
j
( )
N
j
P
kj
P
k +1, j
k

'

'
j

]
]
]
,
where N
j
is d ened in t he preced ing in t er ms of t he ver t ices of t he
polyhed ron. Not ice again t hat t hese t wo for mulas for volume are valid
even for nonconvex polyhed r a.
See also I.1 The Area of a Simple Polygon, Jon Rokne
172
IV.2 GETTING AROUND ON A SPHERE
GRAPHICS GEMS II Edit ed by JAMES ARVO 172
IV.2 IV.2 IV.2 IV.2 IV.2
G GG GGETTING AROUND ON A ETTING AROUND ON A ETTING AROUND ON A ETTING AROUND ON A ETTING AROUND ON A
S SS SSPHERE PHERE PHERE PHERE PHERE
Clif f ord A. Shaf f er
Virginia Tech
Blacksburg, Virginia
Given a point P on a sphere, t his gem d escr ibes how t o comput e t he new
coord inat es t hat result from moving in some d irect ion. I recent ly used
t his mat er ial when d eveloping a browsing syst em for wor ld -scale maps.
When looking d own at a p osit ion on t he sp here, t he u ser of t he
browsing syst em can shift t he view t o t he left , r ight , up, or d own.
The r st t hing t o r ealize is t hat while lat it u d e and longit u d e are
convenient for people, most calculat ions for t he sphere are d one more
easily in Car t esian coord inat es. Given longit ud e , lat it ud e , and a
sphere of r ad ius R wit h cent er at t he or igin of t he coord inat e syst em, t he
conver sions are:
x = R cos cos ; y = R sin cos ; z = R sin ;
R =

x
2
+ y
2
+ z
2
; = arct an

y
x
|
.

`
,
; = arct an

z
x
2
+ y
2
|
.

`
,
.
Given point P on t he sphere, t he plane T t angent t o t he sphere at P
will have it s nor mal vect or going from t he or igin t hrough P. Thus, t he
r st t hree coefcient s for t he plane equat ion will be T
a
= P
x
, T
b
= P
y
,
T
c
= P
z
. Since t he plane must cont ain P, T
d
= (P P), i.e., t he negat ive
of t he d ot prod uct bet ween t he vect or from t he or igin t o P and it self.
Movement on t he sphere must be in some d irect ion. One way t o specify
d irect ions is by means of a great circle G going t hrough t he cur rent point
P. In t his way, we can d escr ibe movement as eit her along G, or in a
d irect ion at some angle at G. G will be cont ained in some plane J, wit h
J
d
= 0 (since it must go t hrough t he or igin). For example, t he plane for
t he great circle cont aining point P and t he nor t h pole N at (0, 1, 0) will
173
IV.2 GETTING AROUND ON A SPHERE
GRAPHICS GEMS II Edit ed by JAMES ARVO 173
have nor mal P N, or t he cross prod uct of t he vect or from t he or igin t o
P wit h t he vect or from t he or igin t o N. Taking t he cross prod uct in t his
ord er will make rot at ions by appear clockwise when looking along t he
d irect ion of t he nor mal vect or from t he plane.
Moving along t he great circle simply will be a rot at ion by some angle .
The rot at ion axis will be t he nor mal vect or for t he plane of t he great
circle. Given J, t he plane for some great circle, and some point P on t he
great cir cle, rot at ion of t he point wit hin plane J by angle clockwise can
be d one as (Faux and Pr at t , 1979):
P
x
= (J
a
J
a
+ cos (1 J
a
J
a
))P
x
+ (J
a
J
b
(1 cos ) J
c
sin )P
y
+ (J
c
J
a
(1 cos ) + J
b
sin )P
z
,
P
y
= (J
a
J
b
(1 cos ) + J
c
sin )P
x
+ (J
b
J
b
+ cos (1 J
b
J
b
))P
y
+ (J
b
J
c
(1 cos ) J
a
sin )P
z
,
P
z
= (J
c
J
a
(1 cos ) J
b
sin )P
x
+ (J
b
J
c
(1 cos ) + J
a
sin )P
y
+ (J
c
J
c
+ cos (1 J
c
J
c
))P
z
.
Moving in a d irect ion per pend icular t o t he great circle requires comput -
ing t he plane J per pend icular t o t he plane J of t he great circle t hat
cont ains P. The nor mal for J is P J
N
, where J
N
is t he nor mal vect or
for plane J, and again, J
d
= 0. Not e t hat t wo d ist inct great circle planes
per pend icular t o a great circle plane will not be par allel.
Finally, assu me we wish t o move from p oint P in some ar bit r ar y
d irect ion t o point P. The d irect ion is specied as being a clockwise angle
t o some great circle (wit h plane J) t hat cont ains P. We r st must
calculat e t he plane J of t he great circle connect ing P and P. We t hen
can use t he preced ing rot at ion equat ions t o calculat e t he act ual move-
ment . To nd t he new nor mal vect or J
N
we simply rot at e J
N
by angle ,
using as t he axis of rot at ion t he vect or from t he or igin t o P. To d o so,
simply rever se t he use of P and J, and subst it ut e for , in t he rot at ion
equat ions.
174
IV.3 EXACT DIHEDRAL METRICS FOR COMMON POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 174
IV.3 IV.3 IV.3 IV.3 IV.3
E EE EEXACT DIHEDRAL METRICS XACT DIHEDRAL METRICS XACT DIHEDRAL METRICS XACT DIHEDRAL METRICS XACT DIHEDRAL METRICS
F FF FFOR COMMON POLYHEDRA OR COMMON POLYHEDRA OR COMMON POLYHEDRA OR COMMON POLYHEDRA OR COMMON POLYHEDRA
Alan W. Paet h
NeuralWare, Inc.
Pit t sburgh, Pennsylvania
Whereas d ecimal ap p roximat ions for ver t ex coord inat es are common,
t his gem gives closed -for m for mulae and t ables for t he d ihed r al angles of
nine prot ot ypical solid s. (This is a d irect ext ension of Paet h (1990e),
which allows closed -for m expressions for t he ver t ex locat ions of select
n-gons.) Uses includ e t he prod uct ion of coord inat e t ables at high preci-
sion (as seen in examp le), crack prevent ion in sp ace p acking lat t ices
having no near-coincid ent ver t ices, and t he gener at ion of polyhed r a using
half-plane equat ions in t he st yle of CAD/ CAM d escr ipt ive solid mod eling.
The t able for d ihed r als for t he Snub gures in analyt ic for m is previously
unpublished , and d ispels t he misconcept ion requot ed by Coxet er in Ball
(1939) suggest ing t hat cubic root s are need ed in t he analyt ic represent a-
t ion of t hese unusual solid s.
Table I is organized by t he regular (plat onic) solid s, quasi-regular solid s
(Coxet er, 1948), and t heir d uals. All possess merely one face d ihed r al: t he
hinge bet ween any t wo ed ge-ad jacen t p olygon s. Th ese ar e list ed
as cos and t an ; sin may be immed iat ely for med as t heir prod uct and
d oes not appear. Not e t hat supplement ar y angles (t hose t hat sum t o 180
and t hus for m an unbroken plane) have opposit e signs: f(90 x) =
f(90 + x) for f in {t an, cos}. Thus, t he t et r ahed ron and oct ahed ron
are seen t o for m a common face when joined t his suggest s t heir 2 : 1
space packing r at io. Likewise, t he cubes d ihed r al necessar ily is zero: It
for ms no ed ge when abut t ed wit h id ent ical copies. This cond it ion for
space packing is sufficient but not necessar y: Three copies of t he rhombic
d od ecahed ron also ll space, as is suggest ed by a solid d ihed r al angle of
2/ 3 (Paet h, 1990g, p p . 236239), as d o t wo cu boct ahed r a and an
175
IV.3 EXACT DIHEDRAL METRICS FOR COMMON POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 175
Table 1. (Quasi) Regular Polyhed r a and Duals.
oct ahed ron. (See also Fig. 1 from Gem 3.5, Mapping RGB Tr iples ont o
sixt een Dist inct Values.) Ot her t r igonomet r ic for ms may fur t her red uce
t he surd s. For inst ance, employing t he halved t angent (Gem 8.5, A
Half-Angle Id ent it y for Digit al Comput at ion) gives t he elegant ser ies,
{

2
/ 2, 1,

2
, ,
2
), for t he ve plat onic solid s; d ihed r al values t an(/ 2)
are posit ive and go t o innit y as t wo faces approach planar it y. Und er t his
t r ansfor mat ion, supplement ar y angles have reciprocal, not complemen-
t ar y measures: The cube now is represent ed by unit y. Using Table I, ot her
id ent it ies may be d er ived , e.g., sin
i cos a
= 2/ 3.
The d od ecahed r on and icosahed ron ar e st rongly d ep end ent on t he
gold en mean. The angle for med bet ween t wo ad jacent (ver t ex) vect or s of
t he lat t er may be used t o d er ive t he face d ihed r al of it s d ual d od ecahe-
d ron by d ot t ing t he vect or s, (0 1 ) (0 1 ). Closer analysis shows
t hat t he solid angle of t he lat t er also may be d er ived using vect or s wit h
int egr al component s, as wit h (1 2 2) (1 0 2), relat ed t o t he compact
equ at ion t an
d od ec
= 2. Similar ly, t he inclu d ed angle of (0 1 2)
(2 1 2) d enes t he solid angle of t he icosahed ron.
As an example of use, t he solid s of vefold symmet r y most oft en are
list ed (Coxet er, 1948) edge on (meaning t he Z axis bisect s an ed ge). Of
176
IV.3 EXACT DIHEDRAL METRICS FOR COMMON POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 176
Figur e 1. Regular Dod ecahed ron (face upr ight ).
177
IV.3 EXACT DIHEDRAL METRICS FOR COMMON POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 177
t he 20 ver t ices in t he d od ecahed ron, a cu bic su bgrou p in Car t esian
alignment t hus is revealed . (Here =
1
= , 1):
(t 1, t 1, t 1), (0, t , t ), (t , 0, t ), (t , t , 0).
Likewise, t he icosahed ron may be const ru ct ed from t hr ee mu t u ally
per pend icular rect angles, each having a gold en aspect r at io. This also
gives t he ed ge-on represent at ion:
(0, t , t 1), (t 1, 0, t ), (t , t 1, 0).
An aest het ic (and oft en more pr act ical) d od ecahed ron is face-on: The
Z axis int er sect s t he cent roid of t wo opposing faces. By st ar t ing wit h a
closed -for m represent at ion for a pent agonal face (Paet h, 1990e) and t hen
applying rot at ions based on t he d ihed r al t able (Table I), t he d esired
or ient at ion is achieved . A fully wor ked example is shown in Fig. 1. An
inscr ibed cu be r emains evid ent , here at {t B, t C, t D}, in t he list of
ver t ices in Fig. 1. (C and D per mut e as t he cube cannot also be face-on.)
Near ly all of t he semi-regu lar Archimedean solid s (whose faces are
regular n-gons wit h more t han one n in symmet r ic ar r angement ) employ
t hese solid angles. For inst ance, t he t r u ncat ed t et r ahed ron ad d s t he
oct ahed rons d ihed r al for hinges bet ween it s 3-gon and 6-gon faces,
suggest ive of it s complet e t runcat ion t o t he oct ahed ron.
Unaccou nt ed for ar e t he snub gu r es, for med by su r rou nd ing t he
ed ges of a regular solid s faces wit h equilat er al t r iangles. Snubbing t he
Table 11.
178
IV.3 EXACT DIHEDRAL METRICS FOR COMMON POLYHEDRA
GRAPHICS GEMS II Edit ed by JAMES ARVO 178
cube and d od ecahed ron creat es new solid s; t he snub oct ahed ron is t he
icosahed ron. This provid es a good t est for t he snub equat ion relat ing
d ihed r al t o pr incipal face t o ver t ex angle :
4 3 cos =

25 + 16 3sin

2
Likewise, snubbing a hexagonal plane t iling (which proper ly may be
regard ed as a 3-space polyhed ron of innit e volume) for ms t he cur ious
snub t iling of t he plane. In each case, t he algebr aic for m hold s, t hough an
obscure snub remains: The snub square ant i-pr ism (t he 85t h solid in a
complet e enumer at ion of polyhed r a, see (Johnson, 1966)). It has a d ihe-
d r al fr ust r at ingly close t o one for med given a ver t ex angle of = 75, yet
yield s only t o ot her met hod s (Linst er nik, 1963). Johnsons 84t h solid , t he
snub disphenoid, is t he only ot her snub having regular n-gon faces. It
may be d isregard ed , as it can be d ecomposed int o simpler solid s. The
Archimed ean snubs are present ed in Table II. A second , d ist inct d ihed r al
angle is present on t he t wo solid s of int erest bet ween t wo equilat er al
t r iangles, and is list ed in parent heses. Or t hogr aphic project ions of t wo
less-familiar solid s appear below.
rhombic d od ecahed r on icosid ad ecahed ron
179
IV.4 A SIMPLE VIEWING GEOMETRY
GRAPHICS GEMS II Edit ed by JAMES ARVO 179
IV.4 IV.4 IV.4 IV.4 IV.4
A AA AA SIMPLE VIEWING GEOMETRY SIMPLE VIEWING GEOMETRY SIMPLE VIEWING GEOMETRY SIMPLE VIEWING GEOMETRY SIMPLE VIEWING GEOMETRY
Andrew S. Glassner
Xerox PARC
Palo Alt o, Calif ornia
Somet imes, it is hand y t o be able t o set up a simple viewing geomet r y.
For example, packages wit hout mat r ix libr ar ies, quick preview hacks, and
simple r ay t r acer s all can benet from a simple viewing const ruct ion.
Here is one t hat I have found hand y.
The input is a viewpoint E, a gaze d irect ion and d ist ance G, an up
vect or U, and viewing half-angles and . The ou t p u t is a screen
mid point M and t wo vect or s, H and V, which are used t o sweep t he
screen. Figure 1 shows t he set up.
Fir st , creat e vect or A by A G U. (I assume r ight -hand ed cross
prod uct s.) Then nd B from B A G. Vect or B is coplanar wit h U and
G, but it is or t hogonal t o A and G. The mid point of t he screen is found
from M E + G. (Not e t hat t he lengt h of G t ells you how far away t he
viewscreen is locat ed .) Vect or s A and B span t he viewplane, but t hey are
t he wrong size. Find t he vect or H by scaling A by t he hor izont al half-
angle: H (A|G|t an)/ |A|. Similar ly, t he ver t ical vect or is found by
V (B|G|t an )/ |B|.
Assuming your or igin is in t he lower left , as shown, t hen any point S on
t he screen may be specied by (sx, sy), bot h number s bet ween 0 and 1.
(For example, if your fr ame buffer is 640 pixels wid e by 480 pixels high,
t hen (30, 250) would map t o (30/ 639, 250/ 479)). The point P on t he
image plane t hen is P M + (2s
x
1)H + (2s
y
1)V. If you prefer t o
have your or igin in t he upper left , t hen gener at e point s wit h t he equat ion
P M + (2s
x
1)H + (1 2s
y
)V.
180
IV.4 A SIMPLE VIEWING GEOMETRY
GRAPHICS GEMS II Edit ed by JAMES ARVO 180
Figur e 1.
If you are r ay t r acing, t he r ay equat ion would be R = E + (P E)t.
(You may wish t o nor malize (P E) before act ually shoot ing t he r ay.)
181
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 181
IV.5 IV.5 IV.5 IV.5 IV.5
V VV VVIEW CORRELATION IEW CORRELATION IEW CORRELATION IEW CORRELATION IEW CORRELATION
Rod G. Bogart
Universit y of Michigan
Ann Arbor, Michigan
To combine comput er-gener at ed object s int o a phot ogr aphic scene, it is
necessar y t o rend er t he object s from t he same point of view as was used
t o make t he phot o. This gem d escr ibes an it er at ive t echnique for cor relat -
ing view par amet er s t o a phot ogr aph image. The met hod is implement ed
in C (Append ix 2) as a user funct ion wit h a simple d r iver progr am for
t est ing. The following sect ions d escr ibe t he mat h behind t he it er at ive
t echnique, some species about t he given implement at ion, and an exam-
ple.
This met hod requires t hat at least ve point s are visible in t he phot o
image, and t hat t he 3D coord inat es of t hose point s are known. Lat er,
when a comput er-gener at ed object is mod eled , it must be in t he same 3D
sp ace as t he p hot o object s, and mu st u se t he same u nit s. It is not
necessar y for t he or igin t o be visible in t he phot o image, nor d oes it
assume a par t icular up d irect ion.
For each of t he ve (or more) d at a point s, t he 2D screen point must be
found . This can be d one simply by examining t he phot o image, or by
employing more ad vanced image processing t echniques. Because t his is
an it er at ive t echnique, t he 2D point need not be accur at e t o sub-pixel
d et ail. The nal set of view par amet er s will project t he given 3D point s t o
2D locat ions t hat have t he minimum er ror from t he given 2D screen
point s.
In ad d it ion t o t he d at a point s, an it er at ive process need s a st ar t ing
value. A set of view par amet er s must be given t hat approximat e t he
cor rect answer. The met hod is ext remely forgiving; however, it d oes help
if t he st ar t ing eye posit ion is at least in t he cor rect oct ant of 3-space, and
t he d irect ion of view looks t oward s t he cent er of t he 3D d at a.
182
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 182
Mat hemat i cal Basi s Mat hemat i cal Basi s Mat hemat i cal Basi s Mat hemat i cal Basi s Mat hemat i cal Basi s
The following equat ions d ene t he project ion equat ions used , along wit h
t he par t ial d er ivat ives need ed for Newt on it er at ion. The it er at ion process
consist s of nd ing t he er ror wit h t he cur rent viewing par amet er s, lling
t he Jacobian mat r ix wit h t he par t ial d er ivat ives, inver t ing t he Jacobian t o
nd t he cor rect ion values, and applying t he cor rect ion values t o t he
cur rent viewing par amet er s. Right -hand ed coord inat es and row vect or s
are used . The following var iables are d ened :
P 3D d at a point
E 3D eye point
T Tr anslat e by negat ive eye
R Viewing rot at e
Half of hor izont al view angle
r Aspect r at io for non-square pixels
x
s
Half X screen wid t h in pixels
x
c
X screen cent er ing
y
c
Y screen cent er ing
u Result ing screen X coord inat e
v Result ing screen Y coord inat e
The project ion equat ions are
PTR = [a b c],
u =

x
s
a
c tan
+ x
c
,
v =

r x
s
b
c tan
+ y
c
,
183
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 183
but it is d ifcult t o t ake t he par t ial d er ivat ives of u and v wit h respect t o
t he unknown view par amet er s. The par t ial of u wit h respect t o a is
simp le, bu t a is d ep end ent on t he u nknown eye p oint and rot at ion
mat r ix. Ther efore, t he p roject ion equ at ions ar e mod ied so t hat t he
par t ial d er ivat ives are easy t o nd .
Rat her t han subt r act ing t he eye point from P and r ot at ing t he result
(PTR), rewr it e t he equat ion by rot at ing each point and subt r act ing t he
result s:
PR ER = [a b c],
PR = [x y z],
[a b c] = [x y z] ER,
[a b c] =

x er
x
y er
y
z er
z [ ]
.
The symbols er
x
, et c. are just t he component s of t he rot at ed eye point .
The rot at ion mat r ix st ill is t he same one as in t he or iginal project ion
equat ions. Subst it ut ing for a, b, and c gives a set of project ion equat ions
t hat are easy t o d ifferent iat e. The expression 1/ t an is replaced by ds,
which simply is t he d ist ance t o t he screen d ivid ed by half t he screen
wid t h:
u =

ds x
s
x er
x
( )
z er
z
+ x
c
,
v =

ds r x
s
y er
y
( )
z er
z
+ y
c
.
The par t ial d er ivat ives for Newt ons met hod are found wit h respect t o
t he 10 it er at ion par amet er s: er
x
er
y
er
z

x

y

z
ds r x
c
y
c
. Not e t hat x
s
is const ant and is known from t he or iginal phot o image. The par ame-
t er s are t he ind ivid ual rot at ions about t he coord inat e axes. Alt hough t he
component rot at ions are not explicit ly referenced in t he project ion equa-
t ions, t hey are embod ied in x, y, and z. Therefore, t he par t ial u/
z
184
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 184
can be found by t he chain rule:


u

z

u
x
x

z
+
u
y
y

z
,

u
x

ds x
s
z er
z
,

u
y
0,


x

z
y ,


u

z

ds x
s
y
z er
z
.
The par t ial u/
z
follows from t he fact t hat (x, y, z) = (r cos
z
,
r sin
z
, z). Therefore, u/
z
= r sin
z
= y. The par t ial d er iva-
t ives wit h resp ect t o t he rest of t he it er at ion p ar amet er s are fou nd
d irect ly, or by applicat ions of t he chain rule, and are present ed in Table I.
The Jacobian mat r ix is simply composed of t hese equat ions evaluat ed
for each given d at a point . For example, if eight d at a point s were given,
t he Jacobian would have 10 rows (for t he it er at ion par amet er s) and 16
columns (for t he u and v par t ial d er ivat ive calculat ions for each given
point ).
The it er at ion process is simple. Fir st , t he 3D d at a point s are project ed
accor d ing t o t he cu r rent view p ar amet er s. The p r oject ed p oint s are
compared t o t he measured 2D d at a t o creat e a set of er ror t er ms. If t he
er ror s are below a pred et er mined t hreshold , t he it er at ion st ops. Ot her-
wise, t he Jacobian mat r ix is built as d escr ibed previously. To prod uce t he
cor rect ion values, t he Jacobian is inver t ed and mult iplied by t he er ror
t er ms. Since t he Jacobian probably is not a square mat r ix, t he pseud o-
inver se is calcu lat ed , (J
1
= J
T
(JJ
T
)
1
). The cor rect ion valu es ar e su b-
185
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 185
Table 1. Par t ial d er ivat ives of u and v wit h respect t o t he 10 it er at ion par amet er s.
t r act ed from t he cur rent it er at ion par amet er s t o creat e a new set of view
par amet er s. Then t he new view par amet er s are used t o project t he 3D
point s, and t he process begins again.
Impl ement at i on Det ai l s Impl ement at i on Det ai l s Impl ement at i on Det ai l s Impl ement at i on Det ai l s Impl ement at i on Det ai l s
The provid ed C Implement at ion (Append ix 2) cont ains t he view cor rela-
t ion rou t ines and a simp le p rogr am t o t est t hem. The t est p rogr am
accept s a le cont aining an init ial view and a set of 3D point s and t heir
186
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 186
2D screen locat ions. The progr am out put s t he cor relat ed view and t he
d at a point s, followed by par amet er s suit able for a specic r ay t r acing
progr am called rayshade.
Some rend erer s cannot hand le ar bit r ar y aspect r at ios, so it is possible
t o prevent t he aspect r at io from being it er at ed . The include le view-
corr.h has a #dene var iable t hat can be changed t o rest r ict t he aspect
r at io. The aspect r at io t hen should be set t o 1.0 in t he init ial set of view
par amet er s passed int o it erat e_view_parms.
It is imp or t ant t o choose ap p r op r iat e 3D p oint s for t he it er at ion
process. Alt hough t he algor it hm can prod uce cor rect result s wit h only
ve d at a point s, it is ad vant ageous t o have as many point s as possible. If
only ve point s are given t hat all lie in a 3D plane, t he process will fail.
Also, if t he 2D point s are near ly collinear, t he process will not it er at e
su ccessfu lly. Therefor e, it is best t o choose p oint s t hat wid ely sp an
3-space as well as spanning a large amount of screen area.
Figure 1 shows t he view geomet r y t hat can result from t he it er at ive
process. The view pyr amid on t he left shows t he line of sight as a d ot t ed
line t oward s t he cent er of t he screen (X
half
, Y
half
). However, t he int end ed
line of sight is t oward anot her point (X
cent er
, Y
cent er
) The view on t he r ight
Figure 1. View pyr amid geomet r y for rend er ing wit h it er at ed par amet er s.
187
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 187
shows a larger view pyr amid cent ered at (X
cent er
, Y
cent er
) and complet ely
enclosing t he or iginal screen. The cor r ect rend er ing is per for med by
implying a large screen, t hen rend er ing a small wind ow t hat is t he size of
t he or iginal image. Dur ing t he it er at ion process, t he d s value represent ed
t he eld of view shown on t he left . For rend er ing a wind ow of a larger
screen, t he eld of view must be scaled by t he r at io of t he new screen
d ivid ed by t he or iginal screen.
It shou ld be not ed t hat t he apply_correct ions rou t ine d oes not nd
t he ind ivid ual rot at ion par amet er s and subt r act t he cor rect ion values
Figur e 2. Example image.
188
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 188
Table 2. Init ial input le for example view cor relat ion.
from t hem. This would wor k only for ver y small changes t o t he rot at ion
par amet er s. Inst ead , t he cor rect ion values are built int o a single mat r ix,
and append ed t o t he cur rent view mat r ix.
Exampl e Exampl e Exampl e Exampl e Exampl e
The st ruct ure shown in Fig. 2 was built from br icks wit h known d imen-
sions. Therefore, it was simple t o choose a set of 3D point s and t he
cor respond ing 2D screen locat ions of t hose point s. The exact input for
t he viewnd progr am is shown in Table 2. The comment s t o t he r ight
are not par t of t he input le.
Table 3. Par amet er s for use wit h rayshade for t he example image.
screen 608 582
wind ow 224 198 607 581
eyep 248.932765 149.991910 239.688754
lookp 248.350545 149.572529 238.992235
up 0.592104 0.368372 0.716740
fov 25.338186 24.858782
189
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 189
Figur e 3. Example image wit h comput er-gener at ed object s.
Wit h t his input le, t he it er at ion st ops aft er 36 st eps, wit h a root -
mean -squ ar ed er r or of 0.446954. Th e n al rayshade p ar amet er s ar e
shown in Table 3. If t he init ial guess for t he up vect or is changed t o
(0, 1, 0), t he it er at ion t akes 116 st eps t o reach t he same values. When t he
up vect or is changed t o (0, 1, 0), t he eye point is set t o (100, 1000, 500),
and t he look point is set t o (300, 300, 300), t he it er at ion t akes 272 st eps.
On cur rent CPUs, 272 it er at ions occur in a few second s.
190
IV.5 VIEW CORRELATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 190
Figure 3 shows some ad d it ional br icks ad d ed by rend er ing an image of
t he t wo t ower s wit h t he new rayshade par amet er s. The r ayt r aced image
t hen was composit ed over t he or iginal phot o image.
Alt hough t his gem is int end ed for use wit h phot ogr aphic d at a, it can be
t est ed by prod ucing an image of known d at a wit h known par amet er s.
Then t he it er at ed par amet er s can be compared t o t he or iginal d at a.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 191
IV.6 IV.6 IV.6 IV.6 IV.6
M MM MMAINTAINING WINGED-EDGE AINTAINING WINGED-EDGE AINTAINING WINGED-EDGE AINTAINING WINGED-EDGE AINTAINING WINGED-EDGE
M MM MMODELS ODELS ODELS ODELS ODELS
Andrew S. Glassner
Xerox PARC
Palo Alt o, Calif ornia
The winged-edge d at a st ruct ure is a power ful mechanism for manipulat -
ing polyhed r al mod els. The basic id ea rest s on t he id ea of an ed ge and it s
ad jacent polygons. The name is d er ived by imagining t he t wo polygons as
a but t er ys wings, and t he ed ge as t he but t er ys bod y separ at ing t hem.
This simp le concep t p rovid es a basis for imp lement ing a var iet y of
power ful t ools for per for ming high-level oper at ions on mod els. The refer-
ences (Baumgar t , 1974), (Baumgar t , 1975), and (Hanr ahan, 1982) pro-
vid e d et ails on such high-level oper at ions as object -object int er sect ion,
union, d ifference, and collision d et ect ion.
There are sever al fund ament al oper at ions t hat a winged -ed ge libr ar y
must suppor t . Each oper at ion requires carefully moving and ad just ing a
var iet y of point er s. To illust r at e t he t ype of problem t hat must be solved ,
consid er t he t ask of inser t ing a new nod e N int o a simple d oubly linked
list bet ween nod es A and B. Each nod e has t wo point er s, prev and next ,
point ing t o t he previous and next nod e, respect ively. At t he t ime of
inser t ion, A.next = B and B.prev = A. If you inser t nod e N by set t ing
A.next N, and t hen set N.next A.next , you are in big t rouble, since
aft er assignment , N.next will p oint t o N, not B. If you make t hose
assignment s in t he opposit e ord er, all is well. This sor t of problem is
great ly mult iplied when moving point er s in a winged -ed ge libr ar yyou
have t o make sure you d o t hings in just t he r ight ord er, or d isast er will
ensue.
The pur pose of t his not e is t o d escr ibe how I solved some of what I
found t o be t he t r ickiest point er-st it ching problems in implement ing a
winged -ed ge libr ar y. A complet e d escr ipt ion of such a libr ar y would be
long and only repeat t he infor mat ion in t he references. Rat her, I will
suggest a gener al archit ect ure and d at a st r uct ures, and give recipes for
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 192
per for ming t hose basic mechanisms t hat require some care t o implement
cor rect ly.
I like t he archit ect ure suggest ed by Pat Hanr ahan. The gener al st r uc-
t ure is t hat faces, ed ges, and ver t ices each are st ored in a r ing (a d oubly
linked list ). A WShape cont ains t hree r ings, one each for faces, ed ges,
and ver t ices. Each ed ge r ing ent r y point s t o a d at a st ru ct u r e called
WEdgeDat a, which cont ains t he infor mat ion for t hat ed ge. Each face
cont ains an ed ge r ing d escr ibing t he ed ges around t hat face. Each ver t ex
cont ains an ed ge r ing of all ed ges around t hat ver t ex. All d uplicat e
inst ant iat ions of an ed ge point t o a single WEdgeDat a st r uct ure. (This
cont ains a point er back t o it s owner in t he mast er ed ge r ing in t he
WShape.) Not i ce t h a t t h er e i s a l ot of r ed u n d a n cy i n t h i s
ar chit ect u r et hat help s sp eed u p sear ches and comp lex op er at ions,
which t ypically st ar t from a face, ed ge, or ver t ex ad wor k from t here.
Figure 1 is a pict or ial d escr ipt ion of a WShape.
Figur e 1.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 193
Figur e 2.
The fund ament al build ing block in t he syst em is t he edge, represent ed
by an inst ance of t he WEdgeDat a d at a st ruct ure. An ed ge is a d irect ed
connect ion bet ween t wo ver t ices (from aVert ex t o bVert ex). Each ed ge
separ at es t wo faces. (Viewing t he ed ge as in Figure 2, aFace is below and
bFace is above; when following an ed ge aFace is on t he r ight looking
d own ont o t he out sid e of t he sur face, and bFace is on t he left .) An ed ge
has four wings; t hese are t he r st ed ges around t he ver t ex encount ered
in t h e sp ecied d ir ect ion . Refer r in g t o Fig. 2, on aFace we t r avel
clockwise from t he ed ge t o r each aCWedge, and cou nt erclockwise t o
reach aCCWedge; we t r avel similar ly for bFace and it s wings, bCWedge
a n d bCCWedge. Not e t h a t ot h er ed ges ma y sh a r e aVert ex a n d l i e
bet ween aCCWedge and bCWedge, but we only st ore t hese t wo out er-
most ed ges in t he WEdgeDat a d at a st r uct ure.
The basic d at a st r uct ures t o implement t his libr ar y are t he WShape,
WFace, WEdge, WVert ex, an d WEdgeDat a. Th e basi c comp on en t s of
t hese st ruct ures are given as follows. I have augment ed t he basic d at a
wit h an index eld and a client Dat a eld ; t he for mer is for bookkeeping
and d ebugging, and t he lat t er is a place for user s of t he libr ar y t o st ore
a point er t o any infor mat ion t hey wish t o associat e wit h an ind ivid ual
element .
ClockDirect ion: type{cw,ccw};
WShape: type record[
ver t exRing: WVer t ex ni l ,
ed geRing: WEd ge ni l ,
faceRing: WFace ni l ,
next , previous: WShape ni l ,
ind ex: i nt 0,
client Dat a: ref any ni l
];
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 194
WFace: type record[
ed geRing: WEd ge ni l ,
next , previous: WFace ni l ,
ind ex: ni l 0,
client Dat a: ref any ni l
];
WEd geDat a: type record[
aCWed ge, bCWed ge: WEd ge ni l ,
aCCWed ge, bCCWed ge: WEd ge ni l ,
aVer t ex, bVer t ex: WVer t ex ni l ,
aFace, bFace: WFace ni l ,
ind ex: i nt 0,
owner : WEd ge ni l ,
client Dat a: ref any ni l
];
WEd ge: type record[
ed geDat a: WEd geDat a ni l ,
next , previous: WEd ge ni l ,
client Dat a: ref any ni l
];
WVer t ex: type record[
basicVer t ex: poi nt,
ed geRing: WEd ge ni l ,
next , previous: WVer t ex ni l ,
ind ex: i nt 0,
client Dat a: ref any ni l
];
Wit h t hese d at a st r u ct u r es in hand , we can consid er some of t he
funct ions a winged -ed ge libr ar y need s t o suppor t . One common oper at ion
when const r uct ing a mod el is embod ied in t he proced ure Set Wings. This
t akes a pair of ed ges wit h a common ver t ex, and d et er mines t heir wing
infor mat ion. There are eight ways t he ed ges might be relat ed when t hey
come int o t he proced ure; Fig. 3 ind icat es how t o set t he point er s. (This is
ad apt ed from page 22 of Baumgar t (1974).) In t he gure, aF and bF
st and for aFace and bFace, and aCW, bCW, aCCW, and bCCW st and
for t he ed ges wit h t hose prexes.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 195
Figur e 3.
The inp u t t o Set Wings is t wo ed ges, e1 and e2. The fou r colu mns
d ist inguish t he four cases t hat id ent ify t he ver t ex shared by t he ed ges.
Each column has t wo illust r at ed cases, d epend ing on how t he ed ges are
shared . The cases are id ent ied using t he equalit y just und er each pict ure.
When a d iagr am is id ent ied as d escr ibing t his pair of ed ges, t he assign-
ment s below t he t est are ap p lied t o t he inp u t ed ges. For examp le,
suppose your input is t wo ed ges, e1 and e2. If e1.aVert ex = e2.bVert ex,
t hen you are in t he second column. Then if e1.aFace = e2.aFace, you
ar e in t he bot t om half of t he second colu mn, and you wou ld set
e1.aCCWedge e2 and e2.aCWedge e1.
Con si d er n ext a u sefu l r ou t i n e cal l ed Next FaceA roundVert ex. Th i s
t akes a ver t ex, a face, and a d irect ion, and ret ur ns t he next face around
t hat ver t ex in t he given d irect ion. Begin by nd ing any ed ge t hat is on t he
inpu t face and cont ains t hat ver t ex. (Call t his ed ge e.) As wit h t he
previous pr oced ure, t here are eight possible geomet r ic congur at ions;
id ent ifying t he one at hand allows you t o d et er mine t he next face around
t he ver t ex. We assu me a p roced u r e called FaceAcrossEdge, which ac-
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 196
Figur e 4.
cept s an ed ge and face, and ret ur ns t he ot her face shar ing t hat ed ge.
(Su ch a p r oced u r e i s ea sy; i f t h e i n p u t fa ce i s edge. aFace, r et u r n
edge.bFace, and vice ver sa.)
Figu r e 4 illu st r at es t he logic behind Next FaceAroundVert ex. In t he
d iagr am, t he input ver t ex is common t o all t hree shapes; it is mar ked wit h
a circle. The input face is shad ed in gr ay. Ed ge e, t he ed ge you nd on
t he face and ver t ex, is ind icat ed wit h an ar row. In each por t ion of t he
gure, t he d esired face is mar ked wit h a st ar ; t he t r iangle is t he next face
clockwise, and t he rect angle is t he next face count erclockwise. In each
case, we ret ur n t he face across an ed ge wit h respect t o t he input face; t he
cor rect ed ge t o use is shown in bold . In four cases, t hat ed ge is just e; t he
ot her four cases each use one of t he wings of e. The legend s r efer t o
t he posit ion of t he passed -in ver t ex and face wit h respect t o e. Each case
is mar ked wit h t he name of t he ed ged used t o nd t he next face, opposit e
t he input face; t his ed ge is mar ked in bold .
For examp le, su p p ose you are given input Face and input Vert ex and
t he d irect ion clockwise. Since clockwise was specied , you know you
care about t he upper row of t he char t . You search t he ver t ex or face for
an ed ge e on t hat ver t ex and face. Now, nd on which sid e of e lies
input Face; suppose input Face = e.bFace, which is t he sit uat ion for t he
t wo r ight most columns. To d ist inguish now bet ween t he t wo r ight most
ent r ies on t he t op row, nd which ver t ex of e is input Vert ex; suppose
e.bVert ex = input Vert ex. Then you are in t he r ight most column of t he
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 197
Figur e 5.
t op row, or t he upper r ight cor ner, and you would call FaceAcrossEdge
(e.bCCWedge, input Face) t o nd and ret ur n t he new face.
Consid er next t he basic op er at ions when mod ifying a winged -ed ge
mod el: These t ypically are known as Euler operat ors, since t hey p re-
ser ve t he Euler char act er ist ic number of t he mod el. One of t he basic
Euler oper at or s is Split Edge, which simply inser t s a new ver t ex int o a
single ed ge, split t ing it in t wo, as shown in Fig. 5.
I say simply ad vised ly, since nd ing t he proper sequence in which t o
move t he point er s can be a lit t le t r icky t o get r ight . Par t of t he problem
is t hat t he d at a st ruct ure I d escr ibed before has a lot of red und ancy, so
t here are many point er s t o move. As wit h t he linked -list example, you
have t o make sure you move your point er s in t he r ight ord er or you will
end up wit h d isast er. Figure 6 shows t he ord er of int erconnect of t he
links. The d iagr am follows Fig. 5; t he bold ed ge and ver t ex on t he r ight
sid e are t he new element s. A * ind icat es t hat a copy of t he ind icat ed ed ge
Figur e 6.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 198
is creat ed (but not t he d at a t o which it point s). The links mar ked wit h a
P are inher it ed from t he input (or parent ) ed ge.
St ep 1: Creat e t he new ed ge and it s d at a st ruct ures.
St ep 2: Creat e t he new ver t ex and it s d at a st ruct ures.
St ep 3: Hook t he ed ge int o t he object ed ge r ing.
St ep 4: Hook t he ver t ex int o t he object ver t ex r ing.
St ep 5: Hook t he new ed ge int o t he ed ge r ings for bot h faces.
St ep 6: Point t he new ver t ex at t he t wo ed ges.
St ep 7: Set up t he st ar t ing ver t ex of t he new ed ge.
St ep 8: Direct t he old ed ge t o t he new ver t ex.
St ep 9: Hook back t he old bVert ex int o t he new ed ge.
St ep 10: Connect t he aCW wings.
St ep 11: Connect t he bCCW wings.
St ep 12: Connect t he back wings of t he new ed ge t o t he old ed ge.
St ep 13: Connect t he front wings of t he old ed ge t o t he new ed ge.
Anot her common op er at ion is RemoveEdge. This r ou t ine accep t s an
ed ge as input , and removes t hat ed ge, merging t he t wo faces t hat share it ,
Figure 7 shows t he ord er for set t ing t he links.
St ep 1: Delet e t he point er from ver t ex a t o t he ed ge.
St ep 2: Delet e t he point er from ver t ex b t o t he ed ge.
St ep 3: Repoint all ed ges point ing t o face b t o point t o face a.
St ep 4: Build t he new ed ge r ing for face a.
St ep 5: Link t he old wings on aVert ex.
St ep 6: Link t he old wings on bVert ex.
St ep 7: Delet e bFace from object .
St ep 8: Delet e ed ge from object .
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 199
object face r ing: 7 object ed ge r ing: 8
Figur e 7.
The op p osit e op er at ion is Insert Bridge, which t akes t wo ver t ices as
input s and build s a new ed ge bet ween t hem. In Fig. 8, t he ed ge is d irect ed
from vl t o v2. A * ind icat es t hat a copy of t he ind icat ed ed ge is creat ed
(but not t he d at a t o which it point s). The new ed ge is shown in bold . Links
labeled wit h P are inher it ed from t he input (or parent ) congur at ion.
St ep 1: Creat e t he new ed ge.
St ep 2: Ad d t he new ed ge t o t he object s ed ge r ing.
St ep 3: Creat e t he new face.
St ep 4: Ad d t he new face t o t he object s face r ing.
St ep 5: Assign t he r st ver t ex t o t he new ed ges t ail.
St ep 6: Assign t he second ver t ex t o t he new ed ges head .
St ep 7: Inser t t he new ed ge int o t he ed ge list at t he head ver t ex.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 200
object ed ge r ing: 2 new face: 3 object face r ing: 4
Figure 8.
St ep 8: Inser t t he new ed ge int o t he ed ge list at t he t ail ver t ex.
St ep 9: Link t he new ed ge t o t he new face.
St ep 10: Link t he new ed ge t o t he old face.
St ep 11: Build t he ed ge r ing for t he new face.
St ep 12: Set t he ed ges around t he new face t o point t o t he new face.
St ep 13: Build t he ed ge r ing for t he old face, and point t he ed ges at
t he new face.
St ep 14: Link t he new face t o t he new ed ge.
St ep 15: Link t he old face t o t he new ed ge.
St ep 16: Set t he new ed ges aCW wings.
St ep 17: Set t he new ed ges bCCW wings.
IV.6 MAINTAINING WINGED-EDGE MODELS
GRAPHICS GEMS II Edit ed by JAMES ARVO 201
St ep 18: Set t he new ed ges bCW wings.
St ep 19: Set t he new ed ges aCCW wings.
Cleanup: Reclaim old face ed ge r ing, and replace old face ed ge r ing
wit h new.
The infor mat ion given in t his gem cer t ainly is not enough t o implement
an ent ire libr ar y; I have provid ed only some signpost s around what I
found t o be t he most t wist ing par t s of t he road . For more infor mat ion on
winged -ed ge d at a st ruct ures and t heir use, please consult t he references.
202
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 202
IV.7 IV.7 IV.7 IV.7 IV.7
QUADTREE/ OCTREE- QUADTREE/ OCTREE- QUADTREE/ OCTREE- QUADTREE/ OCTREE- QUADTREE/ OCTREE-
T TT TTO-BOUNDARY CONVERSION O-BOUNDARY CONVERSION O-BOUNDARY CONVERSION O-BOUNDARY CONVERSION O-BOUNDARY CONVERSION
Claudio Mont ani and Robert o Scopigno
Consiglio Nazionale delle Ricerche
Pisa, It aly
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Numerous and wid ely d ifferent iat ed are t he cod ing schemes proposed for
t he represent at ion and manipulat ion of t wo-d imensional and t hree-d imen-
sional spat ial infor mat ion: from analyt ical t o vect or ial, from r ast er t o
cellu lar or hier archical, from p ar amet r ic t o algebr aic. Each of t hese
represent at ion schemes present s peculiar char act er ist ics wit h reference
t o t he st or age cost s, t he efciency of t he algor it hms, t he simplicit y of t he
d at a manipulat ion, and so on. For t hese reasons, it is common t o use
mult iple d at a represent at ion schemes t o fulll t he required space-t ime
efciency. The quest for efcient scheme conver sion algor it hms always
has been a cent r al t heme in t he problem of t he represent at ion of spat ial
d at a.
An al gor i t h m for t h e con ver si on fr om h i er ar ch i cal r ep r esen t at i on
(quad t ree or oct ree) (Samet et al., 1988, 1990) t o bound ar y is present ed
in t his gem. The algor it hm ret u r ns t he bou nd ar y of t he rep r esent ed
object s in t er ms of a list of polygon bord er s (2D case) or a list of faces
(3D case). The proposed approach can be applied easily t o r ast er or voxel
represent at ion, t oo.
The algor it hm comput es t he bound ar y of t he represent ed regions (or
faces), t aking int o account possible holes, and requires only one complet e
visit of t he hier archical st ruct ure. The hier archical st ruct ure is visit ed
wit h a simple d ept h-r st cr it er ion, and more complex neighbor-nd ing
t echniques (Samet , 1982) are not request ed (Dyer, 1980); t his char act er-
ist ic mad e it possible t o apply t his conver sion algor it hm on bot h point er
and point er less QT/ OT (Gargant ini, 1982a, 1982b), wit h t he same ef-
ciency. The algor it hm makes use of a t wo-st ep approach: It r st conver t s
203
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 203
Figur e 1. A simple example of 2D d r awing
t he hier archical st ruct ure in a r ast er-based t empor ar y d at a st ruct ure, t he
Par allel Connect ed St r ipes (PCS) (Mont ani, 1984); t hen t he bound ar y of
t he represent ed regions is reconst ruct ed by wor king on t he PCS represen-
t at ion. This represent at ion mad e it possible t o reconst ruct efcient ly t he
maximal connect ed polygonal bord er s/ regions t hat const it ut e a bound ar y
represent at ion of t he or iginal hier archical d at a. The polygonal bord er s are
ret ur ned in t he common 4-d irect ions Freemans chains (Freeman, 1974);
t he algor it hm ret ur ns clockwise bound ar ies of t he represent ed regions or
object s and count erclockwise bound ar ies of t he holes.
The The The The The PCS PCS PCS PCS PCS Repr esent at i on Scheme Repr esent at i on Scheme Repr esent at i on Scheme Repr esent at i on Scheme Repr esent at i on Scheme
Figure 2 shows t he PCS represent at ion (Mont ani, 1984) for t he regions of
t he binar y map of Fig. 1. The or iginal 2D space is su bd ivid ed int o
hor izont al st ripes of t hickness equal t o t he st ep size of t he reference gr id
(for simplicit ys sake, t he st ep size being 1 in our examples); t he int er sec-
t ion of each st r ip e wit h t he regions of t he map gener at es a set of
rect angular subst ripes cor respond ing t o t he par t of t he regions int er nal t o
t he st r ipe.
Each st r ipe can be d escr ibed by st or ing it s ord inat e (t he ord inat e of t he
lower sid e), t he number of subst r ipes, and t he list of t he abscissas of t he
204
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 204
Figur e 2. The PCS represent at ion of t he example in Fig. 1.
Table 1. Numer ical represent at ion of t he PCS d at a st r uct ure for t he example in Fig. 2.
west and east sid es of each subst r ipe. Table 1 shows t his infor mat ion for
t he example of Fig. 2.
P PP PPCS CS CS CS CS- t o- Boundar y Conver si on - t o- Boundar y Conver si on - t o- Boundar y Conver si on - t o- Boundar y Conver si on - t o- Boundar y Conver si on
The conversion from PCS representation to boundary is very simple. (Actually,
t h e a l gor i t h m r et u r n s 4-d i r ect i on s Fr eema n s ch a i n s (Fr eema n ,
1974).) It is possible t o walk from one subst r ipe of y ord inat e t o one of
205
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 205
y + 1 or y 1 or d inat e only if t hese are connect ed (i.e., have one
hor izont al sid e or par t of it in common); it is possible t o walk from one
subst r ipe of y ord inat e t o anot her of t he same ord inat e only if t here is a
subst r ipe of y + 1 or y 1 ord inat e connect ing t hem.
The algor it hm consist s of t wo st eps: a r st st ep in which a st ar t ing
p oint for t he chain is sear ched for (PCS_To_Chain p roced u r e) and a
second st ep in which t he chain is const r u ct ed walking t hrou gh t he
st r ip es (Bot t om_Up and Top_Down p r oced u res). The r st st ep is r e-
peat ed unt il all of t he out er bound ar ies (or holes) of t he d at a st ruct ure
have been d et ect ed . To avoid end less reconst ruct ion, each subst r ipe sid e
alread y consid ered in t he conver sion process is mar ked .
The PCS_To_Chain proced ure (Fig. 3) searches for a subst r ipe wit h at
least one unmar ked sid e. If t he unmar ked sid e is t he west sid e of t he S
y
i
subst r ipe (i.e., t he it h subst r ipe in t he st r ipe of ord inat e y), t he point
(Absc(S
i
y
, W), y) is chosen as t he beginning point of t he out put chain,
and t he algor it hm st ar t s t o reconst r u ct clockwise t he bou nd ar y of a
region, act ivat ing t he Bot t om_Up proced ure (Fig. 4) on t he subst r ipe S
y
i
.
PCS_t o_Chain( )
begi n
for y: i nteger YMIN, y y + 1 WHILE y < YMAX do
for i: i nteger 0, i i + 1 WHILE i < Ss_Num(y) do
begi n
i f Check_Mar k(S
y
i
, W) = FALSE then
begi n
Init _Chain(Absc(S
y
i
, W), y);
Bot t om_Up(S
y
i
);
Display_Chain( );
end;
el se i f Check_Mar k(S
y
i
, E) = FALSE then
begi n
Init _Chain(Absc(S
y
i
, E), y + 1);
Top_Down(S
y
i
);
Display_Chain( );
end;
endl oop;
end PCS_t o_Chain;
Figur e 3. PCS_t o_Chain pr oced ure.
206
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 206
Bot t om_Up(S
y
i
)
begi n
i f Check_Mar k(S
y
i
, W) = FALSE then
begi n
Fig. 6a Ad d _Link(l, 1);
Mar k(S
y
i
, W);
for k: i nteger 0, k k + 1 whi l e k < Ss_Num(y + 1) do
i f (Absc(S
y
i
, W) < Absc(S
k
y+l
, E)) and
(Absc(S
y
i
,E) > Absc(S
k
y+l
,W)) do
begi n
p Absc(S
k
y+l
, W);
i f Absc(S
y
i
, W) p then
begi n
Fig. 6b/c Ad d _Link(p-Absc(S
y
i
, W),0);
Bot t om_Up(S
k
y+l
);
return;
end;
el se i f (i = 0) or (Absc(S
y
i1
, E) p) then
begi n
Fig. 6g Ad d _Link(Absc(S
y
i
, W) p,2);
Bot t om_Up(S
k
y+l
);
return;
end;
el se
begi n
Fig. 6f Ad d_Link(Absc(S
y
i
, W) Absc(S
y
i+1
, E),2);
Top_Down(S
y
i1
);
return;
end;
end;
Fig. 6e Ad d _Link(Absc(S
y
i
, E) Absc(S
y
i
, W),0);
Top_Down(S
y
i
);
end;
end; Bot t om_Up;
Figur e 4. Bot t om_Up proced ure.
207
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 207
Alt er nat ively, if t he west sid e of t he subst r ipe is mar ked and t he east sid e
is not , we ind icat e wit h (Absc(S
y
i
, E), y + 1) t he beginning point of t he
out put chain and go on t o reconst ruct count erclockwise t he bound ar y
of a h ol e act i vat i n g t h e Top_Down p r oced u r e (Fi g. 5) on S
y
i
. Wi t h
Absc(S
y
i
, P), we ind icat e t he abscissa of t he P sid e (west or east ) of t he
S
y
i
, subst r ipe.
The cer t aint y in consid er ing t hat t he r st case d eals only wit h t he out er
front ier of a region, and t he second only wit h holes, hold s because:
(a) t he st ar t ing point is searched from t he bot t om upward s and from left
t o r ight , and
(b) by d enit ion of t he PCS, t he non-empt y space is on t he r ight of each
west sid e (i.e., t he inside of a region), while t he empt y space is on
t he r ight of t he east sid es.
The d ifferent d irect ions (clockwise and count erclockwise) of t he chains
d escr ibing t he ou t er bou nd ar ies or t he holes of t he regions are not
obt ained by ad opt ing d ifferent proced ures or inver t ing t he chains re-
t ur ned , but , conver sely, using t he same algor it hm t hat follows t he sid es
and t he bases of t he subst r ipes, which always leaves t he inside of t he
regions t o t he r ight and t he out side t o t he left .
The recur sive proced ure Bot t om_Up is invoked on a subst r ipe S
y
i
; it
ad d s an upward ver t ical link t o t he cur rent chain and t hen searches in t he
st r ipe of ord inat e y + 1 (scanning from left t o r ight ) for a subst r ipe
t op-connect ed t o S
y
i
.
If such a subst r ipe (S
k
y+1
) exist s and
Absc(S
y
i
, W) Absc(S
k
y+1
, W),
t he proced ure (Figs. 6B and 6C) prod uces t he left ward hor izont al links
associat ed t o t he upper sid e of S
y
i
not ad jacent t o S
k
y+1
; t hen, Bot t om_Up
invokes it self on t he S
k
y+1
subst r ipe.
If, ot h er wi se, t h e t op -con n ect ed su bst r i p e S
k
y+1
i s i n t h e op p osi t e
relat ion wit h S
y
i
(Fig. 6D),
Absc(S
y
i
, W) > Absc(S
k
y+1
, W),
t he proced ure analyzes t he posit ion of t he (i 1)t h subst r ipe of t he
ord inat e y. In t he case of Fig. 6F, Bot t om_Up ret ur ns a set of left ward
hor izont al links and t hen it act ivat es Top_Down on t he subst r ipe S
y
i 1
.
208
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 208
Top_Down(S
i
y
)
begi n
i f Check_Mar k(S
i
y
, E) = FALSE then
begi n
Fig. 7a Ad d _Link(1,3);
Mar k(S
i
y
, E);
for k: integer Ss_Num(y 1) 1, k k 1 while k 0 do
i f (Absc(S
i
y
, W) < Absc(S
k
y1
, E)) and
(Absc(S
i
y
, E) > Absc(S
k
y1
, W)) do
begi n
p Absc(S
k
y1
, E);
i f Absc(S
i
y
, E) p then
begi n
Fig. 7b/ c Ad d _Link(Absc(S
i
y
, E) p,2);
Top_Down(S
k
y1
);
return;
end;
el se i f (i = Ss_Num(y) 1) or
(Absc(S
y
i+1
, W) p) then
begi n
Fig. 7g Ad d _Link(p-Absc(S
i
y
, E),0);
Top_d own(S
k
y1
);
return;
end;
el se
begi n
Fig. 7f Ad d _Link(Absc(S
y
i+1
, W) Absc(S
i
y
, E), 0);
Bot t om_Up(s
y
i+1
);
return;
end;
end;
Fig. 7e Ad d _Link(Absc(S
i
y
,E) Absc(S
i
y
, W), 2);
Bot t om_Up(S
i
y
);
end;
end Top_Down;
Figure 5. Top_Down pr oced ure.
209
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 209
Figure 6. Bot t om_Up pr oced ure: possible sit uat ions d ur ing t he bot t om-up bound ar y
reconst ruct ion.
Conver sely, as in Fig. 6G, Bot t om_Up invokes it self on t he S
k
y+1
su b-
st r ipe.
Finally, if a t op-connect ed subst r ipe S
k
y+1
d oes not exist (Fig. 6E), t he
p roced u r e ad d s t o t he ou t p u t chain Absc(S
i
y
, W) Absc(S
i
y
, E) r ight -
ward hor izont al links and invokes Top_Down on t he same subst r ipe.
Similar ly, changing appropr iat ely t he t er ms and d irect ions of move-
ment , t he Top_Down proced ure (Fig. 7) can be d escr ibed . Table 2 shows
t he Freeman chains prod uced by t he applicat ion of t he algor it hm t o t he
example of Fig. 2. It also shows which proced ure has prod uced t he links
in t he chains t o give a clearer id ea of t he conver sion process.
The p seu d o-cod e p roced u r es of Figs. 3, 4, and 5 make u se of t he
following simple funct ions:
Ss_Num(y): ret ur ns t he number of subst r ipes belonging t o t he st r ipe of
ord inat e y;
Absc(S
i
y
, P): ret ur ns t he abscissa of t he P sid e (West or East ) of t he it h
subst r ipe of t he st r ipe of ord inat e y;
210
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 210
Figure 7. Top_Down proced ure: possible sit uat ions d ur ing t he t op-d own bound ar y
reconst ruct ion.
Mark(S
i
y
, P): mar ks t he P sid e (west or east ) of t he subst r ipe S
i
y
;
Check_Mark(S
i
y
, P): ret u r ns false if t he P sid e of t he su bst r ip e S
i
y
is
mar ked , t rue ot her wise;
Init _Chain(x,y): init ializes a new Freeman chain wit h st ar t ing p oint
(x,y);
Add_Link(n,t ): ad d s t o t he cu r rent chain n links (p ossibly none) of
t ype t (being t in t he r ange {0, 1, 2, 3});
Ret urn_Chain(): ret u r ns t he const ru ct ed Freeman chain; t he effect ive
act ion is implement at ion-d epend ent : t he ret ur ned chain act ually can
be d isplayed or st ored .
It is wor t hwhile t o not e t hat t he algor it hm ret ur ns clockwise bound ar ies
of t he regions and count erclockwise bound ar ies of t he holes. This char ac-
t er ist ic is found t o be ver y impor t ant for t he cor rect management and
subsequent processing of ret ur ned infor mat ion.
211
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 211
Table 2. Applying t he PCS-t o-chains conver sion algor it hm t o t he example of Fig.2.
Becau se t he hor izont al links of t he ou t p u t chains are p rod u ced as
connect ions bet ween t wo ver t ical links, t he comput at ional complexit y of
t he PCS_To_Chain algor it hm is propor t ional t o t he number of subst r ipes
of t he PCS d at a st ruct ure r at her t han t o t he per imet er of t he regions. In
real cases, t he search for a t op-connect ed or bot t om-connect ed subst r ipe
is propor t ional t o t he number of d ist inct regions and holes of t he map.
Quadt r ee- t o- Boundar y Conver si on Quadt r ee- t o- Boundar y Conver si on Quadt r ee- t o- Boundar y Conver si on Quadt r ee- t o- Boundar y Conver si on Quadt r ee- t o- Boundar y Conver si on
The Quadt ree-t o-Boundary conver sion is r ealized by r st ap p lying a
Quadt ree-t o-PCS conver sion and t hen reconst ruct ing t he bound ar y of t he
represent ed regions by using t he for mer PCS-t o-Chain proced ure.
The recur sive proced ure Quadt ree-t o-PCS (Fig. 8) here is d ened for
t he binar y point er-based quad t ree, and can be ext end ed easily t o t he
more gener al case of n-level point er or point er less quad t ree. The par am-
et er s of t h e Quadt ree-t o-PCS p r oced u r e a r e t h e p oi n t er Q t o t h e
quad t ree, t he widt h of t he space 2
n
2
n
of d enit ion of t he quad t ree
(widt h = 2
n
), and t he coord inat e x, y of t he lower left cor ner of t he
212
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 212
Quad t ree_t o_PCS (Q, wid t h, x, y)
begi n
i f Nod e_Type(Q) = BLACK then
for i: i nteger 0, i i + 1, whi l e i < wid t h do
begi n
Sid e_Inser t (x, y + i);
Sid e_Inser t (x + wid t h, y + i);
end;
el se i f Nod e_Type (Q) = GRAY then
begi n
hw = wid t h/ 2;
Quad t ree_t o_PCS (Son(Q, NW), hw, x, y + hw);
Quad t ree_t o_PCS (Son(Q, NE), hw, x + hw, y + hw);
Quad t ree_t o_PCS (Son(Q, SW), hw, x, y);
Quad t ree_t o_PCS (Son(Q, SE), hw, x + hw, y):
end;
end Quad t ree_t o_PCS;
Figure 8 Quadt ree_t o_PCS proced ure.
d enit ion space wit h respect t o a global coord inat e space. The proced ure
visit s t he quad t ree and , for each black nod e, inser t s in t he PCS d at a
st r uct ure t he set of subst r ipes cor respond ing t o t he nod e. For each nod e
at level i in t he quad t ree, 2
n-i
subst r ipes of lengt h 2
ni
will be inser t ed
in t he PCS.
The following simple funct ions are used in t he pseud o-cod e d escr ipt ion
of Quadt ree-t o-PCS proced ure:
Node_Type (Q): ret ur ns t he t ype (Black, Whit e, or Gr ay) of t he nod e Q;
Side_Insert (x,y): inser t s in t he st r ipe y of t he PCS d at a st ruct ure a
subst r ipe sid e wit h abscissa x; t he sid es are inser t ed int o st r ipe y in
ascend ing ord er wit h respect t o t he abscissa value. If a sid e wit h t he
same x value is cont ained alread y in t he PCS, t hen t he new sid e is
not inser t ed and t he old one is d elet ed ; in t his way, t wo subst r ipes
wit h a sid e in common are unied in a single one;
Son(Q, P): ret ur ns t he point er t o t he P son (wit h P in {NW, NE, SW, SE})
of t he Q nod e.
213
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 213
Th e p r oced u r e Quadt ree-t o-PCS r et u r n s a PCS d a t a st r u ct u r e i n
which a list of sid es is associat ed t o each st r ipe, ord ered by increasing
abscissa value. By d enit ion, t he od d sid es in t he list are west sid es of
subst r ipes, while t he even are east sid es; moreover, by d enit ion of t he
proced ure Side_Insert , each couple of successive od d and even sid es in
each st r ipe ind ivid uat es one of t he maximal lengt h subst r ipes obt ained by
int er sect ing t he area d escr ibed by t he quad t ree wit h t hat st r ipe. Figure 9
Figure 9. The making of t he PCS d at a st ruct ure d ur ing t he d ept h-r st visit of t he
quad t ree.
214
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 214
shows t he conver sion st eps required t o conver t t he quad t ree represent ing
t he regions of t he example in Fig. 1.
The comp lexit y of t he Quadt ree-t o-PCS algor it hm simp ly is p r op or-
t ional t o t he number of black nod es in t he quad t ree.
Oct r ee- t o- Boundar y Conver si on Oct r ee- t o- Boundar y Conver si on Oct r ee- t o- Boundar y Conver si on Oct r ee- t o- Boundar y Conver si on Oct r ee- t o- Boundar y Conver si on
To int rod u ce t he t hr ee d imensional ext ension of t he p reced ing algo-
r it hms, t he Oct ree-t o-Boundary conver sion algor it hm, let u s d escr ibe
how t o conver t a simple oct ree composed of one black nod e only (Fig.
10); let t he wid t h of t he nod e be 2
n
. We d ene six d ifferent PCSs, t he r st
couple represent ing t he planes X = 0 and X = 2
n
par allel t o t he plane
YZ; t he second couple, Z = 0 and Z = 2
n
par allel t o t he plane XY; and
t he t hird couple, Y = 0 and Y = 2
n
par allel t o t he plane ZX. We t hen can
conver t t he oct ree by d ening t he six PCSs represent ing t he six faces of
t he root black nod e. Once t he six PCSs are const ruct ed , it is possible t o
apply t he PCS-t o-Chain proced ure t o each of t hem and , t herefore, obt ain
Figure 10. Conver t ing a Black nod e of an oct ree int o six PCS d at a st ruct ures.
215
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 215
Oct ree_t o_PCS(Q, wid t h, x, y, z)
begi n
if Nod e_Type(Q) = BLACK then
for i: i nteger 0, i i + 1, whi l e i < wid t h do
begi n
Sid e_Inser t _XY(z, x, y + i);
Sid e_Inser t _XY(z, x + wid t h, y + i);
Sid e_Inser t _XY(z + wid t h, x, y + i);
Sid e_Inser t _XY(z + wid t h, x + wid t h, y + i);
Sid e_Inser t _ZY(x, z, y + i);
Sid e_Inser t _ZY(x, z + wid t h, y + i);
Sid e_Inser t _ZY(z + wid t h, z, y + i);
Sid e_Inser t _ZY(x + wid t h, z + wid t h, y + i);
Sid e_Inser t _XZ(y, x, z + i);
Sid e_Inser t _XZ(y, x + wid t h, z + i);
Sid e_Inser t _XZ(y + wid t h, x, z + i);
Sid e_Inser t _XZ(y + wid t h, x + wid t h, z + i);
end;
el se i f Nod e_Type(Q) = GRAY then
begi n
hw = wid t h/ 2;
Oct ree_t o_PCS(Son(Q, FNW), hw, x, y + hw, z);
Oct ree_t o_PCS(Son(Q, FNE), hw, x + hw, y + hw, z);
Oct ree_t o_PCS(Son(Q, FSW), hw, x, y, z);
Oct ree_t o_PCS(Son(Q, FSE), hw, x + hw, y, z);
Oct ree_t o_PCS(Son(Q, BNW), hw, x, y + hw, z + hw);
Octree_to_PCS(Son(Q, BNE), hw, x + hw, y + hw, z + hw);
Oct ree_t o_PCS(Son(Q, BSW), hw, x, y, z + hw);
Oct ree_t o_PCS(Son(Q, BSE), hw, x + hw, y, z + hw);
end;
end Quad t ree_t o_PCS;
Figure 11. Oct ree_t o_PCS proced ure.
216
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 216
Figure 12. A 3D example.
Figur e 13. The PCS d at a st ruct ures for t he XY faces of t he example.
217
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 217
Figure 14. The PCS d at a st ruct ures for t he YZ faces of t he example.
Figure 15. The PCS d at a st r uct ures for t he XZ faces of t he example.
218
IV.7 QUADTREE/ OCTREE-TO-BOUNDARY CONVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 218
t he Freeman encod ed d escr ipt ion of t he polygonal faces t hat bound t he
polyhed r ical volume represent ed by t he oct ree.
The for mer approach is gener alized in t he Oct ree-t o-PCS proced ure in
Fig. 11. For each black nod e of t he oct ree, t he six faces are conver t ed in
subst r ipes and inser t ed int o six PCSs, each of t hem associat ed t o t he
plane on which t he faces of t he nod e lie. The proced ure makes use of t he
following simple funct ions:
Side_Insert _XY (z, x, y): inser t s a subst r ipe sid e of y ord inat e and x
abscissa in t he PCS t hat represent s t he plane Z = z;
Side_Insert _ZY (x, z, y): inser t s a subst r ipe sid e having ord inat e y and
abscissa z in t he PCS t hat represent s t he plane X = x;
Side_Insert _XZ (y, x, z): inser t s a subst r ipe sid e having ord inat e z and
abscissa x in t he PCS t hat represent s t he plane Y = y.
Analogously t o t he Side_Insert proced ur e d escr ibed for t he Quadt ree-
t o-Boundary conver sion algor it hm, in each of t he p reced ing r ou t ines,
couples of sid es wit h id ent ical coord inat es are d elet ed from t he PCS d at a
st ru ct u r e. The conver sion of t he obt ained set of PCSs int o Freeman
chains is t he same as t he 2D case.
In Figs. 1315 are t he t hree set s of faces ret ur ned by t he algor it hm
when applied t o t he example of Fig. 12.
219
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 219
IV.8 IV.8 IV.8 IV.8 IV.8
THREE-DIMENSIONAL THREE-DIMENSIONAL THREE-DIMENSIONAL THREE-DIMENSIONAL THREE-DIMENSIONAL
H HH HHOMOGENEOUS CLIPPING OMOGENEOUS CLIPPING OMOGENEOUS CLIPPING OMOGENEOUS CLIPPING OMOGENEOUS CLIPPING
O OO OOF TRIANGLE STRIPS F TRIANGLE STRIPS F TRIANGLE STRIPS F TRIANGLE STRIPS F TRIANGLE STRIPS
Pat rick-Gilles Maillot
Sun Microsyst ems, Inc
Mount ain View, Calif ornia
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Triangle st rips are among t he complex pr imit ives hand led by most 3D
gr aphics soft ware packages. One of t he most expensive oper at ions in
gr aphics is t o per for m clipping. This gem present s a solut ion t hat t akes
into account the specic organization of the list of points provided with a
t r iangle st r ip t o achieve up t o 50,000 + t r iangle clippings per second in
soft ware.
Some of t he pr inciples d iscussed here can be applied t o ot her, simpler
gr ap hic st r u ct u res, su ch as mu lt i-bou nd ed p olygons, t o imp rove t he
efciency of st and ard clipping met hod s. The same pr inciples also have
been applied t o quad r ilat er al mesh clipping.
One easy way of opt imizing a gr aphics pipeline oper at ion is t o keep t he
pr imit ive (and it s logic) all along t he gr aphics pipeline. Unfor t unat ely,
some oper at ions of t he pipeline can mod ify, or break, t he logical st r uc-
t ure of t he init ial pr imit ive. This t ypically is t he case of clipping, where a
t r iangle can be changed (clipped ) int o a nine-sid ed polygon aft er t he
clipping oper at ion against six planes.
This gem proposes a met hod t o clip t r iangle st r ips in 3D homogeneous
coord inat es, in t he gener al case of a non-nor malized clipping volume,
accept ing a t r iangle st r ip st ruct ure at t he input of t he clipping process,
and giving a t r iangle st r ip st ruct ure at t he out put .
Dat a St udy Dat a St udy Dat a St udy Dat a St udy Dat a St udy
While d escr ibed by a list of point s, t r iangle st r ips also have a logical
organizat ion t hat should be consid ered d ur ing t he clipping st ep. A t r ian-
220
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 220
Figur e 1. A t r iangle st r ip.
gle st r ip consist s of an ord ered list of n ver t ices [v
0
, v
1
, . . . , v
n 1
] t hat
d ene a sequence of n 2 t r iangles. The t r iangles in t he st r ip share
common ed ges. Thus, t he kt h t r iangle is for med of ver t ices k, k + 1,
k + 2. Figure 1 is a pict or ial example of a t r iangle st r ip.
Al gor i t hm St udy Al gor i t hm St udy Al gor i t hm St udy Al gor i t hm St udy Al gor i t hm St udy
We pr opose clipping t he pr imit ives using a met hod d er ived from t he
Su t her land -Hod gman algor it hm (1974). This means t hat t he clip p ing
calculat ions will be limit ed t o d et er mining int er sect ions wit h one clipping
plane at a t ime, separ at ing t he pr imit ive int o t wo regions: t he inside and
t he out side. These calculat ions will be repeat ed as many t imes as need ed
t o scan all t he enabled clipping planes.
This met hod involves a lot of comput at ions as well as memor y oper a-
t ions. However, since we oper at e in a t hree-d imensional space, and t he
ver t ices can have bot h nor mal and color infor mat ion, it seems t o be t he
most efcient . Each int er sect ion (comput ed only when need ed ) is based
on t he par amet r ic equat ion of t he ed ge from one ver t ex t o anot her :
P P
2
+ (1 )P
1
,
[0.0, 1.0].
221
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 221
The value of is used t o comput e t he int er sect ion ver t ex coord inat es
(P), and also can be used t o int er polat e linear ly t he color and nor mal
d at a gener ally associat ed wit h t he int er sect ion ver t ex.
The int er sect ion, in t he case of a line segment , has t o be evaluat ed only
when t he end point s of t hat line lie in opposit e regions. If a bit is assigned
t o each point , wit h a 1 meaning lies out side and a 0 meaning lies inside,
t hen t he int er sect ion will be comput ed only when (bit [P
i
] bit [P
i+1
]) is
set , meaning t hat one point lies out sid e and t he ot her one lies insid e t he
clipping region. If bot h bit s are set , t hat means t he ent ire line segment is
out sid e t he clipping region. The ent ire line segment is insid e t he clipping
region when bot h bit s ar e equ al t o 0. This ap p r oach, p r esent ed in
Maillot ,s t hesis (1986), offer s t he ad vant age of using fast oper at ions t o
check for t r ivial cases, and provid es a way t o keep int er med iat e result s
available for t he next p oint . In t he case of a t r iangle, we can t ake
ad vant age of t hree point s at a t ime.
A t r iangle st r ip is (obviously) composed of t r iangles. Each t r iangle can
be consid ered separ at ely for t he int er sect ion calculat ions. However, t he
implement at ion of t he clipping algor it hm should provid e a way t o avoid
mult iple equivalent calculat ions by t aking ad vant age of t he logical organi-
zat ion of t he ver t ices. As a t r iangle is composed of t hree point s, and t he
clipping process is organized in n st eps, n being t he number of enabled
clip planes, each point of t he t r iangle can be in or out of t he int er ior half
space d et er mined by t he cur rent clipping plane. This prod uces eight
d ifferent sit uat ions t o examine when comput ing t he clipped result of a
t r iangle wit h a given clipping plane. The d r awings of Fig. 2 show t he
d ifferent cases and t he result ing out put t hat has t o be gener at ed by t he
clipper t o maint ain t he logical organizat ion of t he t r iangle st r ip. The
t r iangle st r ip clipping algor it hm can gener at e some t r iangles wit h an area
of zero. By d oing t his, t he t r iangle st r ip st ruct ure can be maint ained even
when a t r iangle d egener at es int o a quad aft er clipping wit h a clip-plane.
There are special cases when clipping a t r iangle wit h clipping cod es
equal t o 011, or 110. The cod e 011 ind icat es t hat t he cur rent t r iangle has
it s t wo r st point s out sid e, and t he t hird point of t he t r iangle is insid e t he
clipping bound ar y. In t his par t icular case, a new t r iangle st r ip should be
issued . Even in t he case of a single t r iangle st r ip input , it is possible t o
have more t han one t r iangle st r ip aft er t he clipping oper at ion. Figure 3
explains such a sit uat ion.
There is a way, however, t o avoid t he mult iple t r iangle st r ips at t he
clipper out put , and t his helps t o simplify t he t r iangle st r ip rend er ing. The
222
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 222
Figure 2. Tr iangle sit uat ions.
223
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 223
Figure 3. Mult iple t r iangle st r ips cr eat ed by t he clipping oper at ion. A new t r iangle
should be issued when clipping a, b, c.
solut ion, proposed in t he case present ed in Fig. 3, is t o d uplicat e t he
point s Q and R so t hat t hree d egener at e t r iangles are issued t o keep t he
logic of t he or iginal t r iangle st r ip. The implement at ion proposed in t his
gem t akes ad vant age of t his met hod . It should be not ed t hat t his can be
applied only when t he rend er ing st age, fur t her down in t he gr aphics
pipeline, knows how t o d eal wit h d egener at e t r iangles.
Memor y Consi der at i ons Memor y Consi der at i ons Memor y Consi der at i ons Memor y Consi der at i ons Memor y Consi der at i ons
The st and ard clipping algor it hm proposed by Sut her land Hod gman im-
plies a lot of memor y oper at ions. A d et ailed int rod uct ion t o t he pr inciple
of t he algor it hm is present ed in Foley et al. (1990), showing t he d ifferent
st eps used t o clip a polygon in 2D or 3D. Alt hough it is ment ioned t hat
t he reent r ant char act er ist ic of t he or iginal algor it hm avoid s t he need for
int er med iat e st or age, t he cost implied in st ack oper at ions and recur sive
calls probably is not well-suit ed in t he case of a soft ware implement at ion
wit h large d at a st ruct ures.
i , j, k: clipping cod e 110, gener at es i, P, Q
j, k, m: clipping cod e 111, culled
k, m, a: clipping cod e 111, culled
m, a, b: clipping cod e 111, culled
a, b, c: clipping cod e 011, gener at es R, S, c
A new triangle should be issued when clipping a, b, c
...
...
224
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 224
While keeping t he same gener al int er sect ion pr inciples, t his gem pro-
poses a d ifferent approach, necessit at ing int er med iat e st or age, but limit -
ing t he number of calls t o t he inner por t ions of t he clipping algor it hm t o
t he number of act ive clipping planes. The algor it hm only propagat es
point er s t o point s, and not t he point s t hemselves, from one st age of t he
clipper t o t he next st age, t hus avoid ing expensive memor y copy oper a-
t ions.
Homogeneous Cl i ppi ng Agai nst a Non- Nor mal i zed Homogeneous Cl i ppi ng Agai nst a Non- Nor mal i zed Homogeneous Cl i ppi ng Agai nst a Non- Nor mal i zed Homogeneous Cl i ppi ng Agai nst a Non- Nor mal i zed Homogeneous Cl i ppi ng Agai nst a Non- Nor mal i zed
Cl i ppi ng Vol ume Cl i ppi ng Vol ume Cl i ppi ng Vol ume Cl i ppi ng Vol ume Cl i ppi ng Vol ume
Most of t he algor it hms p resent ed in t he lit er at u r e and p rop osing a
clipping in homogeneous coord inat es only d eal wit h a nor malized clip-
ping volume. In fact , it may be more int erest ing for a soft ware implemen-
t at ion of a gr aphics pipeline t o per for m all t he t r ansfor mat ions using a
single mat r ix, and t hen per for m t he clipping against a clip-volume in
homogeneous d evice coord inat es. The gr aphics pipeline is simplied in
t er ms of number st eps t o per for m, but t he clipping oper at ion need s more
at t ent ion.
Clipping against a nor malized clip volume means t hat t he clip volume is
[1, 1] [1, 1] [0, 1]. In t his gem, t he clipping oper at ion uses a
gener al, non-nor malized , clipping volume [xmin, xmax] [ymin, ymax]
[zmin, zmax]. In a homogeneous coord inat es syst em, t he basic clip-
ping equat ion is:
w c w,
wit h w > 0, and c t he value of t he x, y, or z coord inat e.
In t he case of a non-nor malized clipping volu me, t he basic clipping
equat ion becomes:
w*xmin x w*xmax,
w*ymin y w*ymax,
w*zmin z w*zmax,
wit h w > 0.
225
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 225
Det ailed explanat ions about clipping against a nonunifor m clipping vol-
ume, as well as a gener al d escr ipt ion of t he clipping problems, can be
found in Maillot s t hesis (1986).
Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on
The algor it hm proposed here suppor t s t he case where t he w component s
of t he ver t ices of t he t r iangle st r ip are posit ive. Clipping for negat ive ws
requires changing t he clipping equat ion (an exercise left t o t he read er ),
and suppor t ing lines wit h end ver t ices having bot h posit ive and negat ive
ws requires t wo passes by t he clipping algor it hm t o rend er bot h posit ive
and negat ive sect ions, one for each clipping equat ion. Figure 4 shows t he
result of clipping a single t r iangle wit h coord inat es (1, 0, 0, 1), (0, 1, 0, 1),
and (0, 0, 1, 1), compared t o a t r iangle wit h coord inat es (1, 0, 0, 1),
(0, 1, 0, 1), and (0, 0, 1, 1).
To implement t he clipping algor it hm for t r iangle st r ips, we d ene t he
following d at a st ruct ures:
H_point : record [
coord s: array[0..3] of real ;
];
Figure 4. Effect of posit ive and negat ive w component s: (a) all w component s are
posit ive; (b) w component s are posit ive and negat ive.
226
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 226
This st ruct ure hold s a single homogeneous point wit h coord inat es x, y,
z, and w.
H-List : record [
num_hpoint s: i nteger;
hpoint : array[] of H_point ;
];
This st ruct ure hold s a list of homogeneous point s wit h coord inat es x, y,
z, and w.
Clip_ct x: record [
cl_plane: array[0..5] of real ;
cl_t bd one: char;
point er s_bucket _0: array[] of array[] of H_point ;
int eger point er s_bucket _0_max;
point er s_bucket _1: array[] of array[] of H_point ;
point er s_bucket _1_max: i nteger;
hpoint s_bucket : array[] of H_point ;
hpoint s_bucket _max: i nteger;
hpoint s_bucket _ind ex: i nteger;
];
This st ruct ure hold s t he cur rent st at e of t he clipper. St or age is mad e for
point er s t o point s, and int er med iat e values of d ifferent clipping par ame-
t er s. cl_plane[] represent s t he six valu es of xmin, xmax, ymin, ymax,
zmin, zmax of t he clipping volume. cl_t bdone is composed of 6 bit s; bit
0 is set if clipping has t o be d one on xmin, bit 1 is assigned t o xmax,
and so on, up t o bit 5, assigned t o t he clip cond it ion on zmax.
The following is t he pseud o-cod e for t he clipping of a t r iangle st r ip. To
simplify t he present at ion of t he cod e, some por t ions appear in in
t he pseud o-cod e. These are relat ed t o memor y management , making sure
enough memor y has been allocat ed , or ensur ing t he copy of d at a. Please
227
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 227
refer t o t he act u al C Implement at ion proposed in Append ix 2 for a
complet e d escr ipt ion of t he t asks t o be per for med .
The pseud o-cod e also makes reference t o macros. These are used in
t he comput at ion of int er sect ions, or when moving point er s t o point s from
one st age of t he clipper t o t he ot her one. The C Implement at ion gives a
complet e d escr ipt ion of t hese macros.
3D t riangle st rip clipper. A t riangle st rip is made of
vert ices logically organized in t riangles (. . . ). The rst
t riangle is composed of t he vert ices 0, 1, and 2. The second
t riangle is represent ed by t he vert ices 1, 2, and 3, and so
on unt il t he last vert ex.
The t riangle st rip clipper clips t he t riangle st rip against
one t o six boundaries organized in a [xmin, xmax, ymin, ymax,
zmin, zmax] order. Each clip plane can be enabled/disabled by
cont rolling t he clip_ct x^ cl_t bdone [0..5] ags. Each ag
affect s t he respect ive clip plane of clip_ct x^ cl_plane[0..5].
As present ed in t he algorit hm, a t riangle st rip out put s only
one t riangle st rip. This is possible if degenerat e t riangles
are accept able.
Not es:
This basically is a Sut herland-Hodgman algorit hm, but a nonre-
ursiue version. Some short cut s have been employed in t he in-
t ersect ion calculat ions in homogeneous coordinat es.
h3d _st r ip_clip(clip_ct x, in, out )
{
At init , set t he previous st age point ers t o t he input point s values.
n_cur _s in^ num_hpoint s;
i f clip_ct x^ point er s_bucket _0_max < (n_cur _s + 64) then begi n
Ensure memor y for point er s_bucket _0
end;
i f clip_ct x^ point er s_bucket _1_max < (n_cur _s + 64) then begi n
Ensure memor y for point er s_bucket _1
end;
228
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 228
cur _st age clip_ct x^ point er s_bucket _0;
for i: int eger 0, i < n_cur _s, i i + 1 do
cur _st age[i] &(in^ hpoint s[i]);
endl oop;
C clip_ct x^ hpoint s_bucket ;
clip_ct x^ hpoint s_bucket _ind ex 0;
For each of t he clipping planes, clip (if necessary).
for i: i nteger 0, i < 6 and n_cur _s > 2, i i + 1 do
i f (clip_ct x^ cl_t bd one >> i) & 1 then begi n
c i >> l;
Swit ch memor y bet ween cur rent and previous
n_cur _s 0;
St art clipping of t he previous st age, for t he it h clip plane.
Out put point s go in t he current _st age memory.
Process t he rst point of t he t riangle st rip.
clip_cod e 0;
n 0;
COMPUTE_INTER_3D(Q, Q_plan, 1)
Now, process t he second point of t he t riangle st rip.
n 1;
COMPUT_INTER_3D(R, R_plan, 2)
(Q, R) represent s t he rst line segment of t he rst t riangle of
t he t riangle st rip. Need t o clip it as a line t o ensure t he rst t wo point s.
n clip_cod e >> 1;
sel ect n from
0: begi n Q and R insid e
POINT_COPY(Q)
POINT_COPY(R)
end;
1: begi n Q out side, R inside
POINT_INTER_3D(Q, Q_plan, R, R_plan)
POINT_COPY(R)
end;
229
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 229
2: begi n Q inside, R out side
POINT _COPY(Q)
POINT_INTER_3D(Q, Q plan, R, R plan)
end;
3: Q and R out side
endcase;
Process each subsequent point of t he t riangle st rip.
P, Q, R form t he (n 2)it h t riangle of t he st rip.
for n: i nteger 2, n < n_pre_s, n n + 1 do
clip_cod e clip_cod e >> 1;
P Q;
Q R;
P_plan Q_plan;
Q_plan R_plan;
COMPUT_INTER_3D(R, R_plan, 2)
i f n_cur _max < (n_cur _s + 3) then begi n
Ensure t hat enough memor y is available
end;
clip_code now has 3 bit s t hat represent t he posit ion of t he t riangle in
respect t o t he clip boundary. 8 different cases can occur.
sel ect clip_cod e from
0: begi n all inside
POINT_COPY(R)
end;
1: begi n P out side, Q and R inside
POINT_INTER_3D(R, R_plan, P, P_plan)
POINT_COPY(Q)
POINT_COPY(R)
end;
2: begi n P inside, Q out side and R inside
POINT_COPY(R)
POINT_INTER_3D(Q, Q_plan, R, R_plan)
POINT_COPY(R)
end;
3: begi n P and Q out side, R inside
POINT_INTER_3D(R, R_plan, P, P_plan)
Duplicat e t he point just comput ed
230
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 230
POINT_INTER_3D(Q, Q_plan, R, R_plan)
POINT_COPY(R)
end;
4: begi n P and Q inside, R out side
POINT_INTER_3D(R, R_plan, P, P_plan)
POINT_COPY(Q)
POINT_INTER_3D(Q, Q_plan, R, R_plan)
end;
5: begi n P out side, Q inside, R out side
POINT_INTER_3D(Q, Q_plan, R, R_plan)
end;
6: begi n P inside, Q and R out side
POINT_INTER_3D(R, R_plan, P, P_plan)
Duplicat e t he point just comput ed
end;
7: P, Q and R out side
endcase;
endl oop;
end;
endl oop;
The t riangle st rip has been clipped against all (enabled) clipping planes.
Copy t he result t o t he out put .
i f n_cur _s > 2 then
begi n
for i: i nteger 0, i < n_cur _s, i i + 1 do
out ^ hpoint s[i] (cur _st age[i]);
endl oop;
out ^ num_hlpoint s n_cur _s:
end;
el se
out ^ num_hpoint s 0;
return;
};
Concl usi on Concl usi on Concl usi on Concl usi on Concl usi on
This gem has present ed a d ifferent approach t o 3D homogeneous clipping
of complex pr imit ives. Most of t he par t icular it ies present ed herere-
231
IV.8 THREEDIMENSIONAL HOMOGENEOUS CLIPPING OF TRIANGLE STRIPS
GRAPHICS GEMS II Edit ed by JAMES ARVO 231
organizat ion of t he Sut her land -Hod gman algor it hm, int er sect ion compu-
t at ions, nonunifor m clipping volume, et c.can be used in any 3D poly-
gon clipping. The per for mance of t he proposed algor it hm for all clip
planes enabled is bet t er t han 23,000 t r iangles (t r ivial accept ance or t r ivial
reject ) per second on a Sun-Sparc St at ion 330, wit h t he C Implement at ion
given in Append ix 2, and for t r iangle st r ips of 10 or more t r iangles. The
efciency of t he clipping algor it hm var ies wit h t he number of t r iangles
per t r iangle st r ip. The wor st case of t he algor it hmone t r iangle per
t r iangle st r ipst ill clips at an honor able speed of 10,000 + t r iangles per
second .
The specic case of single t r iangles should be opt imized separ at ely. An
implement at ion limit ed t o clipping against unifor m volumes also gives
bet t er per for mances.
The met hod p resent ed her e also has been ap p lied in t he case of
quad r ilat er al meshes. The clipping oper at ion is per for med one quad -mesh
row at a t ime, and pot ent ially can gener at e sever al quad -mesh rows at t he
out put of t he clipping algor it hm. Because quad s are composed of four
point s, t he algor it hm t akes t wo point s at a t ime, and t he core of t he
clipping process necessit at es 16 d ifferent cases.
232
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 232
IV.9 IV.9 IV.9 IV.9 IV.9
I II IINTERPHONG SHADING NTERPHONG SHADING NTERPHONG SHADING NTERPHONG SHADING NTERPHONG SHADING
Nadia Magnenat Thalmann Daniel Thalmann
Universit y of Geneva Swiss Federal Inst it ut e of Technology
Geneva, Swit zerland, Lausanne, Swit zerland
and
Hong Tong Minh
Universit y of Wat erloo
Wat erloo, Ont ario, Canada
Over vi ew Over vi ew Over vi ew Over vi ew Over vi ew
Int erPhong shading is a mod ied ver sion of t he popular Phong shad ing.
When applied t o a facet -based object , it is able t o give a rough or smoot h
appear ance d epend ing on t he var iat ion bet ween t he nor mals of t he facet s.
For example, we may apply it t o a sphere, a cube, or a cylind er. This
var ying shad ing also may be consid ered as a cont inuous mod el bet ween
facet ed shad ing and Phong shad ing. This proper t y is ver y impor t ant for
shad ing object s obt ained by shape int er polat ion bet ween t wo d ifferent
object s, such as a sphere and a cube. The Int er Phong shad ing also has
been used for rend er ing synt het ic act or s. In par t icular, it has been used
for rend er ing Mar ilyn Monroe and Humphrey Bogar t in t he lm, Rendez-
vous a ` Mont ral.
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Since 1970, var ious illuminat ion and shad ing mod els have been pro-
p osed , as d escr ibed by sever al au t h or s (Roger s, 1985; Lor if, 1986;
Magnenat Thalmann and Thalmann, 1987a). Hall (1986) p rop oses a
classicat ion int o t hree groups:
1. Increment al shad ing t echniques and empir ical illuminat ion mod els.
2. Ray t r acing and t r anslat ional illuminat ion mod els.
3. Analyt ical mod els and r ad iosit y t echniques.
233
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 233
In t his Gem, we are concer ned wit h t he r st kind of shad ing mod els.
These mod els t r ad it ionally are implement ed wit h scanline rend er ing sys-
t ems and will be reviewed in t he next sect ion. It is evid ent t hat t he bet t er
t he result s t hat an algor it hm provid es, t he more expensive it is in t er ms
of CPU t ime. However, t he choice of shad ing t echniques also is d epend ent
on t he shape of object s. For example, Phong shad ing is well ad apt ed t o
spheres, and facet ed shad ing is suit able for cubes. Now consid er t he
t r ansfor mat ion of a sphere int o a cube using an in-bet ween algor it hm.
What kind of shad ing mod el should be used t o shad e any in-bet ween
object ? This gem t r ies t o answer t his quest ion by int rod ucing a new kind
of shad ing d epend ent on t he shape of object s. The new shad ing mod el,
called t he Int erPhong model, also may be consid ered as a cont inu ou s
mod el bet ween facet ed shad ing and Phong shad ing. One applicat ion of
t his algor it hm is t o shad e facet ed -based object s obt ained from a gener al
shape int er polat ion (Hong et al., 1988). As object s change, t heir shad ing
is changed aut omat ically.
Revi ew of Incr ement al and Empi r i cal Revi ew of Incr ement al and Empi r i cal Revi ew of Incr ement al and Empi r i cal Revi ew of Incr ement al and Empi r i cal Revi ew of Incr ement al and Empi r i cal
Shadi ng Techni ques Shadi ng Techni ques Shadi ng Techni ques Shadi ng Techni ques Shadi ng Techni ques
The r st illuminat ion mod el t hat t ook int o account t he t hree component s
of ambient , d iffuse, and specular light was d evised by Bui-Tuong Phong
(1975). Int ensit y I in t his mod el is given by:
I = I
a
+ I
d
+ I
s
, (1)
where I
a
is reect ion d ue t o ambient light , I
d
is d iffuse reect ion, and I
s
is specular reect ion.
Diffuse reect ion is d ened as in Lamber t s law, which means for m
s
light sources:
I
d
= k
d
C
s

I
lj
j
m
s

( N L
j
), (2)
where k
d
is t he d iffuse reect ion coefcient , N is t he unit sur face nor mal,
I
lj
is t he int ensit y of t he jt h sour ce, C
s
is t he sur face color, L
j
is t he
234
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 234
vect or in t he d irect ion of t he jt h light source, and m
s
is t he number of
light sources.
Specular reect ion is d ened as:
I
s
= k
s
C
r

I
lj
j
m
s

( N H
j
)
n
, (3)
where k
s
is t he specular reect ion coefcient and C
r
is t he reect ive
color sur face. The exponent n d epend s on t he sur face and d et er mines
how glossy t his sur face is; H
j
is t he vect or in t he d irect ion halfway
bet ween t he obser ver and t he jt h light source.
Surface shading may be d ened as t he d ist r ibut ion of light over an
illuminat ed sur face. For each t ype of object mod el (set of polygons,
algebr aic sur face, pat ches), shad ing can be calculat ed using t he preced -
ing reect ion mod el. However, reect ion mod els d o not d irect ly provid e
ways of calculat ing t he complet e shad ing of an object , but only t he
int ensit y of light as specic point s. The shad ing t echniques used d epend
on t he t ype of object . For polygon meshes, t hree basic ways of shad ing
object s have been d eveloped facet ed shad ing, Gour aud shad ing, and
Phong shad ing.
Facet ed shading was r st int rod uced by Bouknight (1970). It involves
calculat ing a single int ensit y for each polygon. This implies t he following
assumpt ions:
1. The light source is at innit y.
2. The obser ver is at innit y.
3. The polygons are not an approximat ion of a cur ved sur face.
The r st t wo assumpt ions are required so t hat t he d ot prod uct s N L
j
and N H
j
are const ant in t he calculat ions of int ensit y. The t hird as-
sumpt ion is mad e because each polygonal facet of an object will have a
slight ly d ifferent int ensit y from it s neighbor s. This prod uces good result s
for a cube, but ver y poor ones for a sphere.
235
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 235
Gour aud (1971) int rod uced an int ensit y int er polat ion shad ing met hod
t hat eliminat es t he d iscont inuit ies of const ant shad ing. The pr inciple of
Gouraud shading is as follows:
1. For each ver t ex common t o sever al polygons, t he nor mal t o each
polygon is comput ed as a vect or per pend icular t o t he plane of t hat
polygon.
2. For each ver t ex, a unique nor mal is calculat ed by aver aging t he
sur face nor mals obt ained previously.
3. Ver t ex int ensit ies are calculat ed by using t he ver t ex nor mals and a
light mod el.
4. As each polygon has a d ifferent shad ing at each ver t ex, t he shad ing
at any point insid e t he polygon is found by linear int er polat ion of
ver t ex int ensit ies along each ed ge and t hen bet ween ed ges along each
scanline.
Bui-Tuong Phong (1972) has proposed a nor mal-vect or int er polat ion
shad ing met hod . This means t hat inst ead of int er polat ing int ensit ies as in
Gour aud shad ing, Phong int er polat es t he sur face nor mal vect or. Wit h t his
approach, t he shad ing of a point is comput ed from t he or ient at ion of t he
approximat ed nor mal. Wit h Phong shad ing, a bet t er approximat ion of t he
cur vat ure of t he sur face is obt ained , and highlight s d ue t o t he simulat ion
of specular reect ion are rend ered much bet t er. However, t he met hod
requ ir es more comp u t at ion, since t hree nor mal comp onent s mu st be
comput ed , r at her t han one shad ing value, and t he vect or at each point
must be nor malized before evaluat ing t he shad ing funct ion. The linear
int er polat ion scheme used in t he Phong algor it hm t o approximat e t he
or ient at ion of t he nor mal d oes not guar ant ee a cont inuous r st d er ivat ive
of t he shad ing funct ion across an ed ge of a polygonal mod el. In par t icu-
lar, where t here is an abrupt change in t he or ient at ion of t wo ad jacent
polygons along a common ed ge, t he Mach band effect is possible. This
means t hat a subject ive br ight ness may be visible along t his ed ge. The
effect usually is much less visible in t he Phong mod el t han in t he Gour aud
mod el. However, Duff (1979) shows t hat Phong shad ing can prod uce
236
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 236
wor se Mach band s t han Gour aud shad ing, not ably for spheres and cylin-
d er s. Moreover, bot h t echniqu es rend er concave polygons incor rect ly.
Duff has d iscovered anot her great problem in t he comput er animat ion of
shad ed object s wit h t he Gour aud and Phong algor it hms. If an object and
it s light source are rot at ed t oget her in t he image plane, t he shad ing of t he
object can change cont r ar y t o expect at ions. This is d ue t o t he fact t hat
t he int er polat ion of int ensit ies (or nor mals) is car r ied out using values on
a scanline, and when object s and light s are rot at ed , t he scanlines d o not
cut t he ed ges at t he same point s. Duff proposes alleviat ing t his problem
by int er polat ing int ensit ies (or nor mals) in a rot at ion-ind epend ent man-
ner ; he avoid s t he use of values by t he use of an appropr iat e int er polat or
d epend ing only on t he ver t ices of t he polygon.
Int er Phong Shadi ng Int er Phong Shadi ng Int er Phong Shadi ng Int er Phong Shadi ng Int er Phong Shadi ng
Facet ed shad ing is t he quickest and easiest of t he shad ing t echniques. It
is more appropr iat e for rend er ing cubes t han spheres. However, it is not
realist ic for per spect ive views and / or point light sources. One way of
improving realism in t his case is t o recalculat e t he int ensit y at each pixel,
because only t he nor mal is const ant at any point of a given facet , not t he
viewer d irect ion and light d irect ion. This process is almost as expensive
as t he Phong shad ing, alt hough no int er polat ion across facet s is per-
for med . We call t his t yp e of shad ing modied facet ed shading. This
Figur e 1. Nor mal int er polat ion.
237
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 237
shad ing is realist ic for a cube, while Phong shad ing is a good way (in a
facet -based environment ) of rend er ing a sphere. Now consid er t he t r ans-
for mat ion of a sphere t o a cube using an in-bet ween algor it hm. What kind
of shad ing mod el should be used t o shad e any in-bet ween object ? Though
we may d ecid e t hat an object t hat is 50% sphere and 50% cube may be
rend ered using Phong shad ing, t his is not t rue for a 99.9% cube and 0.1%
sphere. We have t o int rod u ce a var ying shad ing mod el bet ween t he
facet ed (or mod ied facet ed ) mod el and t he Phong mod el. We call t his
t he Int er Phong mod el. To explain t his mod el, consid er, as shown in Fig.
1, a point P belonging t o a facet wit h nor mal N. The int er polat ed nor mal
N
p
accord ing t o t he Phong met hod is:
N
p
= N
a
+ t(N
b
N
a
), (4)
N
a
= N
l
+ u(N
2
N
l
),
N
b
= N
4
+ v(N
3
N
4
),
wit h {t, u, v} [0, 1].
We now replace N
p
by a new value calculat ed as:
N
pnew
= N
p
+ f(N N
p
), (5)
wit h
f = (|N

N
p
| +
1
(2

|N N
p
|))

2
2
. (6)
Sever al cases may be consid ered t o explain t he role of
1
and
2
:
1.
1
= 0. In t his case, we have f =

N N
p

2
2
. The algor it hm will
d ecid e t o give a rough or smoot h appear ance d epend ing on t he var iat ion
238
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 238
bet ween t he nor mals of t he facet s. (The polygon facet ed ges are left shar p
or smoot hed .)
2
is a real p osit ive nu mber ; when t he t ension
2
is
d ecreased , t he char act er ist ics of t he Phong mod el are emphasized . Ot her-
wise, when t he t ension
2
is great er t han 1, t he char act er ist ics of t he
facet ed mod el are emphasized .
2
is called t he shading t ension.
2.
1
= 1. In t his case, we have f =
2
. The user may select a value
bet ween 0 and 1 for t he t ension par amet er
2
t o obt ain an int er polat ed
shad ing bet ween facet ed shad ing and Phong shad ing. For example, if

2
= 0.75, we have 75% of facet ed shad ing and 25% of Phong shad ing.
For
2
= 1, we have t he facet ed shad ing, and for
2
= 0, st and ard Phong
shad ing.
3. 0 <
1
< 1. This is a combinat ion of t he t wo previous cases. For
example, if
2
= 0.25, we obt ain a shad ing wit h 25% of effect s from t he
int er polat ion (bet ween Phong shad ing and facet ed shad ing) and 75% from
t he ed ge emphasizing process. (See r st case.)
As
1
is a measure of t he d epend ence on t he var iat ion bet ween t he
nor mals of t he facet s; we call it t he nonlocalit y t ension.
Anal ysi s of t he New For mul a Anal ysi s of t he New For mul a Anal ysi s of t he New For mul a Anal ysi s of t he New For mul a Anal ysi s of t he New For mul a
The use of a new N
p new
calculat ed by Eq. (5) solves t wo problems:
1. The d epend ence of t he t ext ure of t he d isplay of a gr aphical object on
t he scanlines.
2. The und esir able smoot hing of cer t ain regions.
For example, consid er t he cube of Fig. 2; we obser ve t hat N
p1
d epend s
on N
l
, N
2
, and N
4
, and N
p2
d epend s on N
2
, N
3
, and N
4
. This implies a
kind of t ext ure t hat var ies d epend ing on t he scanned areas. Moreover, at
t he ver t ex S, t he cube will be rounded and t he common ed ges will be
d ifcult t o d ist inguish. The problems are solved by moving t he nor mal N
p
t o t he facet nor mal N, which is t he only t rue informat ion.
239
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 239
Figure 2. Ver t ex d epend ence.
To simplify t he explanat ions, consid er t he case wit h
1
= 0 and
2
= 1
We have:

N
p new
N
p
N N
p
N N
p
2
. (7)
If t he nor mal var iat ions bet ween t he ad jacent facet s are small (smoot h
sur faces), as shown in Fig. 3, t he nor mals N
p
and / or N
p
should not be
ver y d ifferent from N and / or N.
Figure 3. Nor mals for ad jacent facet s: a) in 3D; b) in 2D.
240
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 240
This implies t hat

N
p new
N
p
N N
p
2
2
0
(8)
and

N
p new
N
p
N N
p
2
2
0,
as N N
p
(and N N
p
), N
pnew
N
p
(and N
p

new
N
p
); t he new
shad ing mod el preser ves t he Phong char act er ist ics.
For a cube, |N N
p
| is not negligible and

N
p new

N
p
+ N N
p
N N
p
( )
2
is ver y near t he or iginal nor mal N. This means t hat t he var ious ad jacent
facet s will have d ifferent new nor mals, which emphasize t he ed ges.
If we assume t hat all nor mals are nor malized , t he const ant 2 in Eq.
(6) comes from |N N
p
| < |N| + |N
p
| < 1 + 1 = 2. This is t he maximum
cor rect ion allowed and cor respond s t o N N
p
.
From a per for mance point of view, as all nor ms in R
n
are t opologically
equivalent , we may use |N| = |N
x
| + |N
y
| + |N
z
| , which implies
3 absolut e values and 2 ad d it ions for t he nor ms,
3 subt r act ions for N N
p
,
1 mult iplicat ion and 1 d ivision for |N N
p
|(N N
p
)/ 2
3 ad d it ions for N
pnew
= N
p
+ |N N
p
|(N N
p
)/ 2
This is an ext r a cost of 10 ar it hmet ic oper at ions and t hree absolut e
values.
241
IV.9 INTERPHONG SHADING
GRAPHICS GEMS II Edit ed by JAMES ARVO 241
Appl i cat i ons of Int er Phong Shadi ng Appl i cat i ons of Int er Phong Shadi ng Appl i cat i ons of Int er Phong Shadi ng Appl i cat i ons of Int er Phong Shadi ng Appl i cat i ons of Int er Phong Shadi ng
One possible applicat ion of Int er Phong shad ing is t he rend er ing of human
faces. As it was not ed in t he lm, Rendez-vous ` a Mont ral (Magnenat
Thalmann and Thalmann, 1987b), Phong shad ing is convenient for t he
face of a synt het ic act ress, but t he result is t oo smoot h for a synt het ic
act or. Fig. 4 (see color inser t ) shows var ious shad ings for t he face of a
synt het ic act or.
The Int er Phong shad ing mod el may be consid ered as a cont inu ou s
mod el bet ween facet ed shad ing and Phong shad ing. This proper t y is ver y
mu ch imp or t ant for shad ing object s obt ained by shap e int er p olat ion
bet ween t wo d ifferent object s, such as a sphere and a cube.
Figure 5 (see back cover ) shows an example of t r ansfor mat ion of a
sphere int o a d od ecahed ron wit h a cont inuous shad ing int er polat ion from
Phong shad ing t o facet ed shad ing (Int er Phong shad ing).
(a)
(c)
(b)
(d)
Figure 4. A Synthetic actor: a) faceted shad-
ing; b) Phong shading; c) Interphong shad-
ing with
1
= 0 and
2
= 1; d) InterPhong
chading with
1
= 0 and
2
= 5.
Figure 5. A Transformations of a sphere into a dodeca-
hedron (with shading interpolation).
V
RAY TRACING
245
RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 245
V VV VV
R RR RRAY TRACING AY TRACING AY TRACING AY TRACING AY TRACING
Ray t racing is one of t he most popular t echniques for high-d elit y image
synt hesis because of it s wid e var iet y of opt ical effect s and it s concept ual
simplicit y. Fir st int rod uced t o t he realm of comput er gr aphics by Appel
[68], it was lat er ext end ed int o it s now-familiar recur sive for m by Whit t ed ,
1980. Since t hen, r ay t r acing has been wid ely used t o gener at e images of
st r iking realism, and cont inues t o be a t opic of vigorous research. Much
of t he appeal of r ay t r acing st ems from it s fait hful simulat ion of basic
geomet r ical opt ics. By t r acing ind ivid ual r ays of light int o a hypot het ical
3D scene and obeying laws for refr act ion and reect ion, t he over all
char act er ist ics of t r ansparent and reect ive sur faces can be simulat ed .
These char act er ist ics remain t he unmist akable hallmar ks of r ay-t r aced
imager y.
In t he cont ext of mor e r ecent global illu minat ion algor it hms, r ay
t r acing is t aking on a new life as a power ful t ool for solving subproblems.
(Examples of t his can be found in t he following Par t on t he r ad iosit y
met hod ). It is clear t hat r ay t r acing will have an impor t ant role t o play for
a long t ime, whet her used d irect ly for image synt hesis or as t he found a-
t ion for ot her algor it hms. It s gener alit y makes it an id eal research vehicle,
lend ing it self t o a panoply of essent ial gr aphics oper at ions and opt ical
effect s.
The gems of t his Par t ad d ress met hod s for comput ing r ay int er sect ions
wit h polyhed r a, t r iangles, and t or i, as well as large collect ions of such
246
RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 246
object s by use of object hier archies and spat ial subd ivision. The last t hree
gems d iscu ss t echniqu es for u se in shad ow calcu lat ions and in t he
simulat ion of t r anslucent object s, t wo impor t ant effect s in r ay t r acings
wid e reper t oire.
247
V.1 FAST RAYCONVEX POLYHEDRON INTERSECTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 247
V. 1 V. 1 V. 1 V. 1 V. 1
F FF FFAST RAYCONVEX AST RAYCONVEX AST RAYCONVEX AST RAYCONVEX AST RAYCONVEX
P PP PPOLYHEDRON INTERSECTION OLYHEDRON INTERSECTION OLYHEDRON INTERSECTION OLYHEDRON INTERSECTION OLYHEDRON INTERSECTION
Eric Haines
3D / Eye, Inc.
It haca, New York
The st and ard solut ion t o r ay-polyhed ron int er sect ion is t o t est t he r ay
against each polygon and nd t he closest int er sect ion, if any. If t he
polyhed ron is convex, t he r ay-polyhed ron t est can be acceler at ed by
consid er ing t he polyhedron t o be t he space insid e a set of planes. This
d enit ion also d r ast ically red u ces t he memor y requ ir ement s for su ch
polyhed r a, as none of t he ver t ices and t heir connect ivit ies need t o be
st ored ; only t he plane equat ions for t he faces are need ed . Finally, t he
r ay-polyhed ron t est out lined here avoid s t he problems t hat can occur
when t he shared ed ge of t wo polygons is int er sect ed by a r ay, since t here
no longer are any ed ges. There is no chance of a r ay slipping t hrough
t he cr acks by having it s int er sect ion point on an ed ge not consid ered
being insid e eit her polygon.
The algor it hm is based on t he id eas of Rot h (1981) and Kay and Kajiya
(1986). The basic id ea is t hat each plane of t he polyhed ron d enes a
half-space: All point s t o one sid e of t his space are consid ered insid e t he
plane (also consid er ing point s on t he plane as insid e). The logical int er-
sect ion of t he half-spaces of all t he convex polyhed rons planes is t he
volume d ened by t he polyhed ron. Int rod ucing a r ay int o t his d enit ion
changes t he problem from t hree d imensions t o one. The int er sect ion of
each plane by t he r ay creat es a line segment (unbound ed at one end )
mad e of a set of point s insid e t he planes half-space. By t aking t he logical
int er sect ion of all r ay-plane line segment s, we nd t he line segment (if
any) in which t he r ay passes t hrough t he polyhed ron.
248
V.1 FAST RAYCONVEX POLYHEDRON INTERSECTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 248
The r ay is d ened by:
R
or igin
= R
o
= [x
o
y
o
z
o
],
R
di recti on
= R
d
[x
d
y
d
z
d
],
where x
2
d
+ y
2
d
+ z
2
d
= 1 (i.e., nor malized ).
The set of point s on t he r ay is represent ed by t he funct ion:
R(t ) = R
0
+ R*
d
t ,
where t > 0.
In ad d it ion, in r ay t r acing, it is u sefu l t o keep t r ack of t
max
, t he
maximum valid d ist ance along t he r ay. In shad ow t est ing, t
max
is set t o
t he d ist ance of t he light from t he r ays or igin. For r ays in which t he
closest object hit is d esir ed , t
max
is init ialized t o innit y (i.e., some
ar bit r ar ily large d ist ance), t hen upd at ed t o t he d ist ance of t he object
cur rent ly t he closest as t est ing progresses. An object int er sect ed beyond
t
max
d oes not need t o be t est ed fur t her for example, for shad ow t est ing,
such an object is beyond t he light .
We init ialize t he d ist ances t
near
t o negat ive innit y and t
far
t o t
max
These will be u sed t o keep t r ack of t he logical int er sect ion of t he
half-spaces wit h t he r ay. If t
near
ever becomes great er t han t
far
, t he r ay
misses t he polyhed ron and t est ing is d one.
Each plane is d ened in t er ms of [a, b, c, d], which d enes t he plane
a*x + b*y + c*z + d = 0.
P
n
is t he planes nor mal,[a, b, c].
The d ist ance from t he r ays or igin t o t he int er sect ion wit h t he plane P
is simply:
t =
n
/
d
,
where:

n
= P
n
R
o
+ d,

d
= P
n
R
d
.
249
V.1 FAST RAYCONVEX POLYHEDRON INTERSECTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 249
If
d
is 0, t hen t he r ay is par allel t o t he plane and no int er sect ion t akes
place. In such a case, we check if t he r ay or igin is insid e t he planes
half-space. If
n
is posit ive, t hen t he r ay or igin is out sid e t he planes
half-space. In t his case, t he r ay must miss t he polyhed ron, so t est ing is
d one.
Ot her wise, t he plane is cat egor ized as front -facing or back-facing. If
d
is posit ive, t he plane faces away from t he r ay, so t his plane is a back-face
of t he polyhed ron; else, t he plane is a front -face. If a back-face, t he plane
can affect t
far
. If t he comput ed t is less t han 0, t hen t he polyhed ron is
Figur e 1.
250
V.1 FAST RAYCONVEX POLYHEDRON INTERSECTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 250
behind t he r ay and so is missed . If t is less t han t
far
, t
far
is upd at ed t o t.
Similar ly, if t he plane is a front -face, t
near
is set t o t if t is great er t han
t
near
. If t
near
ever is great er t han t
far
, t he r ay must miss t he polyhed ron.
Else, t he r ay hit s, wit h t
near
being t he ent r y d ist ance (possibly negat ive)
and t
far
being t he d ist ance where t he r ay exit s t he convex polyhed ron. If
t
near
is negat ive, t he r ay or iginat es insid e t he polyhed ron; in t his case,
check if t
far
is less t han t
max
; if it is, t hen t
far
is t he r st valid int er sect ion.
An example of t his process is shown in Fig. 1. A t wo-d imensional view
of a r ay and a set of ve planes for ming a polyhed ron is shown. Below
t his is t he set of segment s for med by t he r ay and t he ve faces. The r ay
int er sect s t he plane for med by face 1 and so d enes a set of point s along
t he r ay insid e t he half-space t o t he r ight of t his int er sect ion. The r ay
int er sect s t he p lane of face 2 (shown as a d ashed line) at a closer
d ist ance, even t hough t he face it self is missed . Face 3 is a back-face and
creat es a half-space open t o t he left . Face 4 also is missed , but it s plane
st ill d enes a half-space. Finally, plane 5 for ms a fr ont -face half-space.
The segment in which t he line d ened by t he r ay passes t hrough t he
polyhed ron is t he logical int er sect ion of t he ve face segment s; t hat is,
where all of t hese segment s over lap. Compar ing t his segment wit h t he
r ays own segment gives which (if eit her ) of t he int er sect ion point s is t he
closest along t he r ay. If t here is no logical int er sect ion, t he r ay misses.
251
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 251
V. 2 V. 2 V. 2 V. 2 V. 2
I II IINTERSECTING A RAY WITH NTERSECTING A RAY WITH NTERSECTING A RAY WITH NTERSECTING A RAY WITH NTERSECTING A RAY WITH
AN ELLIPTICAL TORUS AN ELLIPTICAL TORUS AN ELLIPTICAL TORUS AN ELLIPTICAL TORUS AN ELLIPTICAL TORUS
Joseph M. Cychosz
Purdue Universit y
W. Laf ayet t e, Indiana
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
This gem present s t he mat hemat ics and comput at ions required for d et er-
mining t he point s of int er sect ion bet ween a r ay and a t orus. Also pre-
sent ed is an efcient bound ing met hod for t or i.
The Equat i on of an El l i pt i cal Tor us The Equat i on of an El l i pt i cal Tor us The Equat i on of an El l i pt i cal Tor us The Equat i on of an El l i pt i cal Tor us The Equat i on of an El l i pt i cal Tor us
An ellipt ical t orus can be gener at ed by sweeping an ellipse about a given
axis. Figure 1 illust r at es t he result ing cross sect ion of an ellipt ical t or us
t hat has been swept about t he y axis. The cross sect ion consist s of t wo
ellipses of r ad ii a and b, cent ered at x = tr, y = 0. By sweeping t he
ellipses circular ly about t he y axis, a t orus of r ad ius r and cent ered at
t he or igin is for med .
In an approach analogous t o t hat t aken by Glassner et al. (1989), t he
equat ion of t he t wo ellipt ical cross sect ions is given by

x r ( )
2
a
2
+
y
2
b
2
1
|
.

`
,

x + r ( )
2
a
2
+
y
2
b
2
1
|
.

`
,

0,
(1)
which can be expressed as
(b
2
(x r)
2
+ a
2
y
2
a
2
b
2
)(b
2
(x + r)
2
+ a
2
y
2
a
2
b
2
) = 0. (2)
252
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 252
Figure 1. Cross sect ion of an ellipt ical t or us.
Equat ion (2) can be rear r anged t o yield t he following equat ion,

x + r ( )
2
+
a
2
b
2
y
2
+ r
2
a
2
( )
|
.
`
,
2
4r
2
x
2
0.
(3)
By subst it ut ing p for a
2
/ b
2
, A
0
for 4r
2
, and B
0
for (r
2
a
2
), Eq. (3) is
rewr it t en as
(x
2
+ py
2
+ B
0
)
2
A
0
x
2
= 0.
(4)
By set t ing y = 0 in t he preced ing equat ion, we nd t hat x
2
= r
2
. The
t or us now can be for med by subst it ut ing t he sweeping funct ion, r
2
=
x
2
+ z
2
, for x
2
in t he cross-sect ional funct ion present ed in Eq. (4). The
equat ion for t he ellipt ical t or us t hus becomes
(x
2
+ z
2
+ py
2
+ B
0
)
2
A
0
(x
2
+ z
2
) = 0, (5)
where p, A
0
, and B
0
are const ant s d ened previously t hat cont rol t he
shape of t he t orus.
Int er sect i on of a Ray wi t h a Tor us Int er sect i on of a Ray wi t h a Tor us Int er sect i on of a Ray wi t h a Tor us Int er sect i on of a Ray wi t h a Tor us Int er sect i on of a Ray wi t h a Tor us
The int er sect ion of a r ay wit h a t orus can be found by subst it ut ing t he r ay
equat ions shown in Eqs. (6a)(6c) int o Eq. (5), t he t orus equat ion, t he
253
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 253
int er sect ion of a r ay wit h a t orus is d ened in Eq. (7) as follows:
x = x
0
+
x
t , (6a)
y = y
0
+
y
t , (6b)
z = z
0
+
z
t , (6c)
(t
2
(
2
x
+ p
2
y
+
2
z
) + 2t (x
0

x
+ py
0

y
+ z
0

z
)
+ (x
2
0
+ py
2
0
+ z
2
0
) + B
0
)
2
A
0
(t
2
(
2
x
+
2
z
) + 2t(x
0

x
+ z
0

z
) + (x
2
0
+ z
2
0
)) = 0. (7)
The real root s of t he quar t ic equat ion present ed in Eq. (7) d ene t he
d ist ances along t he r ay where t he r ay int er sect s t he t orus. Eq. (7) can be
rear r anged int o t he following for m:
c
4
t
4
+ c
3
t
3
+ c
2
t
2
+ c
1
t + c
0
= 0,
where
c
4
= (
2
x
+ p
2
y
+ a
2
z
)
2
,
c
3
= 4(x
0

x
+ py
0

y
+ z
0

z
)(
2
x
+ p
2
y
+
2
z
),
c
2
= 4(x
0

x
+ py
0

y
+ z
0

z
)
2
+ 2(x
2
0
+ py
2
0
+ z
2
0
+ B
0
)(
2
x
+ p
2
y
+
2
z
) A
0
(
2
x
+
2
z
),
c
1
= 4(x
0

x
+ py
0

y
+ z
0

z
)(x
2
0
+ py
2
0
+ z
2
0
+ B
0
)
2A
0
(x
0

x
+ z
0

z
),
c
0
= (x
2
0
+ py
2
0
+ z
2
0
+ B
0
)
2
A
0
(x
2
0
+ z
2
0
).
254
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 254
Using t he subst it ut ions d eveloped by Cashwell and Everet t (1969), t he
quar t ic in nor malized for m is as follows:
c
4
= 1,
c
3
= 2m,
c
2
= m
2
+2u qf,
c
1
= 2mu ql,
c
0
= u
2
qt ,
where
f = 1
2
y
, g = f + p
2
y
, l = 2(x
0

x
+ z
0

z
), t = x
0
2
+ z
0
2
,

q
A
0
g
2
,

m
l + 2py
0

y
( )
g
,

u
t + py
0
2
+ B
0
( )
g
.
To int er sect a r ay wit h a t orus t hat has been ar bit r ar ily posit ioned and
or ient ed , t he r ay base and d irect ion cosines must be t r ansfor med int o t he
coord inat e syst em of a t or us posit ioned at t he or igin and or ient ed in t he
xz plane. This can be d one by use of a coord inat e t r ansfor mat ion mat r ix
est ablished from t he or t honor mal basis creat ed from t he axis of rot at ion
and t he local x axis. The t r ansfor mat ion mat r ix is d ened as follows:

T =
U 0
N 0
U N 0
C
x
C
y
C
z
1

]
]
]
]
]
]
,
where U d enes t he local x axis of t he t orus, N d enes t he local y axis
(i.e., t he axis of rot at ion) of t he t orus, and C is locat ion of t he cent er of
t he t orus.
Ef f i ci ent Boundi ng of Tor i Ef f i ci ent Boundi ng of Tor i Ef f i ci ent Boundi ng of Tor i Ef f i ci ent Boundi ng of Tor i Ef f i ci ent Boundi ng of Tor i
A common bound ing met hod is t o enclose an object wit hin a sphere.
When t he r ay d oes not int er sect t he bound ing sphere, t here is no need t o
calculat e t he int er sect ion point s of t he r ay wit h t he enclosed object , t hus
255
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 255
Figure 2. Efcient t oroid al bound ing.
eliminat ing u nnecessar y compu t at ion. A t or u s can be enclosed easily
wit hin a sphere posit ioned at t he cent er of t he t orus and wit h a r ad ius as
follows:
r
sphere
= r + max(a, b)
However, t his bound ing approach result s in a signicant ly large void
volume as d epict ed in Fig. 2. To red uce t he result ing void volume, t he
t or us is sand wiched bet ween t wo planes locat ed tb off of t he xz plane.
The ver t ical d ist ances of t he int er sect ion point s of t he sphere t hen are
t est ed t o d et er mine if t he r ay passes eit her complet ely above or below t he
t or us. Since t he t orus lies in t he xz plane, only t he y component of t he
int er sect ion locat ions on t he sp here ar e of int er est . The r ay misses
t he t orus if t he following relat ionship is t rue:
y
in
= y
0
+
y
t
in
,
y
out
= y
0
+
y
t
out
,
(y
in
> b and y
out
> b) or (y
in
< b and y
out
< b),
where t
in
and t
out
are t he int er sect ion d ist ances t o t he bound ing sphere.
256
V.2 INTERSECTING A RAY WITH AN ELLIPTICAL TORUS
GRAPHICS GEMS II Edit ed by JAMES ARVO 256
Det er mi ni ng t he Sur f ace Nor mal of a Tor us Det er mi ni ng t he Sur f ace Nor mal of a Tor us Det er mi ni ng t he Sur f ace Nor mal of a Tor us Det er mi ni ng t he Sur f ace Nor mal of a Tor us Det er mi ni ng t he Sur f ace Nor mal of a Tor us
The nor mal at any given p oint on t he su r face of t he t oru s can be
comput ed by evaluat ing t he gr ad ient (i.e., t he par t ial d er ivat ives of t he
sur face funct ion wit h respect t o each of t he var iables, x, y, and z) of t he
sur face at t he point . Given t he hit point P, t he sur face nor mal N is
d ened as follows:
P = P T
d =

P
x
2
+ P
z
2
,
f =

2 d r ( )
da
2
( )
,
N
x
= P
x
f ,
N
y
=

2 P
y
b
2
,
N
z
= P
z
f,
N = N T
T
33
.
The nor mal in wor ld coord inat e space is fou nd by t r ansfor ming t he
nor mal from t he local coord inat e sp ace by u sing t he inver se of t he
coord inat e t r ansfor mat ion mat r ix T. Since t he upper 3 3 mat r ix in T is
an or t honor mal basis, t he inver se simply is t he t r anspose of t he upper
3 3.
257
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 257
V. 3 V. 3 V. 3 V. 3 V. 3
R RR RRAY-TRIANGLE AY-TRIANGLE AY-TRIANGLE AY-TRIANGLE AY-TRIANGLE
I II IINTERSECTION USING BINARY NTERSECTION USING BINARY NTERSECTION USING BINARY NTERSECTION USING BINARY NTERSECTION USING BINARY
R RR RRECURSIVE SUBDIVISION ECURSIVE SUBDIVISION ECURSIVE SUBDIVISION ECURSIVE SUBDIVISION ECURSIVE SUBDIVISION
Douglas Voorhies David Kirk
Apollo Syst ems Division and Calif ornia Inst it ut e of Technology
Hewlet t Packard Co. Pasadena, Calif ornia
Chelmsf ord, Massachuset t s
The Pr obl em The Pr obl em The Pr obl em The Pr obl em The Pr obl em
Det er mine if a line segment and a t r iangle int er sect . If so, calculat e t he
XYZ coord inat es of t hat int er sect ion, and t he cor respond ing U, V t r iangle
locat ion.
Ini t i al Inf or mat i on Ini t i al Inf or mat i on Ini t i al Inf or mat i on Ini t i al Inf or mat i on Ini t i al Inf or mat i on
The line segment is d ened by XYZ end point coord inat es. (See Fig. 1.)
The t r iangle is d ened by XYZ ver t ex coord inat es, wit h t he coefcient s of
it s AX + BY + CZ + D = 0 plane equat ion available as well.
Const r ai nt s Const r ai nt s Const r ai nt s Const r ai nt s Const r ai nt s
To make t he solut ion effect ive in bot h hard ware and soft war e, t he number
of calculat ions (especially mult iplicat ions) must be minimized , wit h more
d ifcult oper at ions such as d ivid es, root s, and t r anscend ent als avoid ed
ent irely. Int eger ar it hmet ic is prefer able t o oat ing point , again t o per mit
efcient hard ware implement at ion.
The Met hod The Met hod The Met hod The Met hod The Met hod
The 3D int er sect ion problem is d ecomposed int o a ser ies of 1D int er sec-
t ion problems: along t he r ay, along t he t r iangle sid es, and along an axis.
258
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 258
The U,V par amet er s ar e d et er mined par t ially as a sid e effect of t he
int er sect ion calculat ion. There are t hree st eps in t ot al:
1. Find ing t he int er sect ion of t he r ay wit h t he plane of t he t r iangle.
2. Det er mining if t hat point lies insid e or out sid e of t he t r iangle it self.
3. Complet ing t he comput at ion of t he int er sect ion point s t r iangle U,V
par amet er s.
St ep 1 : Ray Pl ane Int er sect i on St ep 1 : Ray Pl ane Int er sect i on St ep 1 : Ray Pl ane Int er sect i on St ep 1 : Ray Pl ane Int er sect i on St ep 1 : Ray Pl ane Int er sect i on
The plane of t he t r iangle is st ored as coefficient s (A, B, C, D) of t he
plane equat ion: AX + BY + CZ + D = 0. This equat ion may be t hought
of as rep r esent ing t he 1-nor m (Manhat t an) d ist ance from t he p lane:
AX + BY + CZ + D = Manhat t an dist ance where t he scaling fact or s
for t he t hree axes may not be equal.
By evaluat ing t his funct ion for end point 1 and end point 2, we get t he
signed d ist ance above or below t he plane for t hese t wo point s. (This
calculat ion requires six mult iplicat ions and six ad d it ions.) If t hese t wo
d ist ances are not zero and agree in sign, t hen bot h are on t he same sid e
of t he plane, and t he line int er val d oes not int er sect t he plane. If one
d ist ance is zero, t hen t hat end point is t he int er sect ion point , and we can
skip t o t he next st ep. If bot h are zero, t he line segment and t he t r iangle
are coplanar t o wit hin t he precision of t he ad d resses, and are presumed
t o not int er sect .
If t he end point d ist ances are nonzero and d iffer in sign, t hen t he plane
passes t hrough or bet ween t hese end point s. The int er sect ion of t he plane
Figur e 1.
259
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 259
wit h t he line segment bet ween t he end point s may be found by recur sive
subd ivision of t he int er val. The int er val is shor t ened by half each it er at ion
by t aking t he int er val' s cu r rent end p oint s and aver aging t hem, t hu s
comput ing t he int er val mid point . The Manhat t an d ist ances also are aver-
aged , prod ucing t he Manhat t an d ist ance for t hat mid point . Each d ivision
of t he int er val prod uces a choice of t wo sub-int er vals; t he one whose end
Manhat t an d ist ances d iffer in sign is pur sued . (Each it er at ion requires
four ad d it ions, four shift s, and a zero d et ect .) Thus:
Init ially: End 1 & End 2 dene t he line segment
(XYZ and dist ance from plane)
unti l (Dist new = 0) do
Comput e Midpoint :
Xnew (X1 + X2) / 2;
Ynew (Y1 + Y2)/ 2;
Znew (Z1 + Z2)/ 2;
Dist new (Dist 1 + Dist 2)/ 2;
Choose new int erval:
i f (SIGN(Dist 1) = SIGN(Distnew)) then End 1 New;
el se End 2 New;
endl oop;
Whereupon (XYZ)new is t he int ersect ion point
St ep 2 : Poi nt Tr i angl e Int er sect i on St ep 2 : Poi nt Tr i angl e Int er sect i on St ep 2 : Poi nt Tr i angl e Int er sect i on St ep 2 : Poi nt Tr i angl e Int er sect i on St ep 2 : Poi nt Tr i angl e Int er sect i on
The second par t of t he algor it hm d et er mines if t he int er sect ion point lies
insid e t he t r iangle. This implicit ly is a 2D problem, since t he plane
int er sect ion point and t he t r iangle are coplanar. The coord inat e whose
axis is most or t hogonal t o t he plane simply is d ropped , t hus project ing
t he int er sect ion point and t he t r iangle on t o t he plane of t he remaining
axes. It s d et er minat ion involves t wo 1D proced ures, wit h t he r st proce-
d ure car r ying an ext r a coord inat e along for use in t he second .
Aft er d ropping t he coord inat e for one axis, we project t he int er sect ion
point and t r iangle ver t ices on t o one of t he remaining t wo axes (by simply
select ing t hat axiss coord inat e); t his is shown in Fig. 2. Eit her axis could
be used , but t he one along which t he t r iangles ext ent is great est pre-
ser ves more precision. The int er sect ion point s project ion on t o t his axis
will lie wit hin t he ext ent of eit her zero or t wo t r iangle ed ges. If no t r iangle
260
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 260
ed ge over laps t he int er sect ion point s project ion, t hen t he line segment
and t he t r iangle d o not int er sect .
For t hose t wo ed ges whose ext ent s over lap t he int er sect ion point in t he
chosen axiss d imension, we must nd t he act ual t r iangle ed ge locat ions
t hat project on t o t he same axis locat ion as t he int er sect ion point . We use
recur sive subd ivision separ at ely on bot h t r iangle ed ges t o converge upon
t hese point s. Each subd ivision begins wit h t he ver t ices for it s ed ge and
subd ivid es t he ed ge recur sively. On each it er at ion, t he axis project ion of
t he new mid point is compared wit h t hat of t he int er sect ion point , and t he
sub-int er val whose project ion cont ains t he int er sect ion point s project ion
is pur sued . Event ually, bot h ed ges converge on 2D locat ions having t he
axis coord inat e equal t o t he int er sect ion point . (This calculat ion requires
t wo ad d it ions, one subt r act ion, and t wo shift s per ed ge it er at ion, for a
t ot al of four ad d it ions, t wo subt r act ions, and four shift s per it er at ion.) In
St ep 3, we will want t he pat t er n of subd ivision d ecisions t hat converge on
t hese ed ge point s; t o save t hem requires t wo shift regist er s.
In t he following algor it hm d enit ion, we use t he not at ion L, M, and S
t o rep resent t he axes (among X, Y, and Z) in which t he p ar t icu lar
t r iangles ext ent s are lar gest , med ium, and smallest , respect ively:
Init ially: End 1 and End 2 are t he (L, M) t riangle edge vert ices
Orient at ion = + if L2 > L1 else Orient at ion =
unti l (Ld ist = 0) do
Comput e Midpoint :
Lnew (L1 + L2)/ 2;
Mnew (M1 + M2)/ 2;
Ld ist Lnew Lint er sect ion;
Choose new int erval:
i f (SIGN(Ld ist ) = Or ient at ion) then End 2 New;
el se End 1 New;
endl oop;
Whereupon (L, M)new is edge point wit h Lnew) = Lint ersect ion
We now look at t he span bet ween t hese t wo ed ge point s and d o 1D
compar isons in t he M d imension. If t he int er sect ion point lies on t he
span bet ween t hese t wo ed ge locat ions, t hen t he int er sect ion point is
insid e t he t r iangle, and t he int er sect ion t est succeed s; ot her wise, it is
261
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 261
Figure 2.
out sid e, and t he int er sect ion t est fails. (This requires only t wo compar-
isons of Mint er sect ion against t he t wo MnewS). Figu re 2 illu st r at es t he
project ion on t o t he M axis as well.
St ep 3 : U, V St ep 3 : U, V St ep 3 : U, V St ep 3 : U, V St ep 3 : U, V Comput at i on Comput at i on Comput at i on Comput at i on Comput at i on
If int er sect ed t r iangles are assumed t o have a canonical U, V mapping of
0, 0, 0, 1, and 1, 0 at t he t hree ver t ices, as shown in Fig. 3, t hen t he U, V
values at t he t wo ed ge point s are available d irect ly.
The pat t er n of subd ivision d ecisions (or t he pat t er n subt r act ed from 1)
encod es t he U or V value for t he result ing ed ge point . For example, if
one ed ge point is t wo-t hird s of t he way from t he 0, 0 ver t ex t o t he 1, 0
ver t ex, t hen t he subd ivision d ecisions proceed : far int er val, near int er val,
far int er val, near int er val . . . , et c. Expressing t his pat t er n as a binar y
Figur e 3.
262
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 262
fr act ion (.1010101010101010) gives t he U p ar amet er of t his examp le
point .
Edge Verti ces Parameter Val ues at Edge Poi nt
U V
0,0 0,1 0 subd ivision fr act ion
0,0 1,0 subd ivision fr act ion 0
0,1 1,0 subd ivision fr act ion 1-subd ivision fr act ion
Given t he U, V values for t he t wo ed ge point s, t he U, V value for t he
int er sect ion point t hat lies on t he span bet ween t hem can be comput ed by
yet anot her recur sive subd ivision of t his span. The ed ge point M coord i-
nat es and U, V par amet er s are aver aged t o d et er mine mid point values for
each it er at ion. Mmid p oint is comp ared wit h Mint er sect ion t o d et er mine
which sub-int er val t o pur sue. When t hese M coord inat es are equal, t he
U, V values are cor rect for t he int er sect ion point . (This requires t hree
ad d it ions, one subt r act ion, and t hree shift s.)
Init ially: End 1 and End 2 are t he t wo (M, U, V) t riangle edge point s
Orient at ion = + if M2 > M1 else Orient at ion =
unti l (Mint er sect ion = Mnew) do
Comput e Midpoint :
Mnew (M1 + M2) / 2
Unew (U1 + U2)/ 2
Vnew (V1 + V2) / 2
Md ist Mnew Mint er sect ion
Choose new int erval:
i f (SIGN(Md ist ) = Or ient at ion) then End 2 New
el se End 1 New
endl oop;
Whereupon (U, V)new is paramet ric t riangle locat ion
for t he int ersect ion point
Concl usi on Concl usi on Concl usi on Concl usi on Concl usi on
This met hod subst it ut es binar y recur sive subd ivision for d ivision in nd -
ing int er sect ion point s along line segment s. By using only simple ar it h-
263
V.3 RAY-TRIANGLE INTERSECTION USING BINARY RECURSIVE SUBDIVISION
GRAPHICS GEMS II Edit ed by JAMES ARVO 263
met ic oper at ions, it is suit able for use on comput er s wit h weak oat ing-
point capability, or even directly in hardware. An advantage is that part of
t he comput at ion need ed t o d et er mine t he U, V t r iangle locat ion of t he
int er sect ion point simply is a sid e effect of d ecid ing whet her t here is any
int er sect ion. A d isad vant age is t he need for t he t r iangles plane equat ion
coefcient s in ad d it ion t o t he ver t exes.
This int er sect ion t echniqu e solves t he 3D r ay-t r iangle int er sect ion
problem by red ucing it t o a sequence of 1D and 2D problems. This aspect
of t he algor it hm is useful regard less of whet her binar y recur sive subd ivi-
sion or d ivision is used .
See also (390) An Efcient Ray-Polygon Int er sect ion, Did ier
Bad ouel; (394) Fast Ray-Polygon Int er sect ion, And rew Woo
264
V.4 IMPROVED RAY TAGGING FOR VOXELBASED RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 264
V. 4 V. 4 V. 4 V. 4 V. 4
I II IIMPROVED RAY TAGGING FOR MPROVED RAY TAGGING FOR MPROVED RAY TAGGING FOR MPROVED RAY TAGGING FOR MPROVED RAY TAGGING FOR
VOXEL-BASED RAYTRACING VOXEL-BASED RAYTRACING VOXEL-BASED RAYTRACING VOXEL-BASED RAYTRACING VOXEL-BASED RAYTRACING
David Kirk
Calif ornia Inst it ut e of Technology
Pasadena, Calif ornia
and
James Arvo
Apollo Syst ems Division of Hewlet t Packard
Chelmsf ord, Massachuset t s
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
A common d ifcult y t hat ar ises in r ay t r acing spat ially subd ivid ed scenes
is caused by object s t hat penet r at e more t han one voxel. The problem is a
d egr ad at ion in per for mance d ue t o repeat ed r ay-object int er sect ion t est s
bet ween t he same r ay and object . These red und ant t est s occur when a r ay
st eps t hrough sever al voxels occupied by t he same object before nd ing
an int er sect ion. One st r at egy t hat avoid s t his problem is t o employ a
mailbox d escr ibed by Ar nald i et al. (1987). A mailbox, in t his cont ext ,
is a means of st or ing int er sect ion result s wit h object s t o avoid red und ant
calculat ions. Each object is assigned a mailbox and each d ist inct r ay is
t agged wit h a unique number. When an object is t est ed for int er sect ion,
t he result s of t he t est and t he r ay t ag are st ored in t he object ws mailbox.
Before t est ing each object , t he t ag st ored in it s mailbox is compared
against t hat of t he cur rent r ay. If t hey mat ch, t he r ay has been t est ed
previously against t his object and t he result s can be ret r ieved wit hout
being recalculat ed .
Unfor t u nat ely, t his scheme can break d own when t he wor ld object
hier archy cont ains mu lt ip le inst ances of sp at ial su bd ivision aggregat e
object s; t hat is, collect ions of object s bund led wit h a r ay int er sect ion
t echnique based on an oct ree, a unifor m gr id , or some ot her spat ial d at a
st r uct ure. In such a scene, sever al int er sect ions may occur bet ween a r ay
and inst ances of an aggregat e object , each inst ance being geomet r ically
d ist inct in t he wor ld coord inat e syst em. Therefore, t o use t he t agging
scheme cor rect ly, we must be careful t o d ist inguish bet ween child object s
wit hin d ifferent inst ances. One way t o d o t his is t o upd at e a r ays t ag
265
V.4 IMPROVED RAY TAGGING FOR VOXELBASED RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 265
Oct ree_Int er sect (Ray, Oct ree, Hit _d at a)
Ray: struct; Ray origin, direct ion, et c.
Oct ree: struct; Local dat a for oct ree.
Hit _d at a: struct; Det ails of int ersect ion.
begi n
Increment al local int ersect ion invocat ion count er.
Oct ree.t ag Oct ree.t ag + 1;
Walk t hrough voxels, looking for rst int ersect ion.
repeat
get next Voxel of Oct ree pierced by Ray;
Test all object s in current voxel
for each Child associat ed wit h Voxel begi n
i f Oct ree.t ag = Child .t ag Then
This_t est Child .mailbox;
el se begin
Int er sect _Object (Ray, Child .Object , This_t est );
Child .mailbox This_t est ;
Child .t ag Oct ree.t ag;
end;
i f This_t est is a closer hit t han Hit _d at a then
Hit _d at a This_t est ;
endfor;
unti l int er sect ion found or no more voxels;
end
Figure 1. A proced ure for using local r ay-object int er sect ion t ags.
266
V.4 IMPROVED RAY TAGGING FOR VOXELBASED RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 266
whenever it encou nt er s an inst ance of an aggregat e object , t hereby
invalid at ing t he previous cont ent s of t he mailboxes. However, t his can be
awkward because knowled ge about r ay t ags must percolat e t hroughout
ever y par t of t he r ay t r acer, even mod ules complet ely d ivorced from
spat ial subd ivision. In par t icular, t he r ay t ag would need t o be upd at ed
ever y t ime a new r ay is gener at ed or t r ansfor med .
An Impr oved Techni que An Impr oved Techni que An Impr oved Techni que An Impr oved Techni que An Impr oved Techni que
A bet t er approach st ems from t he obser vat ion t hat t he it ems t hat need t o
be t agged are not r ays at all, but int er sect ion quer ies bet ween r ays and
aggregat e object s. Therefore, t he r ay t ag can be replaced by invocat ion
count er s resid ing only wit hin aggregat e object s based on spat ial subd ivi-
sion. The t ag t hen is par t of t he pr ivat e d at a of an aggregat e and is
increment ed each t ime it s r ay-int er sect ion t echnique is invoked on behalf
of any inst ance. The mailboxes are st ill associat ed wit h child object s
wit hin t he aggregat e, and t he t ag is compared wit h t he cont ent s of t hese
mailboxes, as before (Figure 1).
The benet s of t his ap p r oach ar e t wo-fold . Fir st , t he r ay t ag and
mailbox concept s are localized t o where t hey are used . Therefore, t he
bulk of t he r ay t r acer can remain unaffect ed by t hem; t ags need not be
copied or upd at ed when r ays are creat ed or t r ansfor med . The second
benet is t hat red und ant int er sect ion t est s are avoid ed complet ely, even
in t he presence of inst anced aggregat e object s.
As object -or ient ed progr amming t echniques are ad opt ed more wid ely in
r ay t r acing implement at ions, it will become common t o encapsulat e basic
r ay t r acing oper at ions such as r ay-aggregat e int er sect ion quer ies, CSG
op er at ions, and shad er s wit hin object s t hat behave mu ch as simp le
p r imit ives (Kir k and Ar vo, 1988). Obser vat ions abou t t he localit y of
infor mat ion allow us t o hid e d at a st ruct ures wit hin t he object s, removing
t hem from t he main bod y of t he r ay t r acer, as we have d one here wit h r ay
t ags.
267
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 267
V. 5 V. 5 V. 5 V. 5 V. 5
E EE EEFFICIENCY IMPROVEMENTS FFICIENCY IMPROVEMENTS FFICIENCY IMPROVEMENTS FFICIENCY IMPROVEMENTS FFICIENCY IMPROVEMENTS
F FF FFOR OR OR OR OR HI HI HI HI HIERARCHY TRAVERSAL ERARCHY TRAVERSAL ERARCHY TRAVERSAL ERARCHY TRAVERSAL ERARCHY TRAVERSAL
I II IIN RAY TRACING N RAY TRACING N RAY TRACING N RAY TRACING N RAY TRACING
Eric Haines
3D / Eye, Inc.
It haca, New York
One common scheme for acceler at ing r ay t r acing is using a hier archical
set of bound ing volumes. In t his scheme, a t ree st r uct ure is for med in
which t he root is a bound ing volume enclosing all object s in t he scene,
and each child is an object or a bound ing volume cont aining more object s
or volumes (Rubin and Whit t ed , 1980; Weghor st et al., 1984). Such a
hier archy can be for med manually or by var ious algor it hms (Kay and
Kajiya, 1986; Gold smit h and Salmon, 1987). The hier archy is accessed by
t est ing a r ay against t he root volume. If it hit s, t he volume is opened up
and t he object s or volumes wit hin are t est ed for int er sect ion. This process
cont inues unt il t he ent ire t ree is t r aver sed , at which t ime t he closest
int er sect ion is ret ur ned . What follows are improved t ree t r aver sal t ech-
niques, many of which have not been published before or have been
over looked .
One simp le imp rovement is t o u se t he cu r rent closest int er sect ion
d ist ance as an upper bound on how far t he r ay t r avels. For example, if t he
r ay hit s a sphere at some d ist ance, t here is no good reason t o examine t he
cont ent s of any bound ing volumes beyond t his d ist ance. For t hat mat t er,
if a polygon is int er sect ed at a d ist ance beyond t his upper bound , t he
polygon must be missed (and so t he insid e-out sid e t est for t he polygon
can be avoid ed ).
Kay and Kajiya improved upon t he t r aver sal process by keeping t r ack
of int er sect ed bound ing volumes and t heir int er sect ion d ist ances. The
closest volume on t his list is ret r ieved via heap sor t , t hen is opened and
examined . If at any t ime t he ret r ieved volume is beyond t he upper bound
d ist ance, t hen t he rest of t he volumes must be missed and so t he process
is complet e. Jeff Gold smit h and I have not ed t hat t his sor t ing process
268
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 268
should not be d one for shad ow r ays, since any int er sect ion found will
block t he light .
Caching is a t echnique t hat can improve efciency in t r aver sal. Shadow
object caching is a good example of t he met hod (Haines and Greenberg,
1986). At each int er sect ion nod e in t he r ay t ree, st ore a set of object
point er s, one per light source. Set each point er init ially t o null. Whenever
a shad ow t est is d one at t his nod e and for a given light , st ore t he object
hit by t he r ay in t he point er locat ion (or st ore null if no object is hit ). At
t he beginning of each shad ow t est , check if t here is an object for t his light
at t he nod e. If so, t est t his object r st . If t he r ay hit s t he object , no more
t est ing is need ed . Ot her wise, cont inue shad ow t est ing as before.
The pr inciple is simple enough: An object t hat blocked t he last shad ow
r ay for a nod e and light probably is going t o block t he next r ay. Using
Ar nald is mailboxes t echnique of mar king object s (Ar nald i, et al., 1987)
avoid s t est ing t he object t wice (once in t he cache and once d ur ing regular
t r aver sal). The mailbox algor it hm is t o give each r ay a unique ID, and
st ore t his ID in t he object when it is t est ed against t he r ay. At t he
beginning of any int er sect ion t est , if t he object s ID mat ches t he r ays ID,
t hen t he object alread y has been t est ed against t he r ay.
Anot her t echnique is t o save t r ansparent object s for lat er int er sect ion
while p er for ming shad ow t est ing (or, memor y p er mit t ing, t o have a
separ at e hier archy for t hem alt oget her ). Only if no opaque object is hit d o
t he t r ansparent object s need t o be t est ed . The id ea here is t o avoid d oing
wor k on t r ansparent object s when, in fact , t he light d oes not reach t he
object .
Caching also can be ap p lied t o t r acing shading r ays; t hat is, eye,
reect ion, or refr act ion r ays. Keep t r ack of t he closest object (if any) last
int er sect ed at t he nod e and t est t his object r st . If t he object is hit , t here
now is a good upper bound on t he r ays lengt h. Bound ing volumes
beyond t his d ist ance are d iscard ed , which can cut d own consid er ably on
t he amount of t he hier archy t r aver sed . In fact , t his minor ad d it ion can
give much of t he benet of Kay and Kajiyas heap sor t scheme wit h much
less implement at ion and overhead . It also can aid Kay and Kajiyas
met hod by helping t o prune t he t ree immed iat ely.
There are a var iet y of t echniques t hat improve t he t r aver sal process
it self. One t op-down preprocess met hod is t o open bound ing volumes
t hat cont ain an end point of t he r ay. For example, a large number of r ays
or iginat e from t he eye locat ion. So, before t r acing any of t hem, t est t he
269
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 269
eyes locat ion against t he root bound ing volume. If it is insid e, t his box
always must be hit ; recur sively t est t he eye locat ion on d own t he t ree. Put
t he bound ing volumes not enclosing t he eye locat ion, and all object s
found insid e opened bound ing volumes, on a list . Use t his list of object s
for t est ing all r ays from t he eye. In t his way, unneed ed int er sect ion t est s
are eliminat ed at t he st ar t . The same process can be d one for each point
light source.
This list for mat ion process is shown in Fig. 1. In t his example, t he r ay
or igin is found t o be insid e bound ing volume 1; so, t his bound ing volume
is opened and t he r ay or igin is t est ed against t he t hree child ren. The
or igin is found t o be in bound ing volume 2, so it s child ren are t est ed .
Bound ing volume 5 also encloses t he or igin, so it s child ren are examined .
These child ren bot h are object s, so t hey are put on t he t est list . Checking
t he ot her child ren of BV2, object 1 is put on t he list , and BV6 is t est ed
against t he or igin. This t ime, t he r ays or igin is not insid e t he bound ing
volume, so BV6 is put on t he list . This t r aver sal process cont inues unt il
t he ent ire t ree has been classied .
Figure 1. Top-d own list for mat ion.
270
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 270
A bot t om-up met hod can be d one on t he y for r ays or iginat ing on an
object . All ancest or s of t he or iginat ing object must be hit by t hese r ays.
Beginning at t he parent bound ing volume of t he or iginat ing object , t est
each son against t he r ay. Move t o t he parent of t his bound ing volume, and
t est all sons except t his one. Cont inue moving up t he t ree t hrough each
ancest or unt il d one. This t r aver sal has t wo ad vant ages. The obvious one
is t hat t he object s ancest or bound ing volumes never have t o be t est ed
against t he r ays. The ot her ad vant age is t hat object s relat ively close t o t he
object are t est ed r st for int er sect ion, t hus provid ing a possible upper
bound ear ly in t he process. This approach was used successfully in t he
ear ly Cor nell r ay t r acer.
This process is similar t o caching in t hat t he list s for med can be reused
for r ays or iginat ing from t he same object . Inst ead of t r aver sing and
int er sect ing, simply move up t he hier archy from t he or iginat ing object
and st ore t he d irect sons of t hese ancest or s (except for t he or iginat ing
sons). This list st ays t he same t hroughout t he rend er ing, so it can be used
whenever a r ay begins on t hat object . If keeping all list s around for t he
d ur at ion of t he process cost s t oo much memor y, an alt er nat ive is t o keep
t he list s in a similar fashion t o shad ow cache object s: St ore t he object s
list at t he int er sect ion nod e. If t he or iginat ing object is t he same for t he
next r ay st ar t ing from t his nod e, t hen t his list can be reused ; ot her wise, it
is freed and a new list formed. Note that the list at a node can be used for
a large number of r ays: t he reect ion r ay, t he refr act ion r ay, and all
shad ow r ays from t his object . Amor t izing t he cost of for ming t his list once
over t he number of r ays per nod e and t he number of t imes t he nod e has
t he same object usually gives a minimal cost per r ay for list management .
An example of how t his process wor ks is shown in Fig. 2. A r ay
or iginat es on object 7; so, object 7 it self is st ored for lat er t est ing in t he
list . This object is shown in parent heses, since one could avoid st or ing it
if it is guar ant eed t hat t he r ay cannot int er sect t his or iginat ing object
(e.g., a r ay or iginat ing on a polygon cannot re-int er sect t his polygon). The
parent bound ing volume 8 is opened and it s ot her son, object 8, is put on
t he list . The parent of BV8 is BV6, which t hen is opened , and it s ot her
son, object 6, is placed on t he list . This process cont inues unt il t he root
nod e, BVI, is opened .
A fur t her t r aver sal enhancement is combining t he t op-d own and bot -
t om-up approaches. Say t here is a list for a given object at a given nod e.
If t he next r ay or iginat es on a d ifferent object , we nor mally would rebuild
271
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 271
Figur e 2. Bot t om-up t r aver sal.
t he list . However, what if t he r ays or igin is insid e t he bound ing volume
of t he list s or iginat ing object ? If so, t he r ay must hit all t he bound ing
volumes eliminat ed when t he list was mad e, and so t he list can be reused
for t his r ay.
It is int erest ing t o not e t hat r ays t hat or iginat e slight ly out sid e t he
bound ing volume st ill can use t he list in fact , any r ay can use t he list .
However, t he fur t her t he r ay is from t he bound ing volume t hat for med t he
list , t he wor se t he t r aver sal t ime. Some bound ing volumes will be open on
t he list t hat t he r ay would not have opened , and some bound ing volumes
t hat could have been culled by removing t he ancest or s will have t o be
t est ed against t he r ay inst ead .
As shown before, t here is much benet in obt aining a close int er sect ion
ear ly on in t r aver sal. This suggest s anot her simple scheme, which is t o
reor d er t he hier archical t ree so t hat object s are befor e bound ing volumes
in t he list of sons of a bound ing volume. All t hings being equal, it is bet t er
t o nd an int er sect ion wit h an object quickly, and possibly prune bound -
ing volumes ear ly on. Sor t ing t he list of sons in t his way suggest s ot her
schemes, such as put t ing larger object s r st in t he list , on t he t heor y t hat
272
V.5 EFFICIENCY IMPROVEMENTS FOR HIERARCHY TRAVERSAL IN RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 272
larger object s ar e more likely t o be hit . Anot her scheme is t o put object s
t hat are quick t o t est r st . For example, if a sphere and a spline pat ch are
equally likely t o be hit by a r ay, it is bet t er t o t est t he sphere r st , as t his
may obt ain an upper bound t hat quickly prunes t he spline from any
t est ing at all. Sor t ing by t he r at io of hit s t o t est s (found empir ically from
t est ing) is anot her possibilit y. A combinat ion of all of t hese fact or s may
be t he best sor t ing scheme.
Likewise, bound ing volumes could be sor t ed by var ious char act er ist ics.
Size and simplicit y of int er sect ion bot h apply as sor t keys. Anot her fact or
is t he number of d escend ant s in t he t ree. In gener al, less d escend ant s
means t hat fewer bound ing volumes will have t o be t r aver sed before
reaching object s. Ou r goal is t o t est object s as soon as p ossible, so
bound ing volumes wit h fewer d escend ant s gener ally are prefer able.
For specialized applicat ions, i.e., for a scene rend ered wit h only eye
r ays, t he sons could be sor t ed by t he d ist ance along t he main d irect ion of
r ays. Object s close by t hen would be t est ed before t hose fur t her behind .
This id ea simply is per for ming a Kay and Kajiya sor t as a preprocess.
Lit t le wor k has been d one on sor t ing t he hier archy t o d at e, so t his whole
area d eser ves explor at ion.
As has been shown, t here are many met hod s for speed ing hier archy
access for r ay t r acing. Some, such as shad ow caching and eye-r ay list
build ing, almost always are wor t h d oing. Ot her s, su ch as object list
build ing, are more d epend ent upon weighing t he savings of t he new
algor it hm ver su s t he ad d it ional set u p and access cost s. Most of t he
t echniques d escr ibed in t his gem are simple t o implement and t est , and
each can yield some bit of savings.
273
V.6 A RECURSIVE SHADOW VOXEL CACHE FOR RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 273
V. 6 V. 6 V. 6 V. 6 V. 6
A AA AA RECURSIVE SHADOW VOXEL RECURSIVE SHADOW VOXEL RECURSIVE SHADOW VOXEL RECURSIVE SHADOW VOXEL RECURSIVE SHADOW VOXEL
C CC CCACH ACH ACH ACH ACHE E E E E FOR RAY TRACING FOR RAY TRACING FOR RAY TRACING FOR RAY TRACING FOR RAY TRACING
Andrew Pearce
Alias Research
Toront o, Ont ario, Canada
This gem d escr ibes a simple t echniqu e for sp eed ing u p shad ow r ay
comput at ion if you are r ay t r acing scenes t hat exploit any t ype of spat ial
subd ivision.
When r ay t r acing shad ow r ays, it is a good id ea t o st ore a point er t o t he
last object t hat caused a shad ow wit h each light source in a shadow
cache (Haines and Greenberg, 1986). The next shad ow r ay t oward s any
light source r st is int er sect ed wit h t he object in t he shad ow cache, and if
an int er sect ion occur s, t he point we are shad ing can be d eclared t o be in
shad ow wit h respect t o t hat light source. This wor ks because it is not
necessar y t o know which object shad ows a light source; it is sufcient t o
know simply t hat an object d oes shad ow a light source. The shad ow
cache t echnique exploit s object coherence in shad owing.
However, if you are r ay t r acing sur face t essellat ions, t he amount of
object coherence in t he shad ow is minimal, since t he t essellat ed t r iangles
prod uced usually are quit e small. It is a simple mat t er t o ext end t he
shad ow cache id ea t o includ e t he caching of t he voxel in which t he last
object t o shad ow t he light was int er sect ed , in a voxel cache wit h each
light source. If t he shad ow-cached object d oes not shad ow t he light
source, t hen one of t he object s in t he vicinit y (as enclosed by t he voxel)
likely will, so all of t he object s in t he voxel are t est ed for int er sect ion t o
see if t hey might shad ow t he light .
David Jevans ad d ed t he comment t hat if t he last shad ow r ay t oward s a
given light source was spawned from a pr imar y r ay, and t he cur rent
shad ow r ay was spawned from a reect ion r ay, t hen t he infor mat ion in
t he shad ow and voxel cache is useless, and probably will wast e comput a-
t ion by int er sect ing object s t hat could not possibly shad ow t he light
274
V.6 A RECURSIVE SHADOW VOXEL CACHE FOR RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 274
source. What he suggest s is t hat a t ree of shad ow voxel caches be st ored
wit h each light source. To access t he shad ow voxel cache t ree, t he hist or y
of each r ay is kept at all t imes; a r ays hist or y d escr ibes uniquely it s
posit ion in t he shad ing t ree for t he cur rent pr imar y (eye) r ay. To keep
t r ack of t he cur rent r ays hist or y, a simple bit t able can be employed
(called pat h in t he cod e).
The shad ow voxel cache will wast e comput at ion when t he spawning
point for t he shad ow r ays moves d r ast ically. Therefore, t he shad ow voxel
cache t rees should be cleared at t he end of each scanline unless scanlines
are t r aced in alt er nat ing d irect ions (i.e., even scanlines sweep left t o r ight
across t he screen, od d scanlines sweep r ight t o left ). There is no way t o
avoid wast ing comput at ion when t he spawning point is changed d r ast i-
cally d ue t o highly cur ved object s or t r ansit ioning bet ween object s; one
must hope t hat t he benet s of t he shad ow voxel cache t ree out weigh t his
lit t le bit of wast ed comput at ion, and , in pr act ice, I have fou nd t his
t echnique t o be ver y effect ive.
275
V.7 AVOIDING INCORRECT SHADOW INTERSECTIONS FOR RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 275
A AA AAVOIDING INCORRECT VOIDING INCORRECT VOIDING INCORRECT VOIDING INCORRECT VOIDING INCORRECT
S SS SSHADOW HADOW HADOW HADOW HADOW I II IINTERSECTIONS NTERSECTIONS NTERSECTIONS NTERSECTIONS NTERSECTIONS
F FF FFOR RAY TRACING OR RAY TRACING OR RAY TRACING OR RAY TRACING OR RAY TRACING
Andrew Pearce
Alias Research
Toront o, Ont ario, Canada
This gem is a quick way t o avoid int er sect ing t he object t hat gener at ed
t he shad ow r ay when r ay t r acing, and is appropr iat e for planar object s.
Due t o oat ing-point precision problems, many r ay t r acer s ad d a small
epsilon t o t he st ar t ing posit ion of t he shad ow r ay (along t he d irect ion of
it s t r avel) t o avoid int er sect ing t he object t hat has just been int er sect ed . If
t he epsilon is not ad d ed , t hen it is possible t hat t he shad ow r ay will nd
an int er sect ion wit h t he object it is supposed t o be shad ing (r ight at t he
or igin of t he shad ow r ay), result ing in an incor rect shad ow.
When r ay t r acing object s t hat are cont ained in most t ypes of spat ial
subd ivision st r uct ures, it is possible t o int er sect an object t hat spans
mult iple voxels more t han once. A simple t echniquewhich is ment ioned
by Ar nald i et al.(1987), Pearce (1987), and Amanat id es and Woo (1987)
is t o assign a unique id ent icat ion number t o each r ay so t hat object s
will be t est ed for int er sect ion wit h any given r ay only once. Once an
object is t est ed for int er sect ion, t he r ays number is st ored in a last -ray
eld in t hat object . Before int er sect ing an object , t he r ays number and
t he last -r ay eld in t he object are compared ; if t he number s mat ch, t hen
t he object alread y has been encount ered and t est ed in a previous voxel
and has been eliminat ed from t he set of possible int er sect ions, so no
fur t her processing is d one on t hat object .
An ad vant age of saving r ay nu mber s wit h each object is t hat t he
shad ow t est easily can ignore t he spawning object simply by set t ing t he
V. 7 V. 7 V. 7 V. 7 V. 7
276
V.7 AVOIDING INCORRECT SHADOW INTERSECTIONS FOR RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 276
object s l ast -r ay el d t o t h e sh ad ow r ays n u mber befor e st ar t i n g
t he shad ow t est . However, if t he object s are nonplanar and can cur ve
around t o self-shad ow, t hen t he t r ad it ional epsilon met hod (or somet hing
similar ) must be used .
277
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 277
V. 8 V. 8 V. 8 V. 8 V. 8
A AA AA BODY COLOR MODEL BODY COLOR MODEL BODY COLOR MODEL BODY COLOR MODEL BODY COLOR MODEL: :: ::
A AA AABSORPTIO BSORPTIO BSORPTIO BSORPTIO BSORPTION N N N N OF LIGHT OF LIGHT OF LIGHT OF LIGHT OF LIGHT
T TT TTHROUGH TRANSLUCENT MEDIA HROUGH TRANSLUCENT MEDIA HROUGH TRANSLUCENT MEDIA HROUGH TRANSLUCENT MEDIA HROUGH TRANSLUCENT MEDIA
Mark E. Lee Samuel P. Uselt on
Amoco Product ion Company Comput er Sciences Corporat ion
Tulsa Research Cent er and NASA Ames Research Cent er,
Tulsa, Oklahoma Mof f et t Field, Calif ornia
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Body color is t he r esu lt of t he select ive absor p t ion of cer t ain wave-
lengt hs of light as t he light t r avels t hrough a med ium. The abilit y t o use
bod y color is impor t ant bot h in realist ic image synt hesis and in scient ic
visualizat ion. The at t enuat ion and color shift of light t r aveling t hrough an
almost t r ansparent med ium provid e impor t ant visual cues t o t he t hick-
ness, d ensit y, and shape of t he object being t r aver sed . Tr ad it ional gr aph-
ics shad ing mod els have concent r at ed on shad ing at sur faces, which is
sufcient for many object s. However, includ ing t he abilit y t o mod el t he
bod y color of t hose object s t hat act as lt er s enhances t he realism and , in
some cases, improves t he int er pret abilit y of t he images prod uced .
Theor et i cal Basi s Theor et i cal Basi s Theor et i cal Basi s Theor et i cal Basi s Theor et i cal Basi s
The t heor y of physical opt ics is used t o d er ive for mulas for calculat ing
t he at t enuat ion of t he int ensit y of light as it passes t hrough t r anslucent
mat er ials. Absor pt ion occur s when light waves lose energy as t hey t r avel
t hrough a med ium. The amount of energy absor bed increases wit h t he
t hickness of t he med ium. If t he med ium absor bs more energy in one
wavelengt h t han ot her s, t hen t he over all color of t he light changes as it
t r avels t hrou gh t he absor bing med iu m. This is t he p r incip le behind
colored lt er s. An absor bing med ium exhibit s bod y color as d ist inguished
from sur face color, since t he color comes from light t hat has t r aveled a
d ist ance t hrough t he med ium. Sur face color comes by t he reect ion of
278
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 278
light at t he sur face. Paint s give t heir color pr imar ily by absor pt ion. Met als
give t heir color pred ominant ly by reect ion (Jenkins and Whit e, 1937).
All of t he for mulas in t his gem are st at ed for a single wavelengt h. If t he
color space being used is based on a cont inuous r ange of wavelengt hs,
t hen all of t he t er ms in t he for mulas are funct ions over t he cont inuous
r ange of wavelengt hs. If t he color space is d iscret e in wavelengt h, such as
an RGB color space, t hen all of t he t er ms are vect or s wit h one element for
each d iscret e wavelengt h.
Absor pt i on by Homogeneous Medi a Absor pt i on by Homogeneous Medi a Absor pt i on by Homogeneous Medi a Absor pt i on by Homogeneous Medi a Absor pt i on by Homogeneous Medi a
The basic absor pt ion for mula is d er ived from t he amount of absor pt ion in
t he med ium t hrough layer s of unit t hickness (Jenkins and Whit e, 1937).
Suppose t hat t he light wave ent er s a med ium layered in unit t hicknesses.
The int ensit y of t he wave ent er ing t he med ium is I
0
. The int ensit y of t he
wave as it ent er s t he second layer will be a fr act ion q of t he init ial
int ensit y I
0
, such t hat
I
1
= qI
0
.
As t h e wave exi t s t h e secon d l ayer, t h en t h e n ew i n t en si t y I
2
i s
I
2
= qI
1
= q
2
I
0
.
The same effect t akes place as t he wave moves from layer t o layer. Aft er
n layer s,
I
n
= q
n
I
0
.
Therefore, as t he layer s become innit ely t hin,
I
x
= q
x
I
0
for some d ist ance x. The fact or q is called t he t ransmission coefcient
(Jenkins and Whit e, 1937) and represent s t he fr act ion of t he int ensit y of
light remaining aft er t r aveling a unit d ist ance t hrough t he volume. This
ver sion of t he absor pt ion mod el is t he mod el proposed by Kay and
Greenberg (1979) and Hall (Hall and Greenberg, 1983).
279
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 279
The same gener al for mula can be d er ived in a d ifferent manner (Jenkins
and Whit e, 1937). For an innit ely small t hickness, dx, t he fr act ion of t he
int ensit y absor bed is propor t ional t o dx by t he following equat ion:

dI
I
= Adx,
where dl/ I is t he fr act ion of t he int ensit y absor bed in t he t hickness, dx.
The fact or A is t he fr act ion of incid ent int ensit y absor bed p er u nit
t hickness for small t hicknesses. By int egr at ing bot h sid es of t he equat ion,
t he nal int ensit y can be d er ived for any d ist ance t r avelled . Using t he fact
t hat when x = 0, I = I
0
,t he equat ion


dI
I
Adx,
0
x

I
0
I
x

yield s
I
x
= I
0
e
(Ax)

This result is Lamber t s law of absor pt ion. A is called t he absorpt ion


coefficient of t he med iu m (Jenkins and Whit e, 1937). Valu es for t his
par amet er for specic real mat er ials somet imes can be found in var ious
r efer en ces (Gu bar eff et al. , 1960; Pu r d u e Un i ver si t y, 1970a, 1970b,
1970c).
Anot her measure of absor pt ion somet imes is more read ily available. It
is called t he ext inct ion coefcient , k
0
, and is relat ed t o t he absor pt ion
coefcient in t he following manner :

A
4k
0

0
,
where
0
is t he wavelengt h measured in a vacuum (Jenkins and Whit e,
1937). If t he wavelengt h in a vacuum,
0
, is replaced by t he wavelengt h
in t he mat er ial, , t hen k
0
can be replaced by k by using t he relat ionship,
k
0
= nk, where n is t he ind ex of refr act ion for t he med ium, which
280
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 280
implies t hat

A
4k

.
The t er m k is called t he absorpt ion index. Bot h t he ext inct ion coef-
cient and t he absor pt ion ind ex can be found somet imes in t he lit er at ure
(Gubareff et al., 1960; Purd ue Univer sit y, 1970a, 1970b, 1970c). Some-
t imes, t he t er m k is used for t he ext inct ion coefcient inst ead of t he
absor pt ion ind ex and care must be exercised when using t he lit er at ure t o
d et er mine whet her t he ext inct ion coefcient or t he absor pt ion ind ex is
being specied .
By subst it ut ing t hese t wo relat ionships for A, t he absor pt ion for mulas
now can be st at ed as
I
x
= q
x
I
0
,
= I
0
e
(Ax)
=

I
0
e
4 k
0
x ( )

0
,
=

I
0
e
4 k x ( )

,
where x is t he d ist ance t r aveled (Bor n and Wolf, 1975; Jenkins and
Whit e, 1937). Any of t he preced ing for mulat ions may be used d epend ing
on t he availabilit y of t he necessar y par amet er s.
Absor pt i on t hr ough Inhomogeneous Medi a Absor pt i on t hr ough Inhomogeneous Medi a Absor pt i on t hr ough Inhomogeneous Medi a Absor pt i on t hr ough Inhomogeneous Medi a Absor pt i on t hr ough Inhomogeneous Medi a
Su p p ose t hat t he absor p t ive med iu m is not const ant t hrou ghou t t he
volume, but is d ened as a funct ion of posit ion. Now t he ext inct ion
coefcient becomes t he funct ion A(x), where x represent s d ist ance and

dI
I
= A(x)dx.
281
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 281
When int egr at ing over t he t hickness t hrough t he volume, t hen


dI
I

I
0
I
x

=

A x ( ) dx
0
x

result s in I
x
=

I
0
e
A x ( ) dx
0
x

Since
A(x) =

4k
0
x ( )

0
and k
0
(x) = nk(x),
t hen
I
x
=

I
0
e
A x ( ) dx
0
x

,
=

I
0
e

4 k
0
x ( )

0
0
x

dx
,
=

I
0
e

4 k x ( )

0
x

dx
.
Now an int egr al st ill remains for evaluat ion. For some applicat ions, t he
med ia being t r aver sed is piecewise homogeneous or var ies smoot hly in
some known fashion and t he int egr al can be evaluat ed d irect ly. For ot her
applicat ions and var ious gr aphical d isplay met hod s, t he int egr als cannot
be evaluat ed d irect ly. For some applicat ions, numer ical int egr at ion algo-
r it hms su ch as Gau ssian qu ad r at u re can be applied , while for ot her
applicat ions, st at ist ical t echniques such as Mont e Car lo met hod s must be
applied . The best evaluat ion met hod s are highly applicat ion- and d isplay
met hod -d epend ent and must be chosen wisely.
Once again, remember t hat t he absor pt ion for mulas cont ain a wave-
lengt h fact or. The absor pt ion fact or s are wavelengt h-d epend ent and must
be specied for ever y wavelengt h t hat is t o be sampled , allowing cer t ain
wavelengt hs t o be absor bed at higher r at es t han ot her s. Filt er s oper at e on
t his pr inciple. Some wavelengt hs are absor bed complet ely, while ot her s
are allowed t o pass unt ouched , causing an over all shift in t he color of t he
light t o be perceived .
282
V.8 A BODY COLOR MODEL: ABSORPTION OF LIGHT THROUGH TRANSLUCENT MEDIA
GRAPHICS GEMS II Edit ed by JAMES ARVO 282
Re ect i on of Li ght Re ect i on of Li ght Re ect i on of Li ght Re ect i on of Li ght Re ect i on of Li ght
As a sid e not e, t he reect ion of light from a cond uct ing med ium (med ium
wit h free elect rons) also is affect ed by t he ext inct ion coefcient . The
Fresnel for mulas d et er mine t he fr act ion of t he int ensit y of t he light wave
t hat will be reect ed . For mor e on t his subject , please see t he append ix
for t he next gem in t his book.
Concl usi ons Concl usi ons Concl usi ons Concl usi ons Concl usi ons
We have d er ived sever al equ ivalent absor pt ion for mu lat ions, each of
which can be used d epend ing on t he applicat ion and t he availabilit y of
d at a. For st able numer ical comput at ion, we prefer t r ansfor ming t he d at a
int o t he for m using t he absor pt ion coefcient . Unst able cond it ions for t he
exponent ial funct ion, such as und er ow and over ow, are d et ect ed easily
and avoid ed .
See also V.9 More Shad ow At t enuat ion for Ray Tr acing Tr ans-
parent or Tr anslucent Object s, Mar k E. Lee, Samuel P. Uselt on;
(397) Shadow A t t enuat ion for Ray Tracing Transparent
Object s, Andrew Pearce
283
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 283
MORE SHADOW MORE SHADOW MORE SHADOW MORE SHADOW MORE SHADOW
A AA AATTENUATION FOR TTENUATION FOR TTENUATION FOR TTENUATION FOR TTENUATION FOR
R RR RRAY TRACING TRANSPARENT AY TRACING TRANSPARENT AY TRACING TRANSPARENT AY TRACING TRANSPARENT AY TRACING TRANSPARENT
O OO OOR TRANSLUCENT OBJECTS R TRANSLUCENT OBJECTS R TRANSLUCENT OBJECTS R TRANSLUCENT OBJECTS R TRANSLUCENT OBJECTS
Mark E. Lee Samuel P. Uselt on
Amoco Product ion Company and Comput er Sciences Corporat ion
Tulsa Research Company NASA Ames Research Cent er
Tulsa, Oklahoma Mof f et t Field, Calif ornia
Approximat ions f or Shadow Generat ion
This gem cont ains t he d er ivat ion of an approximat ion for t he calculat ion
of a shad ow at t enuat ion t er m for shad ow gener at ion.
Why is an approximat ion necessar y? An accur at e, gener al, comput able
algor it hm for calculat ing t he amount of light t hat passes t hrough t r ans-
parent sur faces t o reach t he point being illuminat ed is d ifcult t o con-
st r uct . Object s such as glass lenses t end t o focus light ont o t he point
being illuminat ed . To d emonst r at e t he d ifcult y in const ruct ing an accu-
r at e mod el, consid er t he light being focused t hrough a simple lens. The
solut ion for light being focused t hrough a lens ont o a single point on t he
sur face is a cont inuous area of t he lens. Det er minat ion of t he focusing
areas for ar bit r ar y mult iple t r ansparent sur faces is ext remely d ifcult .
However, if focusing effect s are ignored , t he shad ow mod el becomes
much simpler.
Pearce (1990) present ed one su ch approximat ion. We wou ld like t o
present anot her approximat ion t hat has been used by t he r ay-t r acing
project at t he Univer sit y of Tulsa (Lee et al., 1986).
The Nave Scheme
Let S be t he shad ow at t enuat ion fact or for t he amount of light t hat
reaches t he point t o be illuminat ed . A nave scheme for calculat ing t he S
t er m send s a r ay back in t he light source d irect ion and d et er mines if any
object s lie bet ween t he point of int erest and t he light source. If any
object s obst ruct t he pat h of t he r ay bet ween t he point of int erest and t he
light source, t hen t he point is assumed t o be in shad ow and S = 0;
V. 9 V. 9 V. 9 V. 9 V. 9
284
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 284
ot her wise, t he point is not shad owed and S = 1. This scheme wor ks
efcient ly; however, for t r ansparent sur faces, t he amount of shad ow is
incor rect . A cer t ain amount of light st ill t r avels t hrough t he t r ansparent
sur face t o reach t he int er sect ion point and t he shad ow is not complet ely
d ar k (0 S 1). A bet t er approximat ion is necessar y.
An Impr oved Scheme An Impr oved Scheme An Impr oved Scheme An Impr oved Scheme An Impr oved Scheme
For many shad ing mod els, such as t he Hall mod el (Hall and Greenberg,
1983; Hal l , 1983; Gl assn er, 1989), t h e amou n t of l i gh t t h at p asses
t hrough t he int er face bet ween t wo med ia (gener ally a sur face) is I
0
k
t
T,
where I
0
is t he amou nt of light incid ent t o t he int er face, k
t
is t he
t r ansmission coefcient from t he shad ing equat ion (in our applicat ion, t he
same as k
s
, t he specular reect ion coefcient ), and T = 1 F, where T
is t he Fresnel t r ansmission cur ve and F is t he Fresnel reect ance cur ve.
(See t he append ix for t his gem for t he calculat ion of t he Fresnel re-
ect ance cur ve.) The new approximat ion proced ure now will const ruct
t he shad ow at t enuat ion t er m S from t he same t r ansmission fact or, k
t
T,
used for t he refr act ion of a r ay t hrough a sur face int er face. A r ay is sent
from t he point of int erest t o t he light source and all point s of r ay-sur face
int er sect ion are calculat ed . Unlike t he refr act ion of a r ay at t he int er face
bet ween t wo med ia, t he d irect ion of t he light r ay is not alt ered at such
point s. By not bend ing t he light r ay at each int er face, t he problem of
d et er mining t he pat h of light from t he light source t hrough t r ansparent
object s ont o ot her sur faces has been eliminat ed . The r ay proceed s from
int er sect ion p oint t o int er sect ion p oint , calcu lat ing new t r ansmission
Figure 1. Calculat ion of shad ow t hrough lens
285
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 285
fact or s and weight ing t he cur rent shad ow at t enuat ion t er m S by t hese
t r ansmission fact or s t o gener at e t he new shad ow at t enuat ion t er m. Also,
as light passes t hrough absor bing med ia, t he amount of absor pt ion should
be fact ored int o t he shad ow at t enuat ion t er m. (See preced ing gem, on
bod y color.)
The at t enuat ion t er m S is calculat ed as follows:
Proced ure Shad ow_r ay()
S = 1
send ray t o t he light source and generat e int ersect ion list
for j = 1 t o number _of_int er sect ions or unt il reach light source
get jt h int er sect ion poi nt
comput e dist ance, d, t hrough previous medium wit h absorpt iont
fact or, A
S = Se
(Ad)
at t enuat ion of light by absorpt ion
comput e Fresnel t ransmission curve, T, for t he surface int er-
face
S = Sk
t
T at t enuat ion of light by surface t ransmission fact or
repeat
end.
When t he light source is reached , S cont ains t he shad ow at t enuat ion t er m
for scaling t he amount of light t hat reached t he point being illuminat ed .
Figure 1 d emonst r at es t he shad ow algor it hm. As t he r ay leaves t he
int er sect ion point and reaches t he lens, t he absor pt ion fact or for med ium
1 and t he t r ansmission fact or for t he int er face bet ween med ium 1 and
med ium 2 are fact ored int o t he S t er m. The process cont inues unt il t he
r ay reaches t he light source, where t he nal t er m is:
S =

e
A
1
d
1 ( )


k
t
1
T
1

e
A
2
d
2 ( )

k
t
2
T
2

e
A
3
d
3 ( )
.
Not ice t hat , since t he absor pt ion and t r ansmission fact or s are present in
t he equat ion, t he equat ion is now wavelengt h-d epend ent . (See preced ing
gem, on bod y color.) The wavelengt h d epend ency allows cer t ain wave-
lengt hs t o be absor bed at higher r at es t han ot her s, causing an over all shift
in t he color of t he light t o be perceived and per mit t ing t he shad ows t o be
colored by t he lt er ing of light by var ious med ia. The images in t he
286
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 286
st r at ied sampling paper by Lee, Red ner, and Uselt on (1985) cont ain
examples of colored shad ows gener at ed by using t his t echnique. Not e
also t he d ar k ed ges and light cent er of t he shad ow cast by t he solid glass
wineglass st em.
This approximat ion can be ext end ed fur t her by t aking d iffuse t r ansmis-
sion of light int o account . Let T
s
be t he specular t r ansmission cur ve as
before (previously called T). Let T
d
be t he d iffuse t r ansmission cur ve, k
st
be t he specular t r ansmission coefcient (previously called k
t
), and k
d t
be
t he d iffuse t r ansmission coefcient (Glassner, 1989). In our project at t he
Univer sit y of Tu lsa, k
st
= k
s
, t he sp ecu lar reect ance coefcient , and
k
d t
= k
d
, t he d iffuse reect ance coefcient . Now, T
s
= 1 F
s
as before,
and using conser vat ion of energy pr inciples, T
d
= 1 F
d
, where F
d
is t he
d iffuse reect ance cur ve. The new shad ow at t enuat ion t hrough t he int er-
face bet ween t wo med ia can be mod eled as k
st
T
s
+ k
d t
T
d
. This might
make for a mor e accu r at e ap p roximat ion for shad ows gener at ed by
frost ed glass. However, most d iffusely reect ing object s are opaque and
Hainess id ea of t est ing for opaque object s r st when calculat ing shad ows
d enit ely should be used before applying t his shad owing approximat ion.
Appendi x Appendi x Appendi x Appendi x Appendi x
Wavel engt h- Dependent Re ect i on and Ref r act i on Wavel engt h- Dependent Re ect i on and Ref r act i on Wavel engt h- Dependent Re ect i on and Ref r act i on Wavel engt h- Dependent Re ect i on and Ref r act i on Wavel engt h- Dependent Re ect i on and Ref r act i on
The reect ion of light fr om a conduct ing medium (med iu m wit h free
elect rons) is affect ed by bot h t he ext inct ion coefcient and t he ind ex of
refr act ion. The Fresnel for mulas d et er mine t he fr act ion of t he int ensit y of
t he light wave t hat will be reect ed (Bor n and Wolf, 1975; Cook, 1982;
Cook and Tor r ance, 1982; Jenkins and Whit e, 1937; Spar row and Cess,
1970; Wiebelt , 1966). Br ight er reect ions, such as reect ions from met al-
lic sur faces, are d ue t o increased mot ion by free elect rons und er t he force
of a light wave. The mot ion is great est at t he most resonant frequencies,
which occur where t he values of t he ext inct ion coefcient are great est .
The effect ive reect ance is a weight ed aver age of t he reect ance in t he
d irect ion par allel t o t he elect r ic eld and t he reect ance in t he d irect ion
per pend icular t o t he elect r ic eld . If t he incid ent light is unpolar ized , t hen
t he weight s of t he par allel and per pend icular t er ms are equal (Bor n and
Wolf, 1975; Dit chbur n, 1976; Jenkins and Whit e, 1937; Wiebelt , 1966).
287
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 287
Special care must be t aken t hat t he complex ind ex of refr act ion, n
c
+ ik
0
,
for t he Fresnel for mulas not be confused wit h t he geomet r ic ind ex of
refr act ion, n, used by r ay t r acing for d et er mining t he d irect ion of refr ac-
t ion. When k
0
= 0, as is t he case for d ielect r ic mat er ials such as glass
and plast ic, t hen t he geomet r ic ind ex of refr act ion, n, is t he same as t he
real por t ion of t he complex ind ex of refr act ion, n
c
(i.e., t he complex
ind ex of refr act ion now is real, as for d ielect r ic med ia); ot her wise, n
c
and
n are d ifferent .
Appr oxi mat i ons f or Appl yi ng t he Fr esnel For mul as Appr oxi mat i ons f or Appl yi ng t he Fr esnel For mul as Appr oxi mat i ons f or Appl yi ng t he Fr esnel For mul as Appr oxi mat i ons f or Appl yi ng t he Fr esnel For mul as Appr oxi mat i ons f or Appl yi ng t he Fr esnel For mul as
Unfor t unat ely, t he Fresnel for mulas for a cond uct ing med ium (met als) are
not read ily available or applicable except for t he int er face bet ween met als
and air (n
c
= 1, k
0
= 0). However, as Cook point s out (Cook, 1982;
Cook and Tor r ance, 1982), t he Fresnel for mulas are only weakly d epen-
d ent on k
0
and , t herefore, t he appear ance of a met allic sur face is not
d egr ad ed t oo severely using t he Fresnel for mulas for t he int er face be-
t ween d ielect r ic sur faces (k
0
= 0), which are well-d ened . The Fresnel
for mulas for d ielect r ic mat er ials (Bor n and Wolf, 1975; Dit chbur n, 1976;
Spar row and Cess, 1970; Wiebelt , 1966) are:
r

=

n
t
cos
i
n
i
cos
t
n
t
cos
i
+ n
i
cos
t
,
r

=

n
i
cos
i
n
t
cos
t
n
i
cos
i
+ n
t
cos
t
,
F

= r

2
,
F

= r

2
, and
F =

1
2
(F

+ F

),
where
n
i
is t he ind ex of refr act ion for t he med ium of incid ence,
n
t
is t he ind ex of refr act ion for t he med ium of t r ansmit t ance,

i
is t he angle of incid ence,
288
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 288

t
is t he angle of refr act ion,
r

is t he r at io of t he amplit ud e of t he incid ent wave and t he reect ed


wave for t he d irect ion par allel t o t he elect r ic eld ,
r

is t he r at io of t he amplit ud e of t he incid ent wave and t he reect ed


wave for t he d irect ion per pend icular t o t he elect r ic eld ,
F

is t he reect ivit y value for t he d irect ion par allel t o t he elect r ic eld ,
F

is t he reect ivit y valu e for t he d ir ect ion p er p end icu lar t o t he


elect r ic eld ,
F

is t he t ot al reect ivit y value when t he incid ent light wave energy is
unpolar ized .
The for mula F = 1/ 2(F

+ F

) hold s only und er t he assumpt ion t hat t he


energy incid ent t o t he d ielect r ic int er face is complet ely unpolar ized . The
energy leaving t he sur face is polar ized or par t ially polar ized for all angles
except 0 and 90 d egrees. However, since no polar izat ion infor mat ion is
being maint ained by t he major it y of all exist ing shad ing mod els, t he
assumpt ion must be mad e t hat t he incid ent energy is complet ely unpolar-
ized .
The cosine t er ms are calculat ed as follows:
cos
i
=

V H for shading mod el applications,
V N for reflected ray weight calculations,
L N for shadow ray attenuation calculations,

'

cos
t
=

1 n
i
2
/ n
t
2
( )
1 cos
2

i
( ) ( )
,
where
L is t he r ay from t he point t o be illuminat ed t o t he light source,
N is t he sur face nor mal,
V is t he incid ent or viewing r ay, and
H = (V + L)/ |V + L|.
The t er m T is t he Fr esnel t r ansmission t er m t hat d et er mines t he
amount of light to be transmitted for a particular wavelength. Assuming a
289
V.9 MORE SHADOW ATTENUATION FOR RAY TRANSPARENT OR TRANSLUCENT OBJECTS
GRAPHICS GEMS II Edit ed by JAMES ARVO 289
conser vat ion of energy, t he sum of t he int ensit y of light reect ed and t he
int ensit y of light t r ansmit t ed must equal t he int ensit y of light incid ent on
t he sur face int er face, which implies t hat T = 1 F.
Since t he Fresnel for mulas are well-d ened only for d ielect r ic med ia,
t he values of n
c
+ ik
0
for cond uct ing med ia must be conver t ed t o t he
geomet r ic ind ex of refr act ion, n. Gener at ing t he refr act ed r ay at a sur face
int er sect ion also requires t he geomet r ic ind ex of refr act ion. An approxi-
mat ion can be used t o d er ive t he geomet r ic ind ex of refr act ion, n, from
t he comp lex ind ex of refr act ion, n
c
+ ik
0
. At nor mal incid ence, t he
reect ance equat ion becomes:
F =
n
c
1 ( )
2
+ k
0
2
n
c
+ 1 ( )
2
+ k
0
2
,
where F is t he effect ive reect ance. Using t he geomet r ic ind ex of refr ac-
t ion in place of t he complex ind ex of refr act ion, t he reect ance equat ion
becomes:
F =

n 1 ( )
2
n + 1 ( )
2
.
Solving for n yield s:
n =

1 + F
1 F
.
By using t he effect ive reect ance calculat ed using t he complex ind ex of
refr act ion wit h t his last equat ion, an approximat ion t o t he geomet r ic
ind ex of refr act ion, n, has been d er ived (Cook, 1982; Cook and Tor r ance,
1982).
See also V.8 A Bod y Color Mod el: Absor pt ion of Light t hrough
Tr anslucent Med ia, Mar k E. Lee, Samuel P. Uselt on
VI
RADIOSITY
293
VI RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 293
RADIOSITY RADIOSITY RADIOSITY RADIOSITY RADIOSITY
The radiosit y ap p roach t o image synt hesis was int r od u ced by Gor al
et al. (1984) and is now well-est ablished as one of t he p r eeminent
algor it hms for creat ing high-qu alit y images. Based on id eas from an
engineer ing d iscipline known as r ad iat ive heat t r ansfer, t he r ad iosit y
approach has as it s cent r al t enet a fund ament al physical pr inciple t hat is
ignored almost ent irely by t echniques such as r ay t r acingt he pr inciple
of energy conser vat ion. Alt hou gh t he st and ard r ay-t r acing effect s of
specular reect ion and refr act ion are much more d ifcult t o incor por at e
int o t his approach, r ad iosit y excels at comput ing global light ing in which
energy is balanced among d iffuse sur faces t hat r ad iat e and re-r ad iat e light
ad innit um.
Init ially, r ad iosit y appeared t o be a r ad ical d epar t ure from r ay t r acing,
wit h t he shar p d ifference easily d iscer nible in t he images gener at ed by
each met hod . Ray t r acing boast ed cur ved shiny object s wit h br illiant
reect ions, while r ad iosit y images revealed soft shad ows and color bleed -
ing among at d iffuse sur facessubt le effect s t hat ad d realism t o images
of more commonplace set t ings, such as room int er ior s. Alt hough t he t wo
algor it hms seemed wor ld s apar t , cur rent research is br id ging t he gap t o
yield t echniques t hat enjoy t he st rengt hs of bot h. The view-d epend ent
nat ure of r ay t r acing makes it ind ispensable for precise reect ions, while
t he physically based nat ure of r ad iosit y makes it an id eal par ad igm for
physically accur at e simulat ions. The gems in t his Par t focus on d ifferent
aspect s of t he r ad iosit y approach. The r st gem d escr ibes how a r ad iosit y
VI VI VI VI VI
294
VI RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 294
rend erer can be implement ed based on familiar rend er ing soft ware. The
next t wo gems d escr ibe small improvement s t o relat ively well-known
r ad iosit y approaches. The last t wo gems focus on t he use of r ay t r acing
wit hin t he cont ext of r ad iosit y.
295
VI.1 IMPLEMENTING PROGRESSIVE RADIOSITY WITH USER-PROVIDED POLYGON DISPLAY ROUTINES
GRAPHICS GEMS II Edit ed by JAMES ARVO 295
VI.1 VI.1 VI.1 VI.1 VI.1
I II IIMPLEMENTING PROGRESSIVE MPLEMENTING PROGRESSIVE MPLEMENTING PROGRESSIVE MPLEMENTING PROGRESSIVE MPLEMENTING PROGRESSIVE
R RR RRADIOSITY WITH ADIOSITY WITH ADIOSITY WITH ADIOSITY WITH ADIOSITY WITH
U UU UUSER-PROVIDED POLYGON SER-PROVIDED POLYGON SER-PROVIDED POLYGON SER-PROVIDED POLYGON SER-PROVIDED POLYGON
D DD DDISPLAY ROUTINES ISPLAY ROUTINES ISPLAY ROUTINES ISPLAY ROUTINES ISPLAY ROUTINES
Shenchang Eric Chen
Apple Comput er, Inc.
Cupert ino, Calif ornia
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Radiosit y has emerged in recent year s as a popular rend er ing t echnique.
The main ad vant age of r ad iosit y is it s capabilit y of simulat ing d iffuse
int er reect ion or so-called color bleed ing effect s. This ad vant age has
enabled r ad iosit y images t o be highly realist ic, since most sur faces in t he
real wor ld are d iffuse. Anot her char act er ist ic of t ypical d iffuse r ad iosit y is
t hat t he rend er ing is view-ind epend ent : Int ensit ies are comput ed in wor ld
sp ace on some d iscret e su r face p oint s. This allows fast viewing of
r ad iosit y result s from d ifferent posit ions.
While a nave r ay t r acer can be implement ed fair ly easily and com-
pact ly (as in t he case of Paul Heckber t , who has a r ay t r acer pr int ed on
his business card ), implement ing a r ad iosit y progr am gener ally is re-
gard ed as an enor mous t ask. This is evid ent in t hat t here st ill is no public
d omain r ad iosit y cod e available, t o t he aut hor s knowled ge; yet if we
assume some t ools are available, a nave r ad iosit y rend erer act ually is
quit e simple t o implement .
The main comput at ion in r ad iosit y is t he comput at ion of form fact ors,
which are geomet r ical relat ionships bet ween sur faces (Gor al et al., 1984).
For m fact or s can be comput ed using a hemi-cube t echnique (Cohen and
Greenberg, 1985), which mainly involves hid d en sur face removal. There-
fore, if we assume some polygon d isplay t ools such as z buffer or r ay
cast ing are available, t hen implement ing a r ad iosit y progr am is ver y
simple. The availabilit y of such kind s of t ools gener ally is not a problem.
A number of polygon scan conver t er s and r ay t r acer s are published in
previous gems. Most gr aphics wor kst at ions now have z buffer met hod s
296
VI.1 IMPLEMENTING PROGRESSIVE RADIOSITY WITH USER-PROVIDED POLYGON DISPLAY ROUTINES
GRAPHICS GEMS II Edit ed by JAMES ARVO 296
implement ed in hard ware and may be used t o speed up t he hemi-cube
comput at ion.
In t he following sect ions, an implement at ion of progressive r ad iosit y
(Cohen et al., 1988) is present ed and it s C Implement at ion also is given
in Append ix 2. The implement at ion assumes all t he sur faces are id eal
d iffuse and have been t essellat ed int o pat ches (shoot er s of r ad iosit y) and
element s (receiver s of r ad iosit y). It d oes not per for m any ad apt ive subd i-
vision and ignores t he aliasing problems caused by t he hemi-cube met hod
as not ed by Baum et al. (1989) and Wallace et al. (1989). The progr am
is easily t r anspor t able t o d ifferent plat for ms because it assumes some
user-provid ed polygon d r awing rout ines are available. An ad d it ional ad -
vant age of t his ap p roach is t hat it allows u ser s t o exp er iment wit h
d ifferent hid d en sur face algor it hms t o acceler at e t he hemi-cube comput a-
t ion, which may account for 90% of t he t ot al comput at ion.
Pr ogr essi ve Radi osi t y Pr ogr essi ve Radi osi t y Pr ogr essi ve Radi osi t y Pr ogr essi ve Radi osi t y Pr ogr essi ve Radi osi t y
Progressive r ad iosit y uses an it er at ive solut ion t o comput e t he result s.
Each it er at ion basically consist s of t he following st eps:
Find Shoot ing Pat ch: Fi n d t h e n ext sh oot i n g p a t ch t h a t h a s t h e
great est unshot energy (i.e., t he energy t o be d ist r ibut ed ). If t he unshot
energy is less t han a fr act ion of t he sum of t he init ially emit t ed energy,
t hen st op t he solut ion.
Comput e Form Fact ors: Pl a ce a h emi -cu be on t h e cen t er of t h e
shoot ing pat ch and or ient it t o t he pat chs nor mal d irect ion. Project ever y
element t o all ve faces of t he hemi-cube. Sum t he d elt a for m fact or s
associat ed wit h each hemi-cube pixel t o comput e for m fact or s from t he
shoot ing pat ch t o ever y element .
Dist ribut e Radiosit y: Dist r ibu t e t he u nshot r ad iosit y of t he shoot ing
pat ch t o ever y element .
Display Result s: Di sp l ay al l t h e el emen t s wi t h col or s d et er mi n ed
from t he element s r ad iosit y.
Figure 1 illust r at es t he process.
297
VI.1 IMPLEMENTING PROGRESSIVE RADIOSITY WITH USER-PROVIDED POLYGON DISPLAY ROUTINES
GRAPHICS GEMS II Edit ed by JAMES ARVO 297
Figure 1. Progressive r ad iosit y.
Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on
The progr am rad.c t akes an ar r ay of pat ches and element s as input and
per for ms rend er ing on t hem. The pat ch and element are t wo d ifferent
levels of subd ivision of a sur face. The pat ches act ually are sur face sample
point s t hat cont ain locat ions, nor mals, areas, sur face at t r ibut es, et c. The
shape of a pat ch is not need ed in our implement at ion. The pat ch subd ivi-
sion can be ver y coar se and u su ally is a fu nct ion of t he su r faces
r ad iosit y, size, and posit ion. Var ying pat ch subd ivision is equivalent t o
approximat ing an area light wit h d ifferent number s of point light s and has
a similar speed and qualit y t r ad e-off. Each pat ch is subd ivid ed fur t her
int o element s, which cont ain ad d it ional infor mat ion such as shapes and
pat ches t o which t hey belong. Since element s are used t o d isplay t he
result s, var ying element subd ivision is analogous t o var ying image resolu-
t ions in r ay t r acing.
This progr am makes use of t hree user-provid ed rout ines t o per for m
hemi-cube comput at ion and d isplay of result s:
BeginDraw: This funct ion should clear t he fr ame buffer wit h a back-
ground color and prepare it for d r awing. It also set s up a view t r ansfor-
mat ion t hat will be used by all t he subsequent d r awings of polygons.
DrawPolygon: Th is fu n ct ion sh ou ld t r an sfor m, clip , an d scan -con -
ver t a polygon int o a fr ame buffer, and should per for m hid d en sur face
removal. Each polygon is d r awn wit h a const ant color.
298
VI.1 IMPLEMENTING PROGRESSIVE RADIOSITY WITH USER-PROVIDED POLYGON DISPLAY ROUTINES
GRAPHICS GEMS II Edit ed by JAMES ARVO 298
EndDraw: The funct ion should guar ant ee all t he polygons are d r awn
t o t he fr ame buffer and t he cont ent of t he buffer is read y t o be accessed
by t he caller.
Not ice t hat t he preced ing r out ines also can be implement ed wit h a r ay
t r acer, which st ores polygons in a list when DrawPolygon is called and
st ar t s t r acing r ays when EndDraw is called .
Since t he d r awing rout ines are assumed t o per for m only at shad ing,
each polygon in t he image is shad ed wit h a const ant color comput ed from
t he element r ad iosit y. To gener at e smoot hly shad ed images, bilinear
int er polat ion of t he element r ad iosit ies can be used t o obt ain color s of t he
element ver t ices. Then Gour aud shad ing (1971) can be used t o d isplay
t he image.
A t est progr am room.c is includ ed as a d emonst r at ion. (See C Imple-
ment at ion in Append ix II.)
299
VI.2 A CUBIC TETRAHEDRAL ADAPTATION OF THE HEMI-CUBE ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 299
VI.2 VI.2 VI.2 VI.2 VI.2
A AA AA CUBIC TETRAHEDRAL CUBIC TETRAHEDRAL CUBIC TETRAHEDRAL CUBIC TETRAHEDRAL CUBIC TETRAHEDRAL
A AA AADAPTATION OF THE DAPTATION OF THE DAPTATION OF THE DAPTATION OF THE DAPTATION OF THE
H HH HHEMI-CUBE ALGORITHM EMI-CUBE ALGORITHM EMI-CUBE ALGORITHM EMI-CUBE ALGORITHM EMI-CUBE ALGORITHM
Jef f rey C. Beran-Koehn and Mark J. Pavicic
Nort h Dakot a St at e Universit y
Fargo, Nort h Dakot a
Th e hemi-cube algorit hm h a s become t h e most p op u l a r met h od of
calculat ing r ad iosit y solut ions for complex environment s cont aining hid -
d en sur faces and shad ows (Cohen and Greenberg, 1985). A cubic t et r a-
hed r al ad apt at ion of t his algor it hm increases per for mance by red ucing
t he number of project ion planes from ve t o t hree, while maint aining t he
simplicit y of t he required clipping and project ion oper at ions.
The hemi-cube algor it hm calculat es t he amount of light land ing on a
pat ch from ever y ot her pat ch by t r ansfor ming t he environment so t hat t he
receiving pat chs cent er is at t he or igin and it s nor mal coincid es wit h t he
posit ive z axis. An imaginar y cube is const ruct ed around t he cent er of t he
receiving pat ch. The upper half of t his cube provid es four half-faces and
one full face ont o which t he environment is project ed . Each of t hese faces
is d ivid ed int o square pixels at a given resolut ion. The hemi-cube is
illust r at ed in Fig.1.
Ever y pat ch in t he environment t hat is above, or int er sect s, t he z = 0
plane is clipped so t hat it lies wit hin only one of t he ve view volumes
d ened by t he planes: z = 0, z = x, z = x, z = y, z = y, x = y, and
x = y. These pat ches t hen are project ed ont o t he appropr iat e face of
t he cube by a per spect ive project ion and hid d en-sur face removal is d one
wit h a d ept h-buffer ing algor it hm.
A cubic t et r ahed ron may be const ruct ed by slicing a cube wit h a plane
t hat passes t hrough t hree of t he cubes ver t ices. Using a cube t hat is
id ent ical t o t he one d escr ibed before, select t he following ver t ices t o
d ene t he slicing plane: V
1
= (r, r, r), V
2
= (r, r, r), V
3
= (r, r, r).
The apex of t he cubic t et r ahed ron is at t he point A = (r, r, r), and t he
cen t er of t h e cu bi c t et r ah ed r on s base i s l ocat ed at t h e p oi n t C=
300
VI.2 A CUBIC TETRAHEDRAL ADAPTATION OF THE HEMI-CUBE ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 300
(r/ 3, r/ 3, r/ 3). To locat e t he cent er of t he cubic t et r ahed rons base at
t he or igin, t he cube is t r anslat ed r/ 3 unit s along t he x, y, and z axes
(i.e., V
i
= V
i
C, A = A C, and C = 0). Figure 2 illust r at es t his
cubic t et r ahed ron. The plane equat ion of t he base of t he cubic t et r a-
hed ron now is x + y = z. The equat ion of t he plane cont aining C, A,
and V
1
is z = y. The plane cont aining C, A, and V
2
is d escr ibed by t he
equat ion z = x, while C, A, and V
3
d ene a plane whose equat ion is
x = y.
To use t his cubic t et r ahed r al approach, t he environment is t r ansfor med
so t he cent er of t he receiving pat ch is at t he or igin and t he pat chs nor mal
Figur e 1. The Hemi-cube.
Figur e 2. The cubic t et r ahed ron.
301
VI.2 A CUBIC TETRAHEDRAL ADAPTATION OF THE HEMI-CUBE ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 301
coincid es wit h t he vect or (1, 1, 1). An imaginar y cubic t et r ahed ron is
const r uct ed from a cube and t he plane cont aining t he receiving pat ch as
d escr ibed previously. This d enes t hree faces ont o which t he environ-
ment is t o be project ed . Ever y pat ch in t he environment t hat is above, or
int er sect s, t he x + y = z plane is clipped so t hat it lies wit hin only one
of t he t hree view volumes d ened by t he planes: x + y = z, z = y,
z = x, and x = y. Thus, t he cubic t et r ahed ron ret ains t he proper t y t hat
only simple compar isons are required t o d et er mine on which sid e of a
clipping plane any point lies. Each pat ch, locat ed above t he x + y = z
plane, is project ed ont o t he appropr iat e face of t he cubic t et r ahed ron by a
per spect ive project ion. The project ions for t he cubic t et r ahed ron and t he
hemi-cube d iffer only in t he d ist ance bet ween t he cent er of project ion and
t he p r oject ion p lane. As is t he case wit h t he hemi-cu be algor it hm,
hid d en-sur face removal is d one wit h a d ept h-buffer ing algor it hm.
The r st ad vant age of t he cubic t et r ahed r al ad apt at ion is t he fact t hat
each of t he faces is id ent ical. The hemi-cube uses four half-faces and one
full face of a cube, t hus requir ing t he t op face t o be t reat ed d ifferent ly
t han t he four sid e faces.
The cubic t et r ahed r al ad apt at ion also increases t he per for mance of t he
hemi-cube algor it hm. The cubic t et r ahed ron par t it ions t he environment
into three view volumes instead of ve. This coarser partitioning results in
fewer pat ches t hat must be clipped . This is an impor t ant result because
for each pat ch t hat is clipped , not only must t he int er sect ion of t he pat ch
wit h an ed ge of a view volume be calculat ed , but anot her pat ch is creat ed .
This new pat ch creat es ad d it ional wor k in t he project ion and hid d en-
sur face por t ions of t he algor it hm. The red uct ion in t he clipping, and ,
t herefore, in t he number of project ion and hid d en-sur face calculat ions, is
achieved while maint aining t he ease wit h which t hese oper at ions are
per for med .
The cubic t et r ahed r al ad apt at ion samples t he environment wit h half as
many pixels as would be used by t he hemi-cube algor it hm at a given
resolut ion. The four half-faces and one full face of t he hemi-cube sample
t he environment wit h t hree t imes t he number of pixels locat ed on one full
face of t he cube. The t hree faces of t he cubic t et r ahed ron sample t he
environment wit h only one and one-half t imes t he number of pixels
locat ed on one full face of t he cube. Therefore, t o sample t he environ-
ment wit h t he same number of pixels as t he hemi-cube, t he number of
pixels on t he cubic t et r ahed ron must be d oubled . This d oes not affect
302
VI.2 A CUBIC TETRAHEDRAL ADAPTATION OF THE HEMI-CUBE ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 302
per for mance, since t he number of pixels used for hid d en-sur face removal
and for m-fact or calculat ions now is id ent ical for bot h geomet r ies. The
d oubling, however, d oes slight ly increase t he st or age requir ement s of t he
d elt a for m-fact or look-up t able (Cohen and Greenberg, 1985). Let n be
t he number of pixels on one full face of t he cube. Then t he hemi-cubes
look-up t able cont ains n/ 8 + n/ 4, or 3n/ 8 values. Doubling t he number
of pixels on t he cubic t et r ahed ron result s in a look-up t able cont aining
n/ 2 values.
The cubic t et r ahed ron provid es an at t r act ive ad apt at ion of t he hemi-
cube algor it hm. It replaces t he ve faces of t he hemi-cube wit h t hree
symmet r ical faces. These faces are const ruct ed in such a manner as t o
maint ain t he efciency of t he clipping and project ion oper at ions. The
number of pat ches t hat are clipped is red uced , result ing in a red uct ion of
t he number of project ion and hid d en-sur face calculat ions per for med . This
per for mance increase is accompanied by only a slight increase in t he
amount of st or age required for t he d elt a for m-fact or look-up t able.
303
VI.3 FASTER VERTEX RADIOSITY UPDATE
GRAPHICS GEMS II Edit ed by JAMES ARVO 303
VI.3 VI.3 VI.3 VI.3 VI.3
F FF FFAST VERTEX RADIOSITY AST VERTEX RADIOSITY AST VERTEX RADIOSITY AST VERTEX RADIOSITY AST VERTEX RADIOSITY
U UU UUPDATE PDATE PDATE PDATE PDATE
Filippo Tampieri
Cornell Universit y
It haca, New York
Here is a simple met hod for fast progressive r enement r ad iosit y using
r ay-t r aced for m fact or s t hat , at each it er at ion of t he algor it hm, red uces
t he number of sur faces whose r ad iosit y need s t o be upd at ed .
At each it er at ion of progressive renement r ad iosit y, a shoot ing pat ch
is select ed and t he r ad iosit y of all t he mesh ver t ices in t he environment
must be upd at ed wit h it s cont r ibut ion. A simple approach consist s of
t r aver sing sequent ially a list of t hese ver t ices and upd at ing each one in
t ur n. The upd at e involves t r acing one or more shad ow r ays t o d et er mine
occlu sions for t he comp u t at ion of t he ver t ex-t o-shoot ing p at ch for m
fact or and can be pret t y expensive. If t he ver t ex is behind t he shoot ing
pat ch, t hough, t he ent ire comput at ion can be avoid ed , since, in t his case,
t here can be no energy reaching t he ver t ex. Let t he ver t ex locat ion be
d enot ed by P and t he plane on which t he shoot ing pat ch lies be d enot ed
by N and d, where N = [a, b, c] and ax + by + cz + d = 0 is t he
equat ion of t he plane, t hen:
i f N P + d 0 then
vert ex P is behind t he shoot ing pat ch
el se
vert ex P is in front of t he shoot ing pat ch
Thus, a simple d ot prod uct is sufcient t o cull a ver t ex out of consid er a-
t ion. The cu lling op er at ion, t hou gh, can be mu ch more effect ive at
speed ing up t he upd at e pass if applied t o a group of mesh ver t ices all at
once.
304
VI.3 FASTER VERTEX RADIOSITY UPDATE
GRAPHICS GEMS II Edit ed by JAMES ARVO 304
If t he environment is viewed as consist ing of a set of sur faces, mesh
ver t ices can be grouped accord ing t o which sur face t hey lie on. If t he
su r faces all are polygons, t hen each su r face can be cu lled easily by
t est ing it s cor ner s; if it s cor ner s all are behind t he shoot ing pat ch, t hen
none of it s mesh ver t ices can receive any energy and no fur t her wor k is
necessar y. However, if at least one cor ner is in front of t he shoot ing
pat ch, t hen all of it s mesh ver t ices must be processed , since some of
t hem might receive energy.
Bound ing boxes can be used t o d evelop a fast er and more gener al
met hod of d et er mining whet her a sur face is behind a shoot ing pat ch. If
t he sur face is enclosed in a bound ing box, t hen it can be culled out of
consid er at ion if it s bound ing box is behind t he shoot ing pat ch.
Here is an algor it hm t hat d et er mines whet her or not an axis-aligned
box is complet ely behind a given plane, using only a few compar isons and
a single d ot prod uct . The id ea is as follows: Choose t he cor ner of t he box
t hat is in front of t he plane and t he fur t hest away from it , or t hat which
is t he closest t o t he plane if no cor ner lies in front of t he plane. (Ties are
broken ar bit r ar ily.) If t he chosen cor ner is behind t he plane, t hen all t he
ot her cor ner s must be behind t he plane as well, which implies t hat t he
bound ing box it self and it s cont ent s are complet ely behind t he plane and
t hu s can be cu lled safely ou t of consid er at ion. In Fig. 1, t he chosen
cor ner is circled for t he t hree most represent at ive cases.
The choice is mad e simply by select ing t hat cor ner whose x, y, and z
component s are t he largest when t he cor respond ing component of t he
plane nor mal is posit ive, and t he smallest when t he cor respond ing com-
ponent of t he plane nor mal is negat ive. (If t he component of t he plane
nor mal is zero, any choice will d o.)
Let t he axis-aligned box be d enot ed by it s minimum and maximum
cor ner s, C
min
and C
max
, and t he plane be d enot ed by N and d as before;
Figur e 1.
(a) (b) (c)
305
VI.3 FASTER VERTEX RADIOSITY UPDATE
GRAPHICS GEMS II Edit ed by JAMES ARVO 305
t hen:
1. for i i n xyz do
i f N
i
0. then
P
i
:= C
i
max
el se
P
i
:= C
i
min
;
2. i f N P + d 0. then
t he box is complet ely behind t he plane
el se
t he box is at least part ially in front of t he plane
St ep 1 chooses t he appropr iat e cor ner of t he bound ing box and st ep 2
checks whet her t he cor ner is behind t he plane of t he shoot ing pat ch. On
large sur faces and ne meshes, t his met hod may cull hund red s or even
t housand s of mesh ver t ices in a single oper at ion.
The id ea of using bound ing boxes can be car r ied even fur t her. If t he
sur faces in t he environment are organized in a hier archy of bound ing
boxes, t hen ent ire groups of sur faces are eliminat ed from consid er at ion
when t he bound ing box associat ed t o an int er ior nod e of t he hier archy is
found t o lie complet ely behind t he plane of t he shoot ing pat ch. The whole
environment now is u pd at ed by t r aver sing t he hier archy recu r sively,
st ar t ing from t he root , t est ing at each nod e whet her it s bound ing box is
complet ely behind t he shoot ing pat ch, and examining it s child ren only if
t hat is not t he case.
See also VI. 1 Imp l emen t i n g Pr ogr essi ve Ra d i osi t y wi t h User -
Provid ed Polygon Display Rout ines, Shenchang Er ic Chen
306
VI.4 RADIOSITY VIA RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 306
VI.4 VI.4 VI.4 VI.4 VI.4
R RR RRADIOSITY VIA RAY TRACING ADIOSITY VIA RAY TRACING ADIOSITY VIA RAY TRACING ADIOSITY VIA RAY TRACING ADIOSITY VIA RAY TRACING
Pet er Shirley
Indiana Universit y
Bloomingt on, Indiana
In a r ad iosit y progr am, t he ind irect light ing t hat cont r ibut es t o sur face
color is calculat ed explicit ly. This is used in place of t he less accur at e
ambient t er m usually used in comput er gr aphics. Rad iosit y solut ions are
applicable t o scenes t hat are mad e up of diffuse reect or s (i.e., mat t e
object s). Recent ly, progressive renement r ad iosit y has become p op u -
lar. In progressive renement solut ions, power is t r anspor t ed wit hin t he
environment unt il we have an est imat e for t he power reect ed from each
sur face. If r ay t r acing is used t o t r anspor t t he power, a r ad iosit y progr am
is not hard t o wr it e.
Pr ogr essi ve Re nement Radi osi t y Pr ogr essi ve Re nement Radi osi t y Pr ogr essi ve Re nement Radi osi t y Pr ogr essi ve Re nement Radi osi t y Pr ogr essi ve Re nement Radi osi t y
The simplest way t o implement (and und er st and ) a r ad iosit y progr am is
as a brut e force physical simulat ion. Assume t hat t he ent ire environment
is d ivid ed int o N sur face zones z
i
.
For each zone, we should nd t he aver age reect ivit y, R
i
. The un-
knowns we would like t o solve for are t he r ad iances L
i
of all z
i
. Rad iance
can be t hought of as sur face br ight ness, and somet imes is called int ensit y
in t he comp u t er gr ap hics lit er at u re. For ou r p u r p oses, we can u se
radiance and bright ness int erchangeably.
In a physical simulat ion, it is easier t o d eal wit h power t han r ad iance.
Power simply is t he energy per unit t ime. For example, a light bulb t hat
emit s 60 joules per second is a 60-wat t bulb. Given t he power
i
leaving
z
i
, we can nd t he r ad iance L
i
:

L
i

i
A
i
,
where A
i
is t he sur face area of z
i
.
307
VI.4 RADIOSITY VIA RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 307
Assume t he power emit t ed from z
i
is known t o be
i
emit
This quant it y
will be zero for zones t hat ar e not luminaries (light sou rces). In a
progressive renement solut ion, we send t he power from t he luminaires
t o all ot her zones. We t hen have t hese zones send t he power t hey reect .
This process is repeat ed unt il most of t he power is absor bed . To accom-
plish this, we need to dene
i
unsent
, the accumulated power of z
i
that has
not yet been propagat ed t o ot her zones. We now can out line a simple
progr am t o est imat e L
i
for ever y sur face:
for i = 1 t o N

i
unsent
=
i
=
i
emit
for b = 1 t o B
for i = 1 t o N
Send
i
unsent
t o ot her sur faces

i
unsent
= 0
for i = 1 t o N
L
i
=
i
/ (A
i
)
This algor it hm loops t hrough all t he zones B t imes. B can be t hought of
as t he approximat e number of int er reect ions we mod el (we act ually
mod el approximat ely 1.5B int er reect ions), and values somewhere be-
t ween 4 and 20 should prod uce good result s. Each zone send s it s unsent
power once t o t he ot her zones in each it er at ion of t he loop. The d ifcult
p ar t of t he algor it hm is t he line Send
i
u nsent
t o ot her surfaces. Here,
power is sent t o many z
j
, r aising t he values for
j
and
j
unsent
, This can
be accomplished using project ion t echniques or r ay t r acing. In t he next
sect ion, t he easiest r ay t r acing met hod is d escr ibed .
Sendi ng t he Power wi t h Rays Sendi ng t he Power wi t h Rays Sendi ng t he Power wi t h Rays Sendi ng t he Power wi t h Rays Sendi ng t he Power wi t h Rays
When t he zone z
i
send s it s accumulat ed power out int o t he environment ,
the quantity sent in a particular direction is proportional to cos , where
is t he angle bet ween t he d irect ion and t he sur face nor mal of z
i
. We could
calculat e explicit ly t he power t r ansfer red from z
i
t o ever y z
j
based on
t he geomet r ical relat ionship of z
i
and z
j
. The fr act ion of power leaving
z
i
t hat d ir ect ly get s t o z
j
is called t he for m fact or F
ij
. Inst ead , we
implicit ly can est imat e F
ij
by using a Mont e Car lo simulat ion.
Because we know z
i
reect s/ emit s power in a cosine d ist r ibut ion, we
could d ivid e
i
unsent
int o r packet s, and send each packet in a r and om
308
VI.4 RADIOSITY VIA RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 308
d irect ion. These d irect ions shou ld have a cosine d ensit y, r at her t han
being unifor mly r and om. The power car r ied in each packet would be
t r ansfer red fully t o what ever zone, z
j
, is hit by t he packet (seen in t he
d irect ion t he packet is sent ). In pseud o-cod e, t his id ea becomes:
=
i
unsent
/ r
for k = 1 t o r
Choose a r and om d irect ion (, )
Choose a r and om point p on z
i
Find zone z
k
hit by r ay from p in d irect ion (, )

k
=
k
+ R
k

k
unsent
=
k
unsent
+ R
k

One way t o t hink of t his is as a simulat ion where r phot ons are sent
from z
i
. There are t wo d et ails t hat need t o be eshed out . The r st is how
many r ays r we should send . We cer t ainly should not use t he same r for
each sur face, because we would r at her send many r ays from a br ight
zone, and no rays from a zone with no unsent power. A good method is to
make r d irect ly propor t ional t o
i
unsent
, so a zone wit h t wice as much
power as anot her zone will send t wice as many r ays.
We also need a way t o choose r and om (, ) wit h t he r ight d ist r ibut ion:
The probabilit y of a par t icular d irect ion is propor t ional t o cos . For a
par t icular r ay, we choose a r and om pair (
1
,
2
) unifor mly from t he unit
square (0
j
< 1). We get t he d irect ion (, ) by applying t he t r ansfor-
mat ions = arccos (

1
1
), and = 2
2
. Be sure t o r emember t hat
(, ) are t he coord inat es relat ive t o t he sur face nor mal, and not t he
global Car t esian axes.
Ext ensi ons Ext ensi ons Ext ensi ons Ext ensi ons Ext ensi ons
There are a few t hings we need t o ad d t o our solut ion for it t o be useful.
Most impor t ant ly, we need t o smoot h our solut ion. If we simply at -
shad ed ever y z
i
using L
i
, t hen we would end up wit h obvious zone
bound ar ies, giving a quilt ing effect . The st and ard solut ion is t o int er po-
lat e zone color s t o t he zone ver t ices, and t hen Gour aud shad e each zone.
Because we want color t o var y cont inuously across an object (e.g., t he
309
VI.4 RADIOSITY VIA RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 309
wall in a room), ver t ices shared by ad jacent zones should have exact ly
one color. The simplest way t o nd ver t ex color s t hat meet t his const r aint
is t o set each ver t ex color t o t he aver age of L
i
for all z
i
t hat have t hat
ver t ex on t heir bound ar ies.
Anot her basic t hing we need t o ad d is color. This is d one by represent -
ing t he power, reect ance, and r ad iance var iables as set s of values. If an
RGB color mod el is used , each var iable would have a red , a green, and a
blue component . If we want t o use a more sophist icat ed color mod el, we
can represent each var iable at a set of specied wavelengt hs.
Non-d iffuse luminaires can be ad d ed by d ist r ibut ing t he r ays r st sent
from luminair es accord ing t o some d ensit y ot her t han t he cosine d ensit y.
For example, we could make t he d ensit y propor t ional t o cos
n
, where n
is a user-d ened phong exponent . For t his, we use t he t r ansfor mat ions
= arccos((1
1
)
l/ (n + l)
), = 2
2
.
If we want t o make images of complex scenes, we will want t o use
t ext ure mapping. We can t hink of t his as allowing each zone t o have a
reect ivit y t hat var ies across it s sur face; so each z
i
will have a reect ivit y
fu nct ion R(p) d ened for all p oint s p on t he zone. The aver age re-
ect ance, R
i
, can be found by int egr at ing R(p) over t he sur face of z
i
and d ivid ing by A
i
. If we use Mont e Car lo int egr at ion, t his amount s t o
aver aging R(p
j
) for sever al point s p
j
r and omly t aken from t he sur face of
z
i
. We can p roceed wit h t he st and ar d r ad iosit y solu t ion. When we
nor mally would d isplay a point p on a zone z
i
as color L(p) (found
from Gour aud shad ing), inst ead use R(p)L(p)/ R
i
. In effect , t his t r ans-
for ms t he r ad iosit y solut ion t o one of incoming light r at her t han reect ed
light , which we t hen can mult iply by reect ance.
Mir ror s can be ad d ed t o our solut ion by let t ing t he power car r ying r ays
reect from t hem wit h appropr iat e loss in power (at t enuat ion by t he
reect ivit y of t he mir r or ). These mir ror s will not have any st ored color (as
t heir color var ies d irect ionally), but t hey can be rend ered wit h a st and ard
r ay t r acing progr am.
Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng Fur t her Readi ng
The r st r ad iosit y paper, which gives insight int o t he or iginal t hinking
behind r ad iosit y met hod s, is by Gor al et al. (1984). The hemi-cube, an
alt er nat ive t o r ay t r acing, and t he int er polat ion t o zone ver t ices is d is-
310
VI.4 RADIOSITY VIA RAY TRACING
GRAPHICS GEMS II Edit ed by JAMES ARVO 310
cu ssed by Cohen and Greenber g (1985). The p r ogr essive renement
approach is d escr ibed by Cohen et al. (1988). Ray t r acing for r ad iosit y is
d iscu ssed by Malley (1988), Sillion and Pu ech (1989), Wallace et al.
(1989), and Airey et al. (1990). More infor mat ion on Gour aud shad ing
and mod eling t echniques for polygons wit h shared ver t ices can be found
in Foley et al. (1990). Rad iosit y t echniques for heat t r ansfer, as well as
much of t he und er lying physics, can be found in t he book by Siegel and
Howell (1981).
See also VI. 1 Imp l emen t i n g Pr ogr essi ve Ra d i osi t y wi t h User -
Provid ed Polygon Display Rout ines, Shenchang Er ic Chen
311
VI.5 DETECTION OF SHADOW BOUNDARIES FOR ADAPTIVE MESHING IN RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 311
VI.5 VI.5 VI.5 VI.5 VI.5
D DD DDETECTION OF SHADOW ETECTION OF SHADOW ETECTION OF SHADOW ETECTION OF SHADOW ETECTION OF SHADOW
B BB BBOUNDARIES FOR ADAPTIVE OUNDARIES FOR ADAPTIVE OUNDARIES FOR ADAPTIVE OUNDARIES FOR ADAPTIVE OUNDARIES FOR ADAPTIVE
M MM MMESHING IN RADIOSITY ESHING IN RADIOSITY ESHING IN RADIOSITY ESHING IN RADIOSITY ESHING IN RADIOSITY
Franois Sillion
Cornell Universit y
It haca, New York
Backgr ound Backgr ound Backgr ound Backgr ound Backgr ound
Rad iosit y algor it hms at t empt t o comput e t he global int er reect ion of light
in an environment composed of d iffuse sur faces. Most implement at ions of
t he r ad iosit y approach break t he sur faces in a scene int o pat ches in a
meshing st age, and t hese pat ches are used as second ar y illuminat or s in
t he cour se of t he solut ion. Rad iosit y t ext ures also have been used t o
encod e t he illuminat ion infor mat ion wit hout complicat ing t he geomet r ical
d escr ipt ion (Heckber t , 1990).
The r ad iosit y (d iffused int ensit y) across a pat ch t ypically is int er polat ed
bilinear ly from r ad iosit ies at t he ver t ices, which means t hat t he accur acy
of t he illuminat ion on a sur face is inuenced d irect ly by t he size of t he
mesh element s (or t he t ext ure resolut ion). Typically, we would like t o
concent r at e smaller element s in t he regions of shar p int ensit y var iat ions,
such as shad ow bound ar ies, while limit ing t he subd ivision of sur faces
wit h gent le illuminat ion var iat ions.
We p l ace ou r sel ves i n t h e con t ext of progressive radiosit y, wh er e
successive st eps of t he solut ion can be d escr ibed as shoot ing light from a
select ed pat ch. Since we would like our mesh (or t ext ure) t o d epend on
illuminat ion, we have t o base our subd ivision cr it er ion on t he result s of
t he simulat ion. This means t hat aft er each shoot ing st ep, we want t o
d ecid e which areas t o subd ivid e, based on t he result s of t he cur rent shot .
312
VI.5 DETECTION OF SHADOW BOUNDARIES FOR ADAPTIVE MESHING IN RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 312
Figure 2. Ray-t r aced for m fact or s.
Figure 1. Two cases wit h t he same d ifference in ver t ex int ensit ies. Only t he one
wit h a shad ow bound ar y should require subd ivision, since it cannot be rend ered
by bilinear int er polat ion.
313
VI.5 DETECTION OF SHADOW BOUNDARIES FOR ADAPTIVE MESHING IN RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 313
Unfor t unat ely, it is d ifcult t o base a d ecision on int ensit y compar isons
alone (Fig.1). What we really want t o d et ect are cases where bilinear
int er polat ion will not capt ure t he real int ensit y var iat ions.
The id ea p resent ed her e is equ ally ap p licable t o meshed and t ex-
t ured environment s. We show t hat , using r ay cast ing t o comput e area-t o-
d ifferent ial-area for m fact or s as explained by Wallace et al. (1989), it is
easy, in fact , t o d et ect t rue shad ow bound ar ies, by keeping t r ack of t he
visibilit y of t he shoot ing pat ch at each receiving ver t ex. This infor mat ion
t hen can be used in t he subd ivision cr it er ion.
Obt ai ni ng a Vi si bi l i t y Index Obt ai ni ng a Vi si bi l i t y Index Obt ai ni ng a Vi si bi l i t y Index Obt ai ni ng a Vi si bi l i t y Index Obt ai ni ng a Vi si bi l i t y Index
When using r ay cast ing t o comput e for m fact or s, a shoot ing pat ch is
select ed , and each ver t ex in t he environment mesh is visit ed in t ur n. At
each ver t ex, t he shoot ing pat ch is sampled at one or sever al locat ions (as
a var iet y of sampling algor it hms can be implement ed ), and for each
sample point , a r ay is cast t o d et er mine pot ent ial occlusion. Each sample
point has an area associat ed wit h it , and a delt a form fact or is comput ed
by approximat ing t he region around t he sample point wit h a d isk of t he
same ar ea (Fi g. 2). An area-t o-different ial-area for m fact or (Wal l ace
et al., 1989) t hen is comput ed as an area-weight ed aver age of t he d elt a
for m fact or s.
Suppose now t hat we associat e a visibilit y value t o each r ay; t hat is,
0.0 if t he sample point is obst ruct ed from t he ver t ex, 1.0 ot her wise. We
t hen can comp u t e t he same area-weight ed aver age of t his visibilit y
var iable, and obt ain a pat ch visibilit y index t hat can be st ored wit h t he
ver t ex. Dep end ing on t he amou nt of st or age t hat one is willing t o
allocat e, t his can be as simple as a 1 bit value, or a more precise quant it y.
Subdi vi si on Cr i t er i a Subdi vi si on Cr i t er i a Subdi vi si on Cr i t er i a Subdi vi si on Cr i t er i a Subdi vi si on Cr i t er i a
Aft er a complet e r ad iosit y shot t hat is, when all ver t ices have been
visit ed is t he t ime t o examine t he cu r rent mesh or t ext u re, and t o
314
VI.5 DETECTION OF SHADOW BOUNDARIES FOR ADAPTIVE MESHING IN RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 314
d ecid e whet her t o subd ivid e fur t her. Each ed ge of t he mesh is consid ered
in t ur n, and t he chosen subd ivision cr it er ion is applied t o d ecid e of t hat
ed ge need s t o be split . If yes, t he ed ge and t he neighbor ing mesh
element s are split , and r ad iosit y is shot from t he shoot ing pat ch t o all
newly creat ed ver t ices. The same cr it er ion t hen can be applied recur sively
t o t he newly creat ed ed ges.
As was shown in Fig. 1, t he d ifference in int ensit ies at t he end point s of
an ed ge is not relevant as a cr it er ion: It would require a low t hreshold t o
d et ect faint (but impor t ant for t he pict ure) shad ow bound ar ies, which
would result in unnecessar y subd ivision in open areas.
We ad vocat e t he use of d ifferent t hreshold s for ed ges t hat cross or d o
not cross a shad ow bound ar y: Using t he visibilit y var iable t hat was just
d escr ibed , shad ow bou nd ar ies are id ent ified t r ivially, and t he lower
cr it er ion can be used . When no shad ow bound ar y is crossed , a d ifferent
cr it er ion can be used ; for example, based on t he act ual 3D int ensit y
gr ad ient . It is possible t hen t o t r igger ad apt ive su bd ivision on faint
sh ad ow bou n d ar ies, wit h ou t su bd ivid in g all t h e open areas on t h e
sur faces
The algor it hm can be summar ized as:
Select shoot ing pat ch
For each ver t ex
-for each sample point on t he pat ch
use your favorit e sampling met hod
comput e d elt a for m fact or
comput e visibilit y 1 or 0
-aver age (area weight ed ) for m fact or
-aver age (area weight ed ) visibilit y
End for
For each ed ge
If visibilit y of end point s are d ifferent
Then
apply shad ow bound ar y cr it er ion.
El se
apply nor mal cr it er ion.
Subd ivid e or not accord ing t o cr it er ion
End For
315
VI.5 DETECTION OF SHADOW BOUNDARIES FOR ADAPTIVE MESHING IN RADIOSITY
GRAPHICS GEMS II Edit ed by JAMES ARVO 315
See also VI. 1 Imp l emen t i n g Pr ogr essi ve Ra d i osi t y wi t h User -
Pr ovid ed Polygon Disp lay Rou t ines, Shenchang Er ic Chen; VI.4
Rad iosit y via Ray Tr acing, Pet er Shir ley
VII
MATRIX
TECHNIQUES
319
VII MATRIX TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 319
M MM MMATRIX ATRIX ATRIX ATRIX ATRIX
T TT TTECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES
The mat hemat ical found at ion and pred ominant language of comput er
gr aphics come from linear algebr a, and perhaps t he most fund ament al
element of t his vocabular y is t he mat r ix. Vir t ually ever y gr aphics applica-
t ion rest s at some level upon linear t r ansfor mat ions in screen coord i-
n at es, wor ld coor d in at es, or homogeneous coor d in at es, exp r essed as
2 2, 3 3, and 4 4 mat r ices. Oper at ions involving t hese mat r ices
are spr inkled liber ally t hroughout ever y manner of gr aphics progr am,
from image processing t o r ay t r acing. Their ut ilit y is mad e clear by t he
prepond er ance of hard ware gr aphics d evices d esigned t o acceler at e ma-
t r ix t r ansfor mat ions, as well as by mat hemat ical exposit ions in which t hey
provid e concise not at ion. The gems of t his Par t are d evot ed t o const ruct -
ing, d ecomposing, represent ing, and oper at ing on mat r ices.
VII VII VII VII VII
320
VII.1 DECOMPOSING A MATRIX INTO SIMPLE TRANSFORMATIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 320
VII.1 VII.1 VII.1 VII.1 VII.1
D DD DDECOMPOSING ECOMPOSING ECOMPOSING ECOMPOSING ECOMPOSING
A AA AA MATRIX INTO SIMPLE MATRIX INTO SIMPLE MATRIX INTO SIMPLE MATRIX INTO SIMPLE MATRIX INTO SIMPLE
T TT TTRANSFORMATIONS RANSFORMATIONS RANSFORMATIONS RANSFORMATIONS RANSFORMATIONS
Spencer W. Thomas
Universit y of Michigan
Ann Arbor, Michigan
Somet imes, it is u sefu l t o be able t o ext r act a sequ ence of simple
t r ansfor mat ions (scale, rot at e, et c.) t hat will reprod uce a given t r ansfor-
mat ion mat r ix. This gem provid es a way t o d o t hat . In par t icular, given
(almost
1
) any 4 4 t r ansfor mat ion mat r ix M, it will comput e t he argu-
ment s t o t he following sequence of t r ansfor mat ions, such t hat concat enat -
ing t he t r ansfor mat ions will reprod uce t he or iginal mat r ix (t o wit hin a
homogeneous scale fact or ):
Scale(s
x
, s
y
, s
z
)Shear
2
xy
Shear
xz
Shear
yz
Rot at e
x
Rot at e
y
Rot at e
z
Tr anslat e(t
x
, t
y
, t
z
)
Per spect ive(p
x
, p
y
, p
z
, p
w
)
This rout ine has been used for t asks such as removing t he shear s from a
rot at ion mat r ix, for feed ing an ar bit r ar y t r ansfor mat ion t o a gr aphics
syst em t hat only underst ands a par t icular sequence of t r ansfor mat ions
(which is par t icular ly useful when d ealing wit h rot at ions), or for any ot her
applicat ion in which you want just par t of t he t r ansfor mat ion sequence.
1
The only const r aint is t hat t he prod uct of t he [4, 4] element wit h t he d et er minant
of t he upper left 3 x 3 component of t he mat r ix be nonzero.
2
Shear
xy
shear s t he x coord inat e as t he y coord inat e changes. The mat r ix cor respond ing
t o t his t r ansfor mat ion is

1 0 0
s
xy
1 0
0 0 1

]
]
]
]
]

321
VII.1 DECOMPOSING A MATRIX INTO SIMPLE TRANSFORMATIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 321
The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm The Al gor i t hm
The algor it hm wor ks by undoing t he t r ansfor mat ion sequence in rever se
ord er. It r st d et er mines per spect ive element s t hat , when removed from
t he mat r ix, will leave t he last column (t he perspect ive part it ion) as (0, 0, 0,
1)
T
. Th en i t ext r act s t h e t r an sl at i on s. Th i s l eaves a 3 3 mat r i x
compr ising t he scales, shear s, and rot at ions. It is d ecomposed from t he
left , ext r act ing r st t he scaling fact or s and t hen t he shear ing component s,
leaving a pure rot at ion mat r ix. This is broken d own int o t hree consecut ive
rot at ions.
Ext r act ing t he p er sp ect ive comp onent s is t he messiest p ar t . Essen-
t ially, we need t o solve t he mat r ix equat ion:
=
which red uces t o:


M
1, 4
M
2, 4
M
3, 4
M
4, 4

]
]
]
]
]
]

M
1,1
M
1,2
M
1, 3
0
M
2,1
M
2,2
M
2, 3
0
M
3,1
M
3,2
M
3, 3
0
M
4,1
M
4, 2
M
4, 3
1

]
]
]
]
]
]
p
x
p
y
p
z
p
w

]
]
]
]
]
]

Assuming that the upper left 3 3 partition of M is not singular, this can

M
1,1
M
1,2
M
1, 3
M
1, 4
M
2,1
M
2,2
M
2, 3
M
2, 4
M
3,1
M
3,2
M
3, 3
M
3, 4
M
4,1
M
4, 2
M
4, 3
M
4, 4

]
]
]
]
]
]

M
1,1
M
1,2
M
1, 3
0
M
2,1
M
2,2
M
2, 3
0
M
3,1
M
3,2
M
3, 3
0
M
4,1
M
4, 2
M
4, 3
1

]
]
]
]
]
]
1 0 0 p
x
0 1 0 p
y
0 0 1 p
z
0 0 0 p
w

]
]
]
]
]
]
,
322
VII.1 DECOMPOSING A MATRIX INTO SIMPLE TRANSFORMATIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 322
be solved easily for p
x
, p
y
, p
z
, and p
w
Since some of t he lat er st eps will not
wor k if t his par t it ion is singular, t his is not a ser ious d efect .
The next st ep is t o ext r act t he t r anslat ions. This is t r ivial; we nd
t
x
= M
4,1
, t
y
= M
4,2
, and t
z
= M
4,3
. At t his point , we are left wit h a
3 3 mat r ix, M = M
1..3,1..3
.
The p rocess of nd ing t he scaling fact or s and shear p ar amet er s is
int er leaved . Fir st , nd s
x
= |M
1
|. Then, comput e an init ial value for t he
xy shear fact or, s
xy
, = M
1
, M
2
(This is t oo lar ge by t he y scaling
fact or.) The second row of t he mat r ix is mad e or t hogonal t o t he r st by
set t ing M
2
M
2
s
xy
M
1
. Then t he y scaling fact or, s
y
is t he lengt h of
t he mod ied second row. The second r ow is nor malized , and s
xy
is
d ivid ed by s
y
t o get it s nal value. The xz and yz shear fact or s are
comput ed as in t he preced ing, t he t hird row is mad e or t hogonal t o t he
r st t wo rows, t he z scaling fact or is comput ed , t he t hird row is nor mal-
ized , and t he xz and yz shear fact or s are rescaled .
The result ing mat r ix now is a pure rot at ion mat r ix, except t hat it might
st ill includ e a scale fact or of 1. If t he d et er minant of t he mat r ix is 1,
negat e t he mat r ix and all t hree scaling fact or s. Call t he result ing ma-
t r ix R.
Finally, we need t o d ecompose t he rot at ion mat r ix int o a sequence of
rot at ions about t he x, y, and z axes. If t he rot at ion angle about x is ,
t hat about y is , and t hat about z is , t hen t he composit e rot at ion is:
Thus, = arcsin(R
l,3
). If cos() 0, is d er ived easily from R
2,3
and R
3,3
,
and from R
1,2
and R
1,1
. If cos() = 0, t hen R red uces t o:

R
cos { cos { cos { sin { sin
[ ]
sin { sin { cos { sin { sin { sin {
cos { sin { +cos a { cos { sin { cos {
cos { sin { cos y
{
cos { sin { sin {
+sin { sin { sin { cos { cos { cos {

]
]
]
]
]
]
]
]


0 0 t1
sin t { cos t { 0
cos t { sin t { 0

]
]
]
]
]

323
VII.1 DECOMPOSING A MATRIX INTO SIMPLE TRANSFORMATIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 323
In t his case, we ar bit r ar ily set t o 0 and d er ive from R
2,1
and R
2,2
.
This nishes t he d ecomposit ion.
See also 7.2 Recover ing t he Dat a from t he Tr ansfor mat ion
Mat r ix, Ronald N. Gold man
324
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 324
VII.2 VII.2 VII.2 VII.2 VII.2
R RR RRECOVE ECOVE ECOVE ECOVE ECOVERlNG RlNG RlNG RlNG RlNG TH TH TH TH THE E E E E DATA DATA DATA DATA DATA
F FF FFROM THE TRANSFORMATION ROM THE TRANSFORMATION ROM THE TRANSFORMATION ROM THE TRANSFORMATION ROM THE TRANSFORMATION
M MM MMATRIX ATRIX ATRIX ATRIX ATRIX
Ronald N. Goldman
Rice Universit y
Houst on, Texas
In Graphics Gems (Mat r ices and Tr ansfor mat ions), we showed how t o
con st r u ct t h e 4 4 mat r ices for afn e an d p r oject ive t r an sfor ma-
t ionsr igid mot ion, scaling, and project ionswhich were d ened rela-
t ive t o some ar bit r ar y posit ions and or ient at ions d escr ibed by scalar s,
point s, and vect or s. In t his volume, we ad d ed t he 4 4 mat r ices for
shear and pseud o-per spect ive. Now we shall show how t o ret r ieve t he
d ening d at ascalar s, point s, and vect or sfrom t he 4 4 mat r ix when
we know t he t ype of t r ansfor mat ion represent ed by t he mat r ix. This is
useful, for example, when we concat enat e mat r ices for rot at ions around
d ifferent axes and t hen want t o know t he axis and angle of t he result ing
rot at ion.
Most of t he afne and project ive t r ansfor mat ions we d iscuss have xed
point s and xed d irect ionst hat is, values t hat are left invar iant by t he
t r ansfor mat ion. These xed values show up as eigenvect or s of t he t r ans-
for mat ion mat r ix. (In keeping wit h st and ard usage, we shall use t he t er m
eigenvect or even when t he xed value act ually is a point r at her t han a
vect or ). The d at a we seek t o ext r act oft en are simply eigenvect or s of t he
t r ansfor mat ion mat r ix.
Br iey, an eigenvect or v of a t r ansfor mat ion T is any non~ero vect or
such t hat
T(v) = I(v) =v,
where I is t he id ent it y t r ansfor mat ion. The scalar is called an eigenvalue
of T, and v is said t o be an eigenvect or of T cor respond ing t o t he
325
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 325
eigenvalue . The eigenvalues of T are t he root s of t he equat ion:
Det (T I) = 0
where I is t he id ent it y mat r ix of t he same size as t he mat r ix T. There are
well-known algor it hms for comput ing eigenvalues and eigenvect or s; read -
er s not familiar wit h t hese concept s should consult a st and ard linear
algebr a t ext .
We shall ad opt t he following not at ion:
M = 4 4 mat r ix,
M
33
= upper left 3 3 submat r ix of M,
M
34
= upper 3 4 submat r ix of M,
M
43
= left 4 3 submat r ix of M,
M
T
= t r anspose of M,
Tr ace (M
33
) =

k

M
33
(k, k) = M(1, 1) + M(2, 2) + M(3, 3).
Ar med wit h t hese concept s and t his not at ion, we are read y now t o
ext r act t he d at a from t he t r ansfor mat ion mat r ices. Not e t hat in many
cases, t he d at a is not unique. For example, if we d ene a plane by a point
and a unit vect or, t he point is not unique. Usually, t his point is an
eigenvect or of t he t r ansfor mat ion mat r ix relat ive t o some xed eigen-
value. If we d o not specify fur t her, t hen any such eigenvect or will suffice.
Oft en, t oo, we will require a unit eigenvect or cor respond ing t o some
eigenvalue . Such an eigenvect or is found read ily by comput ing any
eigenvect or v cor respond ing t o t he eigenvalue and t hen nor malizing it s
lengt h t o one, since, by linear it y, if v is an eigenvect or cor respond ing t o
t he eigenvalue , t hen cv also is an eigenvect or cor respond ing t o t he
eigenvalue .
326
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 326
Tr ansl at i on Tr ansl at i on Tr ansl at i on Tr ansl at i on Tr ansl at i on
Let
w = Tr anslat ion vect or
Given
T(w) = Tr anslat ion mat r ix
Comput e
w = Four t h r ow of T(w) = (0, 0, 0, 1) * T(w)
Rot at i on Rot at i on Rot at i on Rot at i on Rot at i on
Let
L = Axis line
w = Unit vect or par allel t o L
Q = Point on L
= Angle of rot at ion
Given
R = R(w, , Q) = Rot at ion mat r ix
Comput e
w = Unit eigenvect or of R
33
cor respond ing t o t he eigenvalue 1
Q = Any eigenvect or of R cor respond ing t o t he eigenvalue 1

cos
Trace R
33
( ) 1
( )
2

sin
R 1, 2 ( ) + cos 1 ( )w
1
w
2
{
w
3
327
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 327
Not ice t hat t he sign of sin d epend s on t he choice of w, since bot h w
and w are eigenvect or s of R
33
cor resp ond ing t o t he eigenvalu e 1.
Therefore, we cannot nd wit hout r st d ecid ing on t he choice of w.
Mi r r or Image Mi r r or Image Mi r r or Image Mi r r or Image Mi r r or Image
Let
S = Mir ror plane
n = Unit vect or per pend icular t o S
Q = Point on S
Given
M = M(n, Q) = Mir ror mat r ix
Comput e
n = Unit eigenvect or of M
33
cor resp ond ing to t he eigenvalu e 1
Q = Any eigenvect or of M cor respond ing t o t he eigenvalue + 1
Scal i ng Scal i ng Scal i ng Scal i ng Scal i ng
Let
Q = Scaling or igin
c = Scaling fact or
w = Scaling d irect ion
328
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 328
a. Unifor m scaling
Given
S = S(Q, c) = Scaling mat r ix
Comput e
c =

Trace S
33
( )
3
Q = Any eigenvect or of S cor respond ing t o t he eigenvalue 1
b. Nonunifor m scaling
Given
S = S(Q, c, w) = Scaling mat r ix
Comput e
c = Tr ace(S
33
) 2
w = Unit eigenvect or of S
33
cor respond ing t o t he eigenvalue c
Q = Any eigenvect or of S cor respond ing t o t he eigenvalue 1
Shear Shear Shear Shear Shear
Let
S = Shear ing plane
v = Unit vect or per pend icular t o S
Q = Point on S
w = Unit shear ing d irect ion vect or
= Shear ing angle
329
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 329
Given
S = Shear (Q, v, w, ) Shear ing mat r ix
Comput e
w
1
, w
2
= ind epend ent eigenvect or s of S
33
cor respond ing t o t he eigenvalue
1
t an
Q = any eigenvect or of S cor respond ing t o t he eigenvalue 1
Pr oj ect i on Pr oj ect i on Pr oj ect i on Pr oj ect i on Pr oj ect i on
Let
S = Image plane
n = Unit vect or per pend icular t o S
Q = Point on S
w = Unit vect or par allel t o project ion d irect ion
R = Per spect ive point
a. Or t hogonal project ion
Given
O = O proj(n, Q) = Pr oject ion mat r ix

w
v S I ( )
33
tan

v
w
1
w
2
w
1
w
2

v S I ( )
33
330
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 330
Comput e
n = Unit eigenvect or of O
33
cor respond ing t o t he eigenvalue 0
Q = Any eigenvect or of O cor respond ing t o t he eigenvalue 1
b. Par allel project ion
Given
P = P proj(n, Q, w) = Project ion mat r ix
Comput e
Q = Any eigenvect or of P cor respond ing t o t he eigenvalue 1
w = Unit eigenvect or of P
33
cor respond ing t o t he eigenvalue 0
n = Unit eigenvect or of

P
33
T
cor respond ing t o t he eigenvalue 0
c. Pseud o-per spect ive
Given
P = Pseud o(n, Q, R) = Pseud o-per spect ive mat r ix
Comput e
Q = Any eigenvect or of P not cor r espond ing t o t he eigenvalue 0
n
T
= Fir st t hree ent r ies of t he four t h column of P = P
34
* (0, 0, 0, 1 )
T
R
d . Per spect ive
Given
P = Per sp(n, Q, R) = Per spect ive mat r ix


0, 0, 0, 1 ( )P
43
+ Q n ( )n
{
Q n ( )

w I P ( )
33
T
{
w I P ( )
33
T
{
331
VII.2 RECOVERING THE DATA FROM THE TRANSFORMATION MATRIX
GRAPHICS GEMS II Edit ed by JAMES ARVO 331
Comput e
Q = Any eigenvect or of P not cor respond ing t o t he eigenvalue 0
n
T
= Fir st t hree ent r ies of t he four t h column of P = P
34
*(0, 0, 0 ,1)
T
R = eigenvect or of P cor respond ing t o t he eigenvalue 0
See also 7.1 Decomposing a Mat r ix int o Simple Tr ansfor ma-
t ions, Spencer W. Thomas

0, 0, 0, 1 ( )P
43
Q n ( )
332
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 332
VII.3 VII.3 VII.3 VII.3 VII.3
T TT TTRANSFORMATIONS AS RANSFORMATIONS AS RANSFORMATIONS AS RANSFORMATIONS AS RANSFORMATIONS AS
E EE EEXPO XPO XPO XPO XPONE NE NE NE NENTIALS NTIALS NTIALS NTIALS NTIALS
Ronald N. Goldman
Rice Universit y
Houst on, Texas
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Consid er t wo rot at ions around t he same axis. Concat enat ing t hese t wo
t r ansfor mat ions is equivalent t o ad d ing t he rot at ion angles; t hat is, t he
prod uct of t wo such rot at ion mat r ices is equivalent t o a single rot at ion
mat r ix where t he angles are ad d ed . Thus, mult iplicat ion of rot at ions is
like t he ad d ing of angles. There is anot her well-known funct ion in mat he-
mat ics wher e mu lt ip licat ion can be p er for med t hrou gh ad d it ion: t he
exponent ial. Mult iplying t wo exponent ials is equivalent t o ad d ing t heir
exponent s. Of cour se, t his obser vat ion is t he basis of st and ard logar it hms.
We shall show here t hat t his connect ion bet ween rot at ion and exponen-
t ials is more t han simply a coincid ence; ind eed , rot at ionsand many of
t he ot her nonsingular t r ansfor mat ions t hat we oft en encount er in com-
put er gr aphicsare exponent ial mat r ices.
The Exponent i al Mat r i x The Exponent i al Mat r i x The Exponent i al Mat r i x The Exponent i al Mat r i x The Exponent i al Mat r i x
Let M be a square mat r ix. We d ene t he mat r ix e
M
by t he usual innit e
ser ies for t he exponent ial. Let I d enot e t he id ent it y mat r ix. Then

e
M
I + M +
M
2
2!
+
M
3
3!
+L
k

M
k
k!

333
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 333
For any const ant c > 0, we d ene c
M
by
C
M
= e
ln(c)M
The mat r ix exponent ial funct ion behaves in many ways like t he ord i-
nar y scalar exponent ial funct ion. We list some of it s main proper t ies
below:
e
M
* e
-M
= I
e
M
* e
N
= e
M+N
whenever MN = NM
Re
M
R
-1
=
Det (e
M
) = e
Tr ace(M)
In t he last equat ion, Det is t he usual d et er minant funct ion and Tr ace is
t he sum of t he d iagonal t er ms of M; t hat is,
Not ice t hat by t he r st proper t y e
M
always is inver t ible, so only nonsingu-
lar mat r ices can be exponent ials.
Tensor Pr oduct and Cr oss Pr oduct Tensor Pr oduct and Cr oss Pr oduct Tensor Pr oduct and Cr oss Pr oduct Tensor Pr oduct and Cr oss Pr oduct Tensor Pr oduct and Cr oss Pr oduct
Before we can proceed fur t her, we need t o recall some not at ion t hat was
u sed in Graphics Gems (Mat r ices and Tr ansfor mat ions) and in t his
book (More Mat r ices and Tr ansfor mat ions) t o const ruct t he mat r ices
for t he t r ansfor mat ions rot at ion, mir ror image, scaling, and shear. Since
we are int erest ed pr imar ily in t r ansfor mat ions of 3-space, we conne
our selves t o 3 3 mat r ices.

Trace M ( )
k

M
kk


e
RMR
-1
334
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 334
a. Id ent it y
b. Tensor Prod uct
c. Cross Prod uct
d . Obser vat ions

u v w ( ) u v ( )w

I
1 0 0
0 1 0
0 0 1

v w
v
1
w
1
v
1
w
2
v
1
w
3
v
2
w
1
v
2
w
2
v
2
w
3
v
3
w
1
v
3
w
2
v
3
w
3

v
1
v
2
v
3
w
1
w
2
w
3

wx_
0 w
3
w
2
w
3
0 w
1
w
2
w
1
0

u wx_ ( ) w u

v w ( )
k
v w ( )
k1
v w ( ) k 1

v w 0 implies e
d vw ( )
I + d v w ( )

w w 1 implies e
d ww ( )
I + e
d
1 w w ( ) ( )

wx_ ( )
2
w w I and wx_ ( )
3
wx_

wx_ ( )
2k
1 ( )
k
I w w ( ) and wx_ ( )
2k+1
1 ( )
k
wx_
335
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 335
Li near Tr ansf or mat i ons Li near Tr ansf or mat i ons Li near Tr ansf or mat i ons Li near Tr ansf or mat i ons Li near Tr ansf or mat i ons
We shall focus our at t ent ion on t he following ve linear t r ansfor mat ions,
which are st and ard in comput er gr aphics. Not ice t hat we d o not includ e
any project ions, since project ions are singular and , t herefore, cannot be
exponent ials. By convent ion, all t he vect or s below are unit vect or s.
rot (w,) = rot at ion around t he axis vect or w t hrough t he
angle ,
mir (n) = mir ror image in t he plane per pend icular t o t he
vect or n,
scale(c) = scaling in all d irect ions by a const ant c > 0,
scale(c, w) = scaling only in t he d irect ion par allel t o t he
vect or w by a const ant c > 0,
shear (v, w, ) = shear ing or t hogonal t o t he plane per pend ic-
ular t o t he vect or v by t he angle in t he
d irect ion par allel t o t he vect or w, which is
per pend icular t o t he vect or v.
Here, we consid er only t he 3 3 mat r ices d ened by t hese t r ansfor ma-
t ions, not t he 4 4 mat r ices d iscussed in previous ar t icles. We can t hink
of t his in t wo ways. The four t h row of t he t r ansfor mat ion mat r ix st ores a
t r anslat ion. If our t r ansfor mat ions are d ened by lines or planes t hat pass
t hrough t he or igin, t hen t his four t h row d oes not cont r ibut e anyt hing and
is not required . Alt er nat ively, we can t hink of applying our t r ansfor ma-
t ions only t o vect or s, not t o point s. In t his case, t he four t h row again
cont r ibut es not hing, since vect or s remain invar iant und er t r anslat ion. In
any event , we are d ealing here wit h linear, r at her t han affine, t r ansfor ma-
t ions.
Now, in previous ar t icles (Mat r ices and Tr ansfor mat ions, in Graph-
ics Gerns, and More Mat r ices and Tr ansfor mat ions, in t his book), we
336
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 336
have shown t hat :
rot (w, ) = (cos)I + (1 cos)w

w + (sin)wx_,
mir (n) = I 2n

n,
scale(c) = cI,
scale(c, w) = I + (c1)w

w,
shear (v, w, ) = I + (t an)v

w.
Each of t hese t r ansfor mat ion mat r ices is nonsingular and , it t ur ns out ,
each can be represent ed as an exponent ial. Ind eed , using t he d enit ions
and t he proper t ies of t he exponent ial map, t he t ensor prod uct , and t he
cross prod uct , it is not d ifcult t o show t hat :
rot (w,) = e
(wx_)
,
mir (n) = e
i

(n

n)
, (i =

1)
scale(c) = c
I
,
scale(c, w) = c
w

w
,
shear (v, w, ) = e
(t an)v

u)
.
One immed iat e applicat ion of t hese exponent ials is t hat t hey make it
par t icular ly easy t o comput e d et er minant s. Recall t hat :
Det (e
M
) = e
Tr ace(M)
Moreover, it is easy t o ver ify t hat :
Tr ace(I) = 3
Tr ace(v

w) = v w
Tr ace(wx_) = 0.
337
VII.3 TRANSFORMATIONS AS EXPONENTIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 337
Therefore,
Det {rot (w,)} = e
0
= 1,
Det (mir (n)} = e
i

=-1,
Det {scale(c)} = e
3ln(c)
= C
3
,
Det {scale(c, w)} = e
ln(C)
= c
Det {shear (v, w, )} = e
0
= 1.
The most int er est ing of t hese exp onent ials by far is t he one for
rot at ion. As we said at t he st ar t , rot at ion mimics t he exponent ial funct ion,
since mult iplicat ion of rot at ions around t he same axis is akin t o ad d ing
angles. This obser vat ion is immed iat e from t he proper t ies of t he exponen-
t ial map, since:
rot (w,
1
) rot (w,
2
) = e

1
wx _ ( )

2
wx _ ( )
,
= e

1
+
2
( ) wx_ ( )
,
= rot (w,
1
+
2
).
Since exponent ials are par t icular ly simple t o manipulat e, t he exponent ial
map also may be useful for d iscover ing ot her id ent it ies relat ing t he
st and ard linear t r ansfor mat ions of comput er gr aphics.
338
VII.4 MORE MATRICES AND TRANSFORMATIONS: SHEAR AND PSEUDO- PERSPECTIVE
GRAPHICS GEMS II Edit ed by JAMES ARVO 338
MORE MATRICES AN MORE MATRICES AN MORE MATRICES AN MORE MATRICES AN MORE MATRICES AND DD DD
T TT TTRANSFORMATIONS: SHEAR RANSFORMATIONS: SHEAR RANSFORMATIONS: SHEAR RANSFORMATIONS: SHEAR RANSFORMATIONS: SHEAR
A AA AAN NN NND D D D D PSEUDO-PERSPECTIVE PSEUDO-PERSPECTIVE PSEUDO-PERSPECTIVE PSEUDO-PERSPECTIVE PSEUDO-PERSPECTIVE
Ronald N. Goldman
Rlce Universit y
Houst on, Texas
In Graphics Gems (Mat r ices and Tr ansfor mat ions), we showed how t o
const ruct t he mat r ices for affine and project ive t r ansfor mat ionsrot a-
t ion, mir ror image, scaling, and project ionswhich were not d ened
relat ive t o t he or igin and coord inat e axes, but r at her relat ive t o some
ar bit r ar y posit ions and or ient at ions. Two fund ament al t r ansfor mat ions we
omit t ed from t hat d iscussion were shear and pseud o-per spect ive. Here,
we const ruct t he mat r ices for t hese t wo impor t ant t r ansfor mat ions. We
begin by recalling some not at ion.
Not at i on Not at i on Not at i on Not at i on Not at i on
a. Id ent it y


I
1 0 0
0 1 0
0 0 1

b. Tensor Prod uct
VII.4 VII.4 VII.4 VII.4 VII.4

v w
v
1
w
1
v
1
w
2
v
1
w
3
v
2
w
1
v
2
w
2
v
2
w
3
v
3
w
1
v
3
w
2
v
3
w
3

v
1
v
2
v
3
w
1
w
2
w
3
339
VII.4 MORE MATRICES AND TRANSFORMATIONS: SHEAR AND PSEUDO- PERSPECTIVE
GRAPHICS GEMS II Edit ed by JAMES ARVO 339
Obser vat i ons Obser vat i ons Obser vat i ons Obser vat i ons Obser vat i ons
u I = u
u (v

w) = (u v)w
Shear Shear Shear Shear Shear
A shear is d ened in t er ms of a shear ing plane S, a unit vect or w in S,
and an angle . Given any point P, project P or t hogonally ont o a point
P in t he shear ing plane S. Now, slid e P par allel t o w t o a point P, so
t hat PPP = . The point P is t he result of applying t he shear ing
t r ansfor mat ion t o t he point P. (See Fig. 1.)
To const ruct t he 4 x 4 mat r ix which represent s shear, let
S = Shear ing plane
v = Unit vect or per pend icular t o S
Q = Point on S
w = Unit vect or in S (i.e., unit vect or per pend icular t o v)
= Shear angle
Figure 1. The Geomet r y of a shear
340
VII.4 MORE MATRICES AND TRANSFORMATIONS: SHEAR AND PSEUDO- PERSPECTIVE
GRAPHICS GEMS II Edit ed by JAMES ARVO 340
Then t he shear t r ansfor mat ion is given by t he 4 x 4 mat r ix:
It is easy t o ver ify by d irect comput at ion t hat
Det {Shear (Q, v, w, )} = 1.
Therefore, shear ing preser ves volumes.
Pseudo- Per spect i ve Pseudo- Per spect i ve Pseudo- Per spect i ve Pseudo- Per spect i ve Pseudo- Per spect i ve
If we per for m per spect ive project ion before clipping, we lose t he abilit y
t o clip in d ept h. To avoid t his problem, we must put d ept h back int o t he
per spect ive t r ansfor mat ion; t hat is, we want a t r ansfor mat ion t hat gives
us bot h per spect ive and d ept h. Usually, t his is d one by fact or ing per spec-
t ive project ion t hrough or t hogonal project ion. Thus, we want a pseud o-
per spect ive t r ansfor mat ion t hat preser ves relat ive d ept h such t hat :
Per spect ive = (Pseud o-Per spect ive) (Or t hogonal Project ion).
To const ruct t he 4 4 mat r ix t hat represent s pseud o-per spect ive, let
S = Per spect ive plane
Q = Point on S
N = Unit vect or per pend icular t o S
R = Per sp ect i ve p oi n t

Shear Q, v, w, ( )
I + tan v w ( ) 0
Q v ( )w 1
341
VII.4 MORE MATRICES AND TRANSFORMATIONS: SHEAR AND PSEUDO- PERSPECTIVE
GRAPHICS GEMS II Edit ed by JAMES ARVO 341
Then t he pseud o-per spect ive t r ansfor mat ion is given by t he 4 4 mat r ix:
where
T
N d enot es t he t r anspose of t he row vect or N.
See also (472) Mat rices and Transformat ions, Ronald Goldman

Pseudo N, Q, R ( )
Q R ( ) N
{
I + N R + N N
T
N
Q N ( ) R + N ( ) R N
342
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 342
VII.5 VII.5 VII.5 VII.5 VII.5
F FF FFAST MATRIX AST MATRIX AST MATRIX AST MATRIX AST MATRIX I II IINVERSION NVERSION NVERSION NVERSION NVERSION
Kevin Wu
Sun Microsyst ems, Inc.
Mount ain View, Calif ornia
Pr obl em St at ement Pr obl em St at ement Pr obl em St at ement Pr obl em St at ement Pr obl em St at ement
Per for ming mat r ix oper at ions quickly is especially impor t ant when a
gr aphics progr am changes t he st at e of t he t r ansfor mat ion pipeline fre-
quent ly. Mat r ix inver sion can be relat ively slow compared wit h ot her
mat r ix oper at ions because inver sion requires careful checking and han-
d ling t o avoid numer ical inst abilit ies result ing from round off er ror and t o
d et er mine when a mat r ix is singular. However, a gener al-pur pose mat r ix
inver sion proced ure is not necessar y for special t ypes of mat r ices. In-
d eed , when speed is more impor t ant t han cod e size, a gr aphics progr am-
mer can benet great ly by id ent ifying groups of mat r ices t hat have simple
inver ses and provid ing a special mat r ix inver sion proced ure for each
t ype. This gem d escr ibes inver sion of 4 4 mat r ices for t ypes t hat
commonly ar ise in 3D comp u t er gr ap hics. Not e t hat p reviou s gems
(Car ling, 1990; Tur kowski, 1990) have given examples where a mat r ix
inver se is need ed , includ ing t ext ure mapping and nor mal vect or t r ansfor-
mat ion.
Bui l di ng Bl ocks Bui l di ng Bl ocks Bui l di ng Bl ocks Bui l di ng Bl ocks Bui l di ng Bl ocks
Gr aphics booksfor example, Foley and van Dam (1982) and Newman
and Sproull (1979)d escr ibe how t o const r uct gener al geomet r ic t r ans-
for ma t i on s by con ca t en a t i n g ma t r i x r ep r esen t a t i on s of t h e ba si c
oper at ions: t r anslat ion, scaling, and rot at ion. We d enot e t he 3D t r ansfor-
343
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 343
at ions wit h 4 4 mat r ices:
T(t
x
, t
y
, t
z
) is a t r anslat ion mat r ix.
S(s
x
, s
y
, s
z
) is a scale mat r ix.
R is a rot at ion mat r ix in (x, y, z) coord inat e space.
We ad opt t he convent ion of t reat ing point s in homogeneous space as row
vect or s of t he for m [wx wy wz w], w 0. These mat r ices are suit able
for d eveloping t he id eas in t he following sect ions, but some gr aphics
progr ammer s may nd it convenient t o consid er ot her build ing blocks,
such as shear.
Basi c Gr oup Theor y Basi c Gr oup Theor y Basi c Gr oup Theor y Basi c Gr oup Theor y Basi c Gr oup Theor y
A group is an algebr aic object useful for char act er izing symmet r ies and
per mut at ions. For example, all cr yst alline lat t ices can be classied by
applying group t heor y. Gilber t (1976) gives a good int rod uct ion t o t he
subject . Our int erest in groups comes from t he d esire t o d ene t he scope
of special mat r ix t ypes.
Def i ni t i on I A group (G, ) is a set G t oget h er wit h a bin ar y
oper at ion sat isfying t he following axioms.
1. Closure: a b G for all a, b G.
2. Associat ivit y: (a b) c = a (b c) for all a, b, c G.
3. Ident it y: There exist s an ident it y element e G, such t hat e a =
a e = a for all a G.
4. Inv erse: Ea ch el emen t a G h a s a n inv erse el emen t a
-l
G,
such t hat a
-1
a = a a
-1
= e.
For our pur poses, t he set G is a par t icular t ype of mat r ix wit h a cer t ain
for m and set of proper t ies. The oper at ion is mat r ix mult iplicat ion. When
t he oper at ion of a group is clear ly und er st ood , we can d enot e t he group
by only it s und er lying set . Hereaft er, we d enot e t he mat r ix group (G, )
344
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 344
by simply G wit h t he mat r ix mult iplicat ion oper at ion implicit . Not e t hat
t he four t h axiom limit s our at t ent ion t o nonsingular mat r ices. A singular
mat r ix has no inver se, so in pr act ice, a mat r ix inver sion proced ure must
check for t his cond it ion.
Mat r i x Gr oups i n Gr aphi cs Mat r i x Gr oups i n Gr aphi cs Mat r i x Gr oups i n Gr aphi cs Mat r i x Gr oups i n Gr aphi cs Mat r i x Gr oups i n Gr aphi cs
The following mat r ix groups can occur frequent ly in gr aphics applica-
t ions, so t hey d eser ve special at t ent ion.
Basi c Mat r i x Gr oups Basi c Mat r i x Gr oups Basi c Mat r i x Gr oups Basi c Mat r i x Gr oups Basi c Mat r i x Gr oups
Each of t he element ar y mat r ix t ypes t oget her wit h mat r ix mult iplicat ion
is a group. These are useful groups:
Ident it y Mat rix Group: = {I}.
Translat ion Mat rix Group: = {T(t
x
, t
y
,t
z
)}.
Isot ropic Scale Mat rix Group:
i
= {S(s, s, s)| S 0}.
Anisot ropic Scale Mat rix Group:
a
= {S(s
x
, s
y
, s
z
)| s
x
, s
y
, s
z
0}.
Rot at ion Mat rix Group: = {R}.
The Wi ndow- t o- Vi ewpor t Mat r i x Gr oup The Wi ndow- t o- Vi ewpor t Mat r i x Gr oup The Wi ndow- t o- Vi ewpor t Mat r i x Gr oup The Wi ndow- t o- Vi ewpor t Mat r i x Gr oup The Wi ndow- t o- Vi ewpor t Mat r i x Gr oup

Tr ansfor mat ion of a wind ow t o a viewpor t is t he last st age of a t ypical


gr aphics t r ansfor mat ion pipeline. It involves scaling and t r anslat ion, but
not rot at ion. A mat r ix of t his for m also may appear in ot her par t s of a
t r ansfor mat ion pipeline.
The Lengt h- Pr eser vi ng Mat r i x Gr oup The Lengt h- Pr eser vi ng Mat r i x Gr oup The Lengt h- Pr eser vi ng Mat r i x Gr oup The Lengt h- Pr eser vi ng Mat r i x Gr oup The Lengt h- Pr eser vi ng Mat r i x Gr oup
1

l
A gr aphics progr am somet imes can benet from knowing when a mat r ix

T t
x
, t
y
, t
z
( )
, S s
x
, s
y
, s
z
( )
s
x
, s
y
, s
z
0
{


T t
x
, t
y
, t
z
( )
, R
{

345
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 345
always preser ves t he d ist ances bet ween point s and t he lengt hs of d irec-
t ion vect or s. For example, when a unit light d irect ion vect or or unit
sur face nor mal vect or passes t hrough such a mat r ix, t he progr am d oes
not need t o nor malize t he vect or aft er t r ansfor mat ion, saving t hree
mult iplicat ions and d ivisions and a square root per vect or.
The Angl e- Pr eser vi ng M The Angl e- Pr eser vi ng M The Angl e- Pr eser vi ng M The Angl e- Pr eser vi ng M The Angl e- Pr eser vi ng Mat r i x Gr oup at r i x Gr oup at r i x Gr oup at r i x Gr oup at r i x Gr oup
a

a
A mat r ix t hat preser ves angles allows light ing calculat ions t o t ake place in
mod el coord inat es. Inst ead of t r ansfor ming sur face nor mals t o wor ld
coord inat es and per for ming light ing t here, we can t r ansfor m t he light s
back t o mod el coord inat es t o calculat e t he reect ed light . This is bene-
cial when t here are fewer light s t han sur face nor mals in a par t icular
mod el sp ace. Since angles are p r eser ved , so are d ot p rod u ct s (aft er
renor malizing d irect ion vect or s). Some local light sou rces may have
at t enu at ion p r op er t ies t hat cau se t he int ensit y of light reaching t he
sur face t o d iminish wit h it s d ist ance from t he light source. In such a
sit uat ion, t he unifor m scaling fact or must be applied t o d ist ances in mod el
coord inat es.
The Af f i ne The Af f i ne The Af f i ne The Af f i ne The Af f i ne Mat r i x Gr oup Mat r i x Gr oup Mat r i x Gr oup Mat r i x Gr oup Mat r i x Gr oup

An affine mat r ix preser ves t he st r aight ness of lines and t he par allelism of
par allel lines, but possibly alt er s d ist ances bet ween point s or t he angles
bet ween lines. Thus, an afne mat r ix can per for m anisot ropic scaling.
Per spect ive project ion is an example of a t r ansfor mat ion t hat is not affine.
However, par allel project ion is affine. In ad d it ion, t he mod el t r ansfor ma-
t ion t hat map s p oint s from mod el coord inat es t o wor ld coor d inat es
almost always is afne.
The Nonsi ngul ar Mat r i x Gr oup The Nonsi ngul ar Mat r i x Gr oup The Nonsi ngul ar Mat r i x Gr oup The Nonsi ngul ar Mat r i x Gr oup The Nonsi ngul ar Mat r i x Gr oup
Al l t h e p r eced i n g gr ou p s ar e su bgr ou p s of t h e nonsingular mat r i x
group. Per spect ive mat r ices are includ ed in t his group as well. We d enot e
it by .

T t
x
, t
y
, t
z
( )
, R, S s, s, s ( ) s 0
{


T t
x
, t
y
, t
z
( )
, R, S s
x
, s
y
, s
z
( )
s
x
, s
y
, s
z
0
{

346
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 346
Member shi p and Pr i vi l eges Member shi p and Pr i vi l eges Member shi p and Pr i vi l eges Member shi p and Pr i vi l eges Member shi p and Pr i vi l eges
The preced ing sect ion int rod uced t he mat r ix groups by list ing t he ele-
ment ar y mat r ices t hat belong t o each group; t hese are t he columns in
Table 1. Now, we examine each element ar y mat r ix and t abu lat e it s
member ships t o t he mat r ix groups; t hese are t he rows of Table 1.
A gr aphics progr am can t ake ad vant age of t his infor mat ion in t he
following way. We assign each group t o a bit in a ag word and associat e
t his ag word or membership record wit h each mat r ix in a gr ap hics
progr am. The progr am has ut ilit ies for const ruct ing each of t he elemen-
t ar y mat r ices. For example, a ut ilit y t akes a t r anslat ion vect or and ret ur ns
a t r anslat ion mat r ix. In ad d it ion, it set s t he member ship record associat ed
wit h t his mat r ix accord ing t o t he second row of Table 1.
The gr aphics progr am t akes ad vant age of t he d enit ion of a group
when it mu lt ip lies t wo mat r ices. Since a grou p is closed u nd er it s
oper at ion, t he prod uct of t wo mat r ices is a member of t he groups t o
which bot h oper and s belong: The progr am simply int er sect s t he oper and s
member ship r ecord s u sing logical AND t o obt ain t he record of t he
prod uct . When t he progr am need s t o calculat e t he inver se of a mat r ix, it s
member ship record est ablishes it s pr ivilege t o use a fast mat r ix inver sion
proced ure.
As an asid e, we not e t hat a gr aphics progr am also can use t he member-
ship record s t o opt imize mat r ix mult iplicat ion. Each mat r ix group has a
char act er ist ic for m, oft en wit h many zeros and ones. As a previous gem
(Thompson, 1990) has obser ved , a progr ammer can eliminat e ext r aneous
mu lt ip licat ions and ad d it ions and u nroll t he loop s accor d ing t o t he
Table 1. Element ar y Mat r ices and Mat r ix Groups
347
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 347
member ships of t he t wo mat r ices. Perhaps more impor t ant ly, a progr am-
mer can opt imize mult iplicat ion of point s by a mat r ix because t housand s
of point s may require t he geomet r ic mapping of t he mat r ix.
Mat r i x Inver si on Mat r i x Inver si on Mat r i x Inver si on Mat r i x Inver si on Mat r i x Inver si on
The member ship record associat ed wit h a mat r ix d et er mines how much
effor t a gr aphics progr am requires t o inver t t he mat r ix. The progr am
d et er mines t he group t hat has t he fast est inver sion proced ure among t he
mat r ixs eligible groups and calls t hat proced ure. The four t h axiom in a
groups d enit ion st at es t hat t he inver se belongs t o t he same groups as
t he or iginal mat r ix. By implicat ion, t he inver se has t he same for m as t he
or iginal, so some of t he zeros and ones occupy t he same posit ions.
Inver ses of t he El ement ar y Mat r i ces Inver ses of t he El ement ar y Mat r i ces Inver ses of t he El ement ar y Mat r i ces Inver ses of t he El ement ar y Mat r i ces Inver ses of t he El ement ar y Mat r i ces
The inver ses of t he element ar y mat r ices are st r aight for ward :
Ident it y: I
1
= I.
Translat ion: T
-l
(t
x
, t
y
, t
z
) = T(-t
x
, -t
y
, -t
z
).
Scale: S
1
(s
x
, s
y
, s
z
) = S(s
x
1
, s
Y
1
, s
z
1
), s
x
, s
y
, s
z
0.
Rot at ion: R
l
= R
T
Eval uat i on St r at egy Eval uat i on St r at egy Eval uat i on St r at egy Eval uat i on St r at egy Eval uat i on St r at egy
A gr aphics progr am can evaluat e inver ses on t he y (aut omat ic evalua-
t ion) or on d emand (lazy evaluat ion).
Given t he inver ses of t he preced ing element ar y mat r ices, t he progr am
aut omat ically can evaluat e t he inver se when it mult iplies t wo mat r ices
accord ing t o t he r ule, (AB)
1
= B
1
A
1
, provid ed A and B are inver t ible.
This approach r equires t hat t he inver se always is available. Therefore,
mat r ix mult iplicat ion runs at half it s nor mal speed because t he mult iplica-
t ion ut ilit y must nd t he prod uct of t wo mat r ices and t he t wo inver ses.
Lazy evaluat ion allows mat r ix mult iplicat ion t o run at full speed be-
cause t he gr aphics progr am never evaluat es t he prod uct of inver ses. An
inver sion ut ilit y explicit ly evaluat es an inver se as required . In pr act ice, a
348
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 348
t ypical gr aphics progr am usually per for ms many more mat r ix mult iplica-
t ions t han inver sions so lazy evaluat ion gives bet t er over all syst em per for-
mance. The following t wo sect ion s d escr ibe ad d it ion al sp ecial-case
inver sion t echniques for use wit h lazy evaluat ion t hat complement t he
ones in t he preced ing sect ion.
Inver se of a Wi ndow- t o- Vi ewpor t Mat r i x Inver se of a Wi ndow- t o- Vi ewpor t Mat r i x Inver se of a Wi ndow- t o- Vi ewpor t Mat r i x Inver se of a Wi ndow- t o- Vi ewpor t Mat r i x Inver se of a Wi ndow- t o- Vi ewpor t Mat r i x
The inver se of a wind ow-t o-viewpor t mat r ix is useful in picking when t he
pick d evice gives locat ions in t he d evice coord inat es of t he viewpor t and
t he pick aper t ure concept ually resid es in t he vir t ual d evice coord inat es of
t he wind ow:
, sx, sy, sz 0.

s
x
0 0 0
0 s
y
0 0
0 0 s
z
0
t
x
t
y
t
z
1

]
]
]
]
]
]
]
]
]
1

1
s
x
0 0 0
0
1
s
y
0 0
0 0
1
s
z
0
t
x
s
x
t
y
s
y
t
z
s
z
1

]
]
]
]
]
]
]
]
]
Inver se of an Af ne Mat r i x Inver se of an Af ne Mat r i x Inver se of an Af ne Mat r i x Inver se of an Af ne Mat r i x Inver se of an Af ne Mat r i x
The prod uct of any combinat ion of t he element ar y mat r ices always is
affine. A t ypical 3D gr aphics progr am probably need s t o nd t he inver se
of mat r ices in t he affine group and t he nonsingular group more
oft en t han any ot her groups. A gener al-pur pose mat r ix inver sion proce-
d ure is necessar y for . However, a fast er proced ure is possible for
because t he last column always is [0 0 0 1]
T
. A fact applicable t o t he
inver se of block mat r ices (for examp le, Kailat h, 1980) ser ves as t he
st ar t ing point :

M
1

A 0
C B

]
]
]
1

A
1
0
B
1
CA
1
B
1

]
]
]

349
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 349
This hold s for any square submat r ices A and B as long as t heir inver ses
exist . For our afne mat r ices, we let A be t he upper-left 3 3 submat r ix
of M and B be 1. Then t his result simplies t o

M
1

A 0
C 1

]
]
]
1

A
1
0
CA
1
1

]
]
]

The effor t required t o calculat e t he inver se of t he 3 3 mat r ix A is much


less t han t hat for a gener al 4 4 mat r ix.
One met hod for nd ing t he inver se of a gener al mat r ix involves d et er-
mi n a n t s a s d escr i bed i n a p r evi ou s gem (Ca r l i n g, 1990): A
-1
=
A*/ d et (A), wher e A* is t he ad joint mat r ix of A and d et (A) is t he
d et er minant of A. If t he d imension of A is n, t he number of mult iplica-
t ions for t his met hod is ((n + 1)!) for large n.
Anot her inver sion t echnique is Gauss-Jord an eliminat ion. In pr act ice, a
relat ed t echniqueLU d ecomposit ion wit h par t ial pivot ing and backsub-
st it u t ionis more efficient and robu st . Numerical Recipes in C (Press
et al., 1988) d escr ibes t his in some d et ail and gives a C Implement at ion.
The oper at ions count is (n
3
), and t he book claims t here is no bet t er way
t o nd t he inver se. LU d ecomposit ion has much overhead and bookkeep-
ing, includ ing many t est s and loops. In ad d it ion, par t ial pivot ing requires
exch a n gi n g r ows. Th ese ext r a st ep s ca n cou n t for mor e t h a n
t he oat ing-point ar it hmet ic, d epend ing on t he hard ware.
Some t est r uns for calculat ing t he inver se of affine mat r ices on a SUN
SPARCst at ion 330 d emonst r at ed t hat t he ad joint approach is t wice as fast
as LU d ecomposit ion aft er unrolling t he loops, subst it ut ing const ant s for
t he var iable ind ices, and eliminat ing ext r aneous t est s; bot h t hese imple-
ment at ions t reat afne mat r ices as block mat r ices. This ad ,joint t echnique
is t hree t imes fast er t han a proced ure capable of inver t ing any nonsingu-
lar 4 4 mat r ix using LU d ecomposit ion and no block mat r ices. How-
ever, numer ical analyst s agree t hat Gaussian eliminat ion t echniques like
LU d ecomp osit ion wit h p ivot ing are more st able in t he p resence of
rou nd off er r or t han d et er minant met hod s. The gr ap hics p rogr ammer
need s t o d ecid e whet her t he r isk is wor t h t he improved per for mance.
A C Implement at ion for calculat ing t he inver se of a 3D afne mat r ix is
includ ed in Append ix 2. It find s A
1
from t he ad joint mat r ix and M
1
from t he equat ion for inver t ing block mat r ices.
350
VII.5 FAST MATRIX INVERSION
GRAPHICS GEMS II Edit ed by JAMES ARVO 350
Inver se of a Nonsi ngul ar Mat r i x Inver se of a Nonsi ngul ar Mat r i x Inver se of a Nonsi ngul ar Mat r i x Inver se of a Nonsi ngul ar Mat r i x Inver se of a Nonsi ngul ar Mat r i x
A 4 4 mat r ix belonging t o t he nonsingular mat r ix group requires a
gener al mat r ix inver sion proced ure. Some t est runs (again, on a SPARC-
st at ion 330) have shown t hat LU d ecomposit ion is fast er t han t he ad joint
met hod , but t he r at io is less t han a fact or of t wo. The result s may d iffer
on a host machine wit h d ifferent oat ing-point per for mance relat ive t o
nonar it hmet ic per for mance, but LU d ecomposit ion wit h par t ial pivot ing is
more st able numer ically.
Summar y Summar y Summar y Summar y Summar y
A gr aphics progr ammer can t ake t he following st eps t o improve t he
per for mance of 3D mat r ix inver sion for special t ypes of mat r ices com-
monly found in comput er gr aphics:
1. Provid e a set of ut ilit ies for const ruct ing a basic set of element ar y
mat r ices.
2. Associat e a member ship record wit h each mat r ix t hat d escr ibes t he
mat r ix grou p s t o which t he mat r ix belongs. The u t ilit ies in t he
previous st ep init ialize t he mat r ixs member ship record .
3. The mat r ix mult iplicat ion ut ilit y d et er mines t he member ship record
of a prod uct by int er sect ing t he record s of t he t wo oper and mat r ices.
4. The mat r ix inver sion ut ilit y inver t s a mat r ix by calling t he fast est of
t he proced ures associat ed wit h t he groups in t he mat r ixs member-
ship record .
351
VII.6 QUATERNIONS AND 4X4 MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 351
VII.6 VII.6 VII.6 VII.6 VII.6
Q QQ QQUATERNIONS AND UATERNIONS AND UATERNIONS AND UATERNIONS AND UATERNIONS AND 4 X 4 4 X 4 4 X 4 4 X 4 4 X 4
M MM MMATRICES ATRICES ATRICES ATRICES ATRICES
Ken Shoemake
Ot t er Ent erprises
Palo Alt o, Calif ornia
Quat ernions are st ead ily replacing Euler angles as t he int er nal represen-
t at ion of or ient at ions, presumably because of such ad vant ages as are
d et ailed in Shoemake (1985, 1989). What is not so obvious from t hat
paper, however, is t hat t hey mesh remar kably well wit h 4 4 homoge-
neous mat r ices.
Mat r ix mult iplicat ion can be used quit e nicely for quat er nion mult ipli-
cat ion, since qu at er nions are, in fact , fou r -comp onent homogeneou s
coord inat es for or ient at ions, and since t hey mult iply linear ly. Consid er a
quat er nion q as a 4-vect or, wr it t en (x
g
, y
q
, z
g
, w
q
), or as just (x, y, z, w)
when cont ext makes it clear. The quat er nion prod uct pq is a linear
funct ion of eit her p or q, so t wo d ifferent mat r ix for ms are possible.
(Tr anspose t hese when using row vect or s.) They are:
pq
and

L p
( )
q
w
p
z
p
y
p
x
p
z
p
w
p
x
p
y
p
y
p
x
p
w
p
z
p
x
p
y
p
z
p
w
p

]
]
]
]
]
]
x
q
y
q
z
q
w
q

]
]
]
]
]
]

R q
( )
p
w
q
z
q
y
q
x
q
z
q
w
q
x
q
y
q
y
q
x
q
w
q
z
q
x
q
y
q
z
q
w
q

]
]
]
]
]
]
x
p
y
p
z
p
w
p

]
]
]
]
]
]
pq
352
VII.6 QUATERNIONS AND 4X4 MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 352
Using t hese L and R mat r ices, we can read ily conver t a quat er nion t o a
homogeneous rot at ion mat r ix. Recall t hat a quat er nion q rot at es a vect or
v u sing t he p r od u ct qvq
1
, wher e q
1
= q*/N(q). In t he common
case of a unit quat er nion, q
1
= q*. This per mit s t he rot at ion mat r ix t o
be comp u t ed from t he comp onent s of qsince q* is merely (x, y,
z, w)as
Rot(q) = L(q)R(q*),
so t hat a hard ware mat r ix mult iplier can d o all t he conver sion wor k. Isnt
t hat nice?
More specically, suppose you are using hard ware mat r ix mult iplica-
t ion t o compose a ser ies of mat r ices t hat will be applied t o row vect or s in
r ight -hand ed coord inat es, as in vSNQTP, where Q is t o be d er ived from a
quat er nion, q = (x, y, z, w). Then inst ead of Q, compose wit h L(q) and
R(q*), so t hat t he sequence is vSNRLTP. For row vect or s, we want t he
t r anspose for m of L and R, so we have
Q
row
= R
r ow
(q*)L
row
(q) =
Because t he d esired result is a homogeneous rot at ion mat r ix, an over all
scale fact or can be ignored ; t hus, q* can be used inst ead of q
1
even if
N(q) = q q* = x
2
+ y
2
+ z
2
+ w
2
is not equal t o one. Be aware, how-
ever, t hat some syst ems d o not implement mat r ix manipulat ions carefully,
and will misbehave if t he bot t om r ight ent r y of t he mat r ix is not 1. Even
when nor malizat ion is d esired , it is not necessar y t o comput e a square
root ; only ad d it ion, subt r act ion, mult iplicat ion, and d ivision are used .
Not ice t hat only t he last row and column of t he t wo mat r ices d iffer, and
t hen only by t r ansposit ion or sign change. (This may seem obvious, but
one progr ammer s obvious is anot her s obscure, and perhaps point -
ing it out will save someone t ime.) Alt hough t hese t wo mat r ices may look

w z y x
z w x y
y x w z
x y z w

]
]
]
]
]
]

w z y x
z w x y
y x w z
x y z w

]
]
]
]
]
]

353
VII.6 QUATERNIONS AND 4X4 MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 353
peculiar t o t he aver age comput er gr aphicist , mult iplying t hem conr ms t hat
t he result is a mat r ix wit h t he expect ed zeros in t he last row and column,
wit h 1 in t he cor ner for a unit quat er nion.

Q
row

w
2
+ x
2
y
2
z
2
2xy 2wz 2xz + 2wy 0
2xy + 2wz w
2
x
2
+ y
2
z
2
2yz 2wx 0
2xz 2wy 2yz + 2wx w
2
x
2
y
2
+ z
2
0
0 0 0 w
2
+ x
2
+ y
2
+ z
2

]
]
]
]
]
]
Fans of 4D should not e t hat any rot at ion of a 4-vect or v can be wr it t en
as p q v q
1
p, which is t r anslat ed easily int o mat r ices using t his
same approach. The q quat er nion cont rols rot at ion in t he planes exclud -
ing wnamely xy, xz , and y z while t he p qu at er nion cont r ols
rot at ion in t he planes includ ing wnamely wx, wy, and wz.
Conver t ing a homogeneous mat r ix back t o a quat er nion also is rela-
t ively easy, as t he Q
r ow
mat r ix has a great d eal of st ruct ure t hat can be
exploit ed . To preser ve numer ical precision, one must ad apt t o t he spe-
cic mat r ix given, but t he st ruct ure also makes t hat elegant . Obser ve t hat
t he d ifference, Q
r ow
minus it s t r anspose, has a simple for m:

Q
row
Q
row
T

0 4wz 4wy 0
4wz 0 4wx 0
4wy 4wx 0 0
0 0 0 0

]
]
]
]
]
]
.
Clear ly, it is easy t o nd x, y, and z when w is known, so long as w is
not zeroor, for bet t er precision, so long as w is not near ly zero. On t he
ot her hand , t he sum Of Q
row
plus it s t r anspose also is simple, if we ignore
t he d iagonal:

Q
row
+ Q
row
T
diagonal
0 4xy 4xz 0
4xy 0 4yz 0
4xz 4yz 0 0
0 0 0 0

]
]
]
]
]
]

354
VII.6 QUATERNIONS AND 4X4 MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 354
So, knowing any one of x, y, or z also makes it easy t o nd t he ot her s,
and t o nd w (using t he d ifference mat r ix). In par t icular, if (i, j, k) is a
cyclic per mut at ion of (0, 1, 2), t hen

w
Q k, j
[ ]
Q j, k
[ ]
q i
[ ]
, q j
[ ]

Q i, j
[ ]
+ Q j, i
[ ]
q i
[ ]
,


q k
[ ]

Q i, k
[ ]
+ Q k, i
[ ]
q i
[ ]
.
Now obser ve t hat t he t r ace of t he homogeneous mat r ix (t he sum of t he
d iagonal element s) always will be 4w
2
. Denot ing t he d iagonal element s
by X, Y, Z, and W, one nd s all possibilit ies:
4x
2
= X Y - Z + W,
4y
2
= X + Y - Z + W
4z
2
= X Y + Z + W
4w
2
= X + Y + Z + W
Except for w, t he comput at ion is q[i] = Sqr t (Q[i, i] Q[j, j] Q[k, k]
+ Q[3, 3])/ 2. Since a d ivid e almost cer t ainly is cheaper t han a square
root , it is bet t er t o comput e just one of t hese, prefer ably t he largest , since
t hat will give t he best precision for t he d ivid es; but look at t he d iagonal
element s again, and let S = w
2
x
2
y
2
z
2
. Then X = S + 2x
2
,
Y = S + 2y
2
, Z = S + 2z
2
, and T = X + Y + Z = S + 2w
2
. Clear ly,
which of X, Y, Z, or T is largest ind icat es which of x, y, z, or w is
largest . (T is t he t r ace of t he upper-left 3 3 cor ner of t he homogeneous
mat r ix.)
See also (498) Usi n g Qu a t er n i on s for Cod i n g 3D Tr a n sfor ma -
t ions, Pat r ick-Gilles Maillot
355
VII.7 RANDOM ROTATION MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 355
VII.7 VII.7 VII.7 VII.7 VII.7
RA RA RA RA RANDOM ROTATION NDOM ROTATION NDOM ROTATION NDOM ROTATION NDOM ROTATION
M MM MMATRICES ATRICES ATRICES ATRICES ATRICES
James Arvo
Apollo Syst ems Division of Hewlet t -Packard
Chelmsf ord, Massachuset t s
It is somet imes convenient t o gener at e ar bit r ar y 3 3 rot at ion mat r ices
for use in creat ing r and omized mod els, r and om animat ion sequences, or
for use in st ochast ic simulat ions. The following rout ine (Fig. 1) maps
t hree r and om var iables in t he r ange [0, 1] ont o t he set of or t hogonal
3 3 mat r ices wit h posit ive d et er minant ; t hat is, t he set of all rot at ions
in 3-space. This mapping is one-t o-one on t he d omain (0, 1) (0, 1)
(0, 1). The algor it hm wor ks by r st const r uct ing a unit quat er nion from
t he t hree r and om var iables, t hen conver t ing t he qu at er nion int o an
or t hogonal mat r ix. If t he r and om var iables are ind epend ent and unifor mly
d ist r ibut ed in [0, 1], t he result ing rot at ions will also be unifor mly d is-
t r ibut ed .
Rand om_Rot at ion_Mat r ix(x
1
, x
2
, x
2
M)
x
1
, x
2
, x
3
: real ;
M: matri x3;
begi n
Use t he random variables x
1
and x
2
t o det ermine t he axis f r t at i n in
cylindrical coordinat es.
z: real x
1
;
: real 2x
2
;
r: real

1 z
2
;
Figur e 1.
356
VII.7 RANDOM ROTATION MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 356
end
Figure 1. (Cont inued)
See also 7.6 Quat er nions and 4 4 Mat r ices, Ken Shoemake;
(498) Using Quat ernions for Coding 3D Transf rmat i ns,
Pat rick-Gilles Maillot
Use t he random variable x
3
t o det ermine t he half-angle
rot at ion, , about t his axis.
: real x
3
;
Map (z, , r, ) t o a unit quat ernion (a, b, c, d).
a: real cos();
b: real sin() cos() r;
c: real sin() sin() r;
d: real sin() z;
Const ruct an ort hogonal mat rix corresponding t o (a, b, c, d).
This mat rix has posit ive det erminant , so it is a rot at i n.

M
1 2 c
2
+ d
2
( ) 2 bc + ad ( ) 2 bd ac ( )
2 bc ad ( ) 1 2 b
2
+ d
2
( ) 2 cd + ab ( )
2 bd + ac ( ) 2 cd ab ( ) 1 2 b
2
+ c
2
( )

]
]
]
]
]
357
VII.8 CLASSIFYING SMALL SPARSE MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 357
VII.8 VII.8 VII.8 VII.8 VII.8
C CC CCLASSIFYING SMALL SPARSE LASSIFYING SMALL SPARSE LASSIFYING SMALL SPARSE LASSIFYING SMALL SPARSE LASSIFYING SMALL SPARSE
M MM MMATRICES ATRICES ATRICES ATRICES ATRICES
James Arvo
Apollo Syst ems Division of Hewlet t -Packard
Chelmsf ord, Massachuset t s
Zer o St r uct ur es Zer o St r uct ur es Zer o St r uct ur es Zer o St r uct ur es Zer o St r uct ur es
Small mat r ices, such as 3 3 or 4 4, are ubiquit ous in comput er
gr aphics. They are used t o t r ansfor m ever yt hing from r ays and nor mal
vect or s in r ay t r acing t o vect or s and polygons in t r ad it ional d isplay list
processing. Because t hese mat r ices are oft en for med by concat enat ing
sever al simpler mat r ices, such as rot at ions, t r anslat ions, changes of scale,
and reect ions, t hey frequent ly cont ain a number of zero element s: i.e.,
t hey are frequent ly sparse. If a given spar se mat r ix is used for many
t r ansfor mat ions, it s zero st ruct ure can be exploit ed t o minimize t he t ot al
number of oat ing-point oper at ions. To d o t his, we propose t agging each
mat r ix wit h an int eger form index ind icat ing it s zero st r u ct u r e and
subsequent ly using t his ind ex t o br anch t o opt imized hand ler s for each
zero st r uct ure; t hat is, cod e in which t he zero ad d it ions and mult iplica-
t ions have been removed .
Because a 3 3 mat r ix has 2
9
, or 512, possible zero st ruct ures, near ly
half of which are guar ant eed t o be singular (247 of t hem, t o be exact ), it
would seem unreasonable t o supply special-pur pose cod e for ever y case.
A compromise is t o pick a small number of common zero st ruct ures and
opt imize only t hese. The frequency wit h which t hese spar se mat r ices ar ise
in a given applicat ion will d et er mine whet her using t he for m ind ex will
be benecial. However, because t he ad d ed cost of a br anch is t ypically ver y
small (d epend ing upon t he compiler and machine archit ect ure), t here is
lit t le t o lose and pot ent ially much t o gain in using t his approach.
For m ind ices also make it possible t o opt imize space by st or ing only
nonzero element s. However, it is oft en more convenient t o st ore t he full
358
VII.8 CLASSIFYING SMALL SPARSE MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 358
mat r ix because t his allows non-t ime-cr it ical cod e and preexist ing libr ar ies
t o oper at e on t hese mat r ices in t he nor mal fashion, oblivious t o zero
st r uct ures.
Cl assi f yi ng a Mat r i x Cl assi f yi ng a Mat r i x Cl assi f yi ng a Mat r i x Cl assi f yi ng a Mat r i x Cl assi f yi ng a Mat r i x
Figu re 1 enu mer at es a set of 16 common zero st r u ct u r es for 3 3
mat r ices. Includ ed are six permut at ions, t hree rot at ions, and t he seven
d ist inct for ms result ing from per mut ing t he rows and columns of t he
simple rot at ions. Not e t hat t he labels permut at ion and rot at ion per t ain
only t o t he st ruct ure and d o not imply t hat t he mat r ix is a t rue per mut a-
t ion or rot at ion. This can be d et er mined only by consid er ing t he values of
t he nonzero element s, which is unnecessar y for our pur poses.
Though we could d ed uce a zero st r uct ure for a mat r ix from t he zero
st r uct ures of it s component mat r ices and t he ord er of concat enat ion, it is
Figur e 1. Sixt een common zero st r uct ures for a 3 3 mat r ix
359
VII.8 CLASSIFYING SMALL SPARSE MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 359
far easier t o d o t his aft er t he mat r ix has been comput ed . This makes it
unnecessar y for t he mod eling oper at ions t o have any knowled ge of zero
st r uct ures, and it also t akes ad vant age of for t uit ous callcellat ions t hat
int rod uce ad d it ional zeros.
The algor it hm in Fig.2 is a fast and convenient way t o d et er mine which
of t he zero st ruct ures of Fig.1 apply t o a given 3 x 3 mat r ix. Rat her t han
using d eeply nest ed if-t hen-elses, which call be cumber some, t his proce-
Classify_Mat r ix(M):i nteger
M:Mat r ix3;
Begi n
Init ialize form by oring all possibilit ies t oget her.
for m:i nteger P
1
...P
6
R
*
C
1
...C
6
;
Eliminat e possibilit ies due t o non-zeros on t he diagonal.
i f M[0][0]

0 then for m for m(P


1
P
5
R
*
C
1
C
5
C
6
);
i f M[1][1]

0 then for m for m(P


1
P
6
R
*
C
1
C
2
C
3
);
i f M[2][2]

0 then for m for m(P


1
P
4
R
*
C
1
C
4
C
7
);
Eliminat e possibilit eis due t o non-zeros on t he diagonal.
i f M[0][1]

0 then for m for m(P


2
P
4
R
z
C
3
C
4
C
5
C
7
);
i f M[0][2]

0 then for m for m(P


3
P
6
R
y
C
1
C
2
C
3
C
6
C
7
);
i f M[1][2]

0 then for m for m(P


2
P
5
R
x
C
3
C
4
C
5
C
6
);
Eliminat e possibilit ies due t o non-zeros in t he loer t riangle.
i f M[1][0]

0 then for m for m(P


3
P
4
R
z
C
2
C
4
C
6
C
7
);
i f M[2][0]

0 then for m for m(P


2
P
6
R
y
C
1
C
2
C
3
C
4
C
5
);
i f M[2][1]

0 then for m for m(P


3
P
5
R
x
C
2
C
5
C
6
C
7
);
return[for m]
end
Figure 2. A funct ion for id ent ifying t he zero st ruct ure of 3 3 mat r ices. Here, means
bit wise-and, means bit wise-or, and R
*
is an abbreviat ion for (R
x
R
y
R
z
)
360
VII.8 CLASSIFYING SMALL SPARSE MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 360
d ure maint ains a bit -vect or of possible classicat ions, which is nar rowed
d own by examining each mat r ix element in sequ ence. Only nonzero
element s const r ain t he possible classicat ions because st ar red element s
may be anyt hing, includ ing zero. Thus, for each nonzero element , we
reset t he bit s cor respond ing t o for ms in which t hat element is zero. Any
reasonable compiler will replace t he or expressions in Fig. 2 wit h t he
equivalent const ant s at compile t ime.
Spar se_Mat _Vect _Mult (M, for m, a, b)
M:Matri x3;
for m:i nteger;
a:vector3;
b:vector3;
begi n
sel ect for m f rom
P
1
:begi n
b.x M[0][0] a.x;
b.y M[1][1] a.y;
b.z M[2][2] a.z;
end
P
2
:begi n
b.x M[2][0] a.x;
b.y M[0][1] a.y;
b.z M[2][2] a.z;
end
.
.
.
DENSE: Resort t o t radit ional mat rix mult iply
endcase
end
Figur e 3. A proced ure for mult iplying a spar se mat r ix by a vect or.
361
VII.8 CLASSIFYING SMALL SPARSE MATRICES
GRAPHICS GEMS II Edit ed by JAMES ARVO 361
Figu r e 3 shows how one might u se t he for m ind ex t o sp eed u p
ma t r i x-vect or p r od u ct s. Op er a t i on s su ch a s ma t r i x i n ver si on a n d
mat r ix-mat r ix mult iplicat ions can also enjoy t he ext r a infor mat ion sup-
plied by t he for m ind ex; but be war ned t hat in t he case of inver sion, most
but not all mat r ices have t he same zero st ruct ure as t heir inver ses. For
example, t he inver se of a P
2
mat r ix has t he for m of P
3
, and vice ver sa.
VIII
NUMERICAL AND
PROGRAMMING
TECHNIQUES
365
VIII NUMERICAL AND PROGRAMMING TECHNIQUES
GRAPHICS GEMS II Edit ed by JAMES ARVO 365
Comput er gr aphics is replet e wit h progr amming t r icks and careful numer-
ical t echniques, bot h of which d eal wit h t he myr iad mat hemat ical prob-
lems t hat ever y gr aphics progr ammer encount er s. Solut ions oft en come
from clever mat hemat ical id ent it ies, special numer ical algor it hms, and
shrewd progr amming. The gems of t his Par t present met hod s for count -
ing bit s, useful t r igonomet r ic id ent it ies, and met hod s for fast approxima-
t ions and evalu at ion of familiar fu nct ions su ch as squ are root and
arct angent , as well as t he more exot ic noise funct ion.
VIII VIII VIII VIII VIII
N NN NNUMERICAL AND UMERICAL AND UMERICAL AND UMERICAL AND UMERICAL AND
P PP PPROGRAMMING ROGRAMMING ROGRAMMING ROGRAMMING ROGRAMMING
T TT TTECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES
366
VIII.1 BIT PICKING
GRAPHICS GEMS II Edit ed by JAMES ARVO 366
VIII.1 VIII.1 VIII.1 VIII.1 VIII.1
B BB BBIT PICKING IT PICKING IT PICKING IT PICKING IT PICKING
Ken Shoemake
Ot t er Ent erprises
Palo Alt o, Calif ornia
One bit r ast er gr aphics is not d ead yet , and t he use of bit vect or s
probably will never d iewhich is merely an excuse t o propagat e one of
t he pret t iest lit t le hacks on a binar y comput er. Some comput er archit ec-
t ures, such as t he Mot orola 68020, includ e an inst ruct ion for nd ing t he
highest 1-bit set in a word , presumably t o assist in soft ware nor malizat ion
of oat ing-point oper at ion result s. This high 1 nd ing can be quit e hand y
for ot her bit vect or oper at ions as well. Find ing t he lowest 1-bit set in a
word is a d ifferent mat t er. However, using t he proper t ies of 2s-comple-
ment ar it hmet ic, it can be d one easily. Simply t ake t he bit -wise AND of t he
word and it s negat ive; t he result will be a word cont aining just t he lowest
1-bit . If n is exact ly a p ower of 2, t hen n = = (n& n) is TRUE,
ot her wise not . One example of t he use of t his t echnique is in st epping
t hrough 1 bit in a word , which is used t o record pixel cover age for
ant i-aliasing. Why d oes it wor k? Here is a pict ure (Table 1):
Table 1.
n 0 0 0 1 1 1 0 0 1 0 1 0 0 0 0 0
!n 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1
+1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
n 1 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0
n 0 0 0 1 1 1 0 0 1 0 1 0 0 0 0 0
n& n 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
367
VIII.1 BIT PICKING
GRAPHICS GEMS II Edit ed by JAMES ARVO 367
Remember t hat n in 2s-complement ar it hmet ic is !n + 1; car r y propa-
gat ion is effect ively d oing t he search.
See also VIII.3 Fast In-Line Manip u lat ions: Of Int eger s, Field s,
and Bit Count ing, Alan W. Paet h, David Schilling
368
VIII.2 FASTER FOURIER TRANSFORM
GRAPHICS GEMS II Edit ed by JAMES ARVO 368
VIII.2 VIII.2 VIII.2 VIII.2 VIII.2
F FF FFASTER FOU ASTER FOU ASTER FOU ASTER FOU ASTER FOURl Rl Rl Rl RlER TRANSFORM ER TRANSFORM ER TRANSFORM ER TRANSFORM ER TRANSFORM
Ken Shoemake
Ot t er Ent erprises
Palo Alt o, Calif ornia
Fast Four ier Tr ansfor m algor it hms have been explored pret t y t horoughly,
and var y from quit e t er se t o highly opt imized . It is not hard t o nd source
cod e, as in Press et al. (1988) or Bur r us and Par ks (1985). However,
t here is one t ask common t o ever y in-place algor it hm t hat can be mad e
fast er, namely, t he ipped bit count shufing of d at a t hat occur s before
or aft er t he t r ansfor m proper.
Hist or ically, folks have t r ied t o come up wit h clever ways eit her t o ip
t he bit s of an ord inar y count er or t o make a ipped count er ; but t here is
anot her possibly point ed out by Evans (1987). Not ice in Table 1 t hat ,
r st , all rear r angement s involve simply swapping pair s; and second , t hat
some ind ices d o not change (t he palindromes 000, 010, 101, and 111).
Bot h t hese proper t ies hold in larger cases as well, and suggest t r ying t o
gener at e only t he pair s t hat must be swapped . For a lengt h 1024 FFT,
t his means enumer at ing 496 ind icesless t han half t he t ot al.
When t he bit s are ipped , abcxyz t ur ns int o zyxcbaas, for example,
101011 becomes 110101and vice ver sa. A way t o avoid d uplicat ions
and palind romes can be found by split t ing t he bit s in half, as in 101 011.
When zyx is st r ict ly great er t han abc, zyxcba is st r ict ly great er t han
Table 1.
Decimal 0 1 2 3 4 5 6 7
Binar y 000 001 010 011 100 101 110 111
Binar y 000 100 010 110 001 101 011 111
Decimal 0 4 2 6 1 5 3 7
Ind ex
in
Ind ex
ou t
369
VIII.2 FASTER FOURIER TRANSFORM
GRAPHICS GEMS II Edit ed by JAMES ARVO 369
Figur e 1.
abcxyz, and cannot be a palind rome. A simple enumer at ion st r at egy for a
lengt h n = 2
2k
FFT t hus is possible:
shift = k >> 1; half = 1 << shift ;
h = k shift ;
for (low = 1; low + +; low < half) {
limit = ip (low, h); t op = limit << shift ;
for (high = 0; high + +; high < limit ) {
SWAP (d at a[(high << shift ) + low],
d at a[t op + ip (high, h)]);
}
}
More subt ly, t he same cod e wor ks when n = 2
2k+1
, because of t he way in
which h is comput ed . One fur t her speed up, now possible because only
small values of h will occur, is t o implement flip using a t able look-up.
For a 1024-point FFT, t he t able need hold only 32 ent r ies.
Why d oes t he cod e wor k for od d number s of bit s? Fir st , t he ipping,
shift ing, and ad d ing leave t he mid d le bit unchanged . Second , t he inner-
370
VIII.2 FASTER FOURIER TRANSFORM
GRAPHICS GEMS II Edit ed by JAMES ARVO 370
most loop gener at es bot h 0 and 1 for t he mid d le bit , so bot h cases are
con si d er ed . Fi n al l y, z yx0 st r i ct l y gr eat er t h an abcm i mp l i es z yx i s
st r ict ly great er t han abc, which st ill guar ant ees no d uplicat es or palin-
d romes. Figure 1 shows t he od d -bit s case; t he even-bit s case omit s t he m
bit in t he mid d le.
371
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 371
VIII.3 VIII.3 VIII.3 VIII.3 VIII.3
O OO OOF INTEGERS, FIELDS F INTEGERS, FIELDS F INTEGERS, FIELDS F INTEGERS, FIELDS F INTEGERS, FIELDS, ,, ,,
AND BIT COUNTING AND BIT COUNTING AND BIT COUNTING AND BIT COUNTING AND BIT COUNTING
Alan W. Paet h David Schilling
NeuralWare Inc. Sof t ware Consult ant
Pit t sburgh, Pennsylvania Bellevue, Washingt on
Inner loops common t o gr aphics cod e may benet from shor t , regist er -
based in-line cod e. These may exploit mixed ar it hmet ic-logical oper at ion
on int eger s t o achieve high per for mance at small cost . Two t echniques
useful for bit manipulat ion wit hin a single regist er are d escr ibed . The r st
increment s (d isjoint ) eld s wit hin machine word s; t he second t allies t he
number of bit s set . Bot h are helpful par t icular ly in manipulat ing RGB
pixels wit hin a single machine word wit hout resor t t o t he (re)packing of
each component , a valuable proper t y exploit ed elsewhere (Paet h, 1990a).
Basi cs Basi cs Basi cs Basi cs Basi cs
Consid er hard ware t hat represent s int eger s in t he near ly univer sal 2s-
complement binar y for m. Bit wise logical negat ion not () is an ar it hmet ic
1s-complement oper at ion, d iffer ing by one unit from ar it hmet ic negat ion
on su ch mach in es. Th ey may be equ at ed : n ot (A) = (A + 1).
Negat ing bot h sid es yield s an increment al for m; a d ecrement may be
d er ived in like manner :
A not (A) A A + 1,
A not (A) A A 1.
372
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 372
The lat t er p laces t he logical op er at ion ou t er most , allowing it t o be
absor bed fur t her. For inst ance, t he expression, X bi t-and (Y 1) and
equivalent X and-not (Y), become X bi t-cl ear ( Y) on archit ec-
t ures having only a bi t-cl ear (e.g., a Vax).
Count ing t hrough Bit s under Mask
A binar y int eger of 2
N
non-ad jacent bit s may be count ed (increment ed
t hrough it s 2
N
unique st at es) in simple fashion by using a mask of act ive
bit s. This sit uat ion commonly occur s when a machine word represent s a
color pixel of t hree ad jacent int eger s, most oft en byt es represent ing RGB
values. As an example, hexad ecimal mask 808080 has 3 bit s set . These
d ene t he most signicant bit s for each pr imar y in a 24-bit pixel d escr ip-
t or. Cou nt ing u p t hr ou gh t his scat t ered int eger gener at es t he eight
bound ing cor ner s of t he color cube at 50% int ensit y. Conver sely, t he 6-bit
mask of 030303 may d ene low-ord er unused dit her bit s when repre-
sent ing d at a having only 6 bit s per color channel on a 24-bit d isplay;
count ing und er t he second mask enumer at es all possible int er med iat e
d it her values.
A minimal implement at ion requires t wo r egist er s: a mask of t hose bit s
t hat are live in t he par t it ioned int eger, plus t he cur rent count value,
init ially zero. Successive values may be gener at ed using t he br ief fr ag-
ment :
count = count mask,
count = count bi t-and mask.
This for m combines logical and ar it hmet ic op er at ions t o achieve t he
d esired effect . The oper at ion is minimal in t hat no more t han t he t wo
or iginal regist er s are employed . Also, bot h machine inst ruct ions are of t he
compact t wo-op for m, regA op = regB.
To und er st and why t his wor ks, recall t hat subt r act ion of mask in t he
r st st at ement may be expressed as t he ad d it ion of t he 2s-complement of
mask. This for m may be represent ed in t ur n by t he 1s-complement of
373
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 373
mask plus 1: mask = not (mask) + 1. The rewr it e gives:
count = count + not (mask) + 1,
count = count bi t-and mask,
where t he unit const ant ser ves t o increment t he count . The inclusion of
not (mask) p r ovid es a car r y p at h across t hose bit s in mask t hat ar e
unoccupied , allowing low-bit car r y-out s t o ad vance t o t he car r y-in of t he
next act ive bit . The second st at ement zeros out car r y-chain scaffold ing,
t hereby vacat ing bit posit ions unused in regist er count . The cycle t hen is
read y t o repeat .
Tallying t he on on on on on bit s in an Int eger
Bit -t allying is a common t ool in a progr ammer s kit . In gr aphics scenar-
ios, it is used most oft en when t he t arget word represent s a por t ion of a
r ast er. For inst ance, consid er a binar y out put d evice in which on bit s
represent mar ks (e.g., a laser pr int er ). Tallying 1s in t he input d at a
st ream provid es an est imat e of t he local or global d ensit y of t he pr int .
Similar ly, count ing t he on bit s wit hin a 4 4 spat ial mask can conver t a
binar y r ast er of size 4N 4M int o a gr ayscale r ast er of size N M. In
bot h examples, a signicant por t ion of t he input may be off/ unmar ked : a
count ing met hod wit h cost propor t ional t o t he number of on bit s may be
benecial.
A st r aight for ward ap p roach emp loys byt e-ind exed t ables. Based on
machine ar chit ect u re and imp lement at ion sp ecics, t his may be t he
fast est t echnique.
Her e, a 256-ent r y t able ind exed by byt ewhose Nt h ent r y is t he
number of bit s present in it s byt e ind ex Nsolves t he problem for 8-bit
word s. For 32-bit long word s, t he word r st is broken int o 4 byt es. Each
is t allied using t he t able met hod . The four values t hen are summed . The
summing may be d one implicit ly by for ming t he remaind er mod ulo 255,
as explained at t he conclusion of t his gem. The t able met hod has const ant
cost , but st ill may lose t o t he following bit -based met hod s on machines
374
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 374
for which byt e alignment and ind exing are expensive, or when r ast er s are
ver y spar se or full, but not bot h.
A less int uit ive scheme wit h running t ime propor t ional t o t he number of
set bit s likewise may t ake ad vant age of mixed ar it hmet ic-logical oper a-
t ions. For sufcient ly spar se r ast er s, t his met hod oft en provid es asymp-
t ot ically bet t er running t ime:
i nteger functi on t ally(bit s)
count : i nteger 0;
whi l e (bit s < > 0)
begi n
bit s = bit s bi t-and (bit s l)
or use bit s = bit s bi t-cl ear (-bit s)
count = count + l
end
This algor it hm is st rongly suggest ive of t he r st it em in t his gem. Bit
anding any int eger wit h it s pred ecessor zeros t he r ight most bit set (up t o
and includ ing t he word s r ight most / least signicant bit ); for inst ance, t he
oper at ion, ABCD0300 bi t-and ABCD02FF = ABCD0200. Bit s t hen may be t al-
lied and d iscerd ed unt il t he word is zero.
For dense r ast er s whose word s have many bit s set , t he met hod like-
wise is fast : Given as 32-bit word W, t he complement ed word W may be
count ed and t he value 32 C(W) ret ur ned . A hybr id bipolar algor it hm
per for ming bot h t est s in line-by-line par allel has been suggest ed (Boot h,
1989) for fast symmet r ic per for mance. Here, each inner loop has t wice
t he cost , but t he cod e t er minat es at most in half t he number of st eps, as
no more t han half t he bit s can be bot h 1 and 0. This gives id ent ical
wor st -case per for mances and a chance t o end ear ly for word s t hat are
eit her empt y or full.
Analysis reveals a subt let y: The algor it hm gener ally is not useful. Even
wit h no penalt y for overhead in par allel execut ion, t his hybr id scheme is
slower on aver age by 1.73 t imes. This is a consequence of t he binomial
t heorem on t he d ist r ibut ion of bit s. For a 32-bit int eger of r and om bit
set t ings, t he number of pat t er ns having bet ween 15 and 17 bit s set (and
as many off) is 40.33%; most oft en, any algor it hm will t er minat e near t he
375
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 375
16t h cycle. Compar ing hybr id t o simple, t he for mer d oes t wice t he wor k
for each st ep. Put anot her way, t he t win halt ing cond it ions and associat ed
wor k buy lit t le improvement ; t hey t end t o occur at roughly t he same
moment .
Finally, count ing may be d one by viewing a long word as 32 1-bit
t allies. These are regrouped (by ad d it ion) as 16 2-bit t allies, cont inuing
for log
2
(word -lengt h) st eps, at which point a 32-bit t ally is left . This
met hod has many var iat ions; t hree are provid ed in t he C Implement at ion.
Once par t ial t allying has creat ed four ad jacent byt e count s (t he same
for mat as t he r st t ally algor it hm), a remaind er st ep may be employed t o
complet e t he t ask (Beeler et al., 1972). The mod ulus allows t he cast ing
out of N 1s in any base N > 2; t he d igit al root t est (d igit sums) for
d ivisibilit y by 9 in base 10 is a well-known example. In t he case at hand :
N = (d
3
d
2
d
1
d
0
) = d
i
2
8i
,
N mod 255 =

d
i
2
8i
mod 255
( )
i 0
3

]
]
]
mod 255,
= (d
3
+ d
2
+ d
l
+ d
0
) mod 255,
= (d
3
+ d
2
+ d
l
+ d
0
).
The last st ep d iscard s t he mod ulus, as t he value of t he sum at most is 32.
Per for ming t he mod ulus on eight hex d igit s would employ mod 15 and
int rod uces ambiguit y; an int erest ing, compact algor it hm employing t he
mod ulus 31 wit h minor cor rect ion for ambiguit y appear s as t he nal C
cod e algor it hm.
A pseud o-cod e example follows:

i 0
3

376
VIII.3 OF INTEGERS, FIELDS, AND BIT COUNTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 376
i nteger functi on t ally32(a)
a: unsigned long i nteger; a: 32 1-bit
t allies
begi n
mask = 1431655765; hex 55555555
a = (a bit-and mask) + (a rshift 1) bit-and mask; a: 16 2-bit tallies
mask= 858993459; hex 33333333
a = (a bit-and mask) + (a rshift 2) bit-and mask; a: 8 4-bit tallies
mask= 117901063; hex 07070707
a = (a bit-and mask) + (a rshift 4) bit-and mask; a: 4 8-bit tallies
return(a mod 255) sum t he byt es by
end cast ing out 255s.
on machines for which modulus is ex pensiv e, t he re turn may be
replaced wit h t his coda:
mask = 2031647; hex 001f001f
a = (a bi t-and mask) + (a rshi ft 8) bi t-and mask; a: 2 8-bit tallies
mask = 63;hex 0000003f
a = (a bi t-and mask) + (a rshi ft 16) bi t-and mask; a: 1 32-bit tally
return(a) d one.
end
See also VIII.1 Bit Picking, Ken Shoemake
377
VIII.4 USING GEOMETRIC CONSTRUCTION TO INTERPOLATE ORIENTATION WITH QUATERNIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 377
VIII.4 VIII.4 VIII.4 VIII.4 VIII.4
USING GEOMETRIC USING GEOMETRIC USING GEOMETRIC USING GEOMETRIC USING GEOMETRIC
C CC CCONSTRUCTIONS TO ONSTRUCTIONS TO ONSTRUCTIONS TO ONSTRUCTIONS TO ONSTRUCTIONS TO
I II IINTERPOLATE ORIENTATION NTERPOLATE ORIENTATION NTERPOLATE ORIENTATION NTERPOLATE ORIENTATION NTERPOLATE ORIENTATION
W WW WWITH QUATERNIONS ITH QUATERNIONS ITH QUATERNIONS ITH QUATERNIONS ITH QUATERNIONS
John Schlag
MacroMind, Inc.
San Francisco, Calif ornia
Quat er nions have been est ablished as a useful represent at ion for int er po-
lat ing 3D or ient at ion in comput er animat ion. In keeping wit h t r ad it ional
comp u t er animat ion p r act ices, we wou ld like bot h int er p olat ing and
ap p roximat ing sp lines. These can be d er ived easily by ap p lying t he
geomet r ic const ruct ions known for linear splines.
Shoemake (1985) provid ed a scheme for d er iving Bzier cont rol point s
from a sequence of quat er nions. This provid es an int er polat ing spline for
quat er nions, but t he const ruct ion is somewhat more complicat ed t han
necessar y. The most common int er polat ing spline in use probably is t he
Cat mull-Rom spline. In 1988, Bar r y an d Gol d man (1988) obl i gi n gl y
provid ed a geomet r ic const ruct ion for Cat mull-Rom splines. This pro-
d uces an int er polat ing spline d irect ly from t he cont rol point s, wit hout t he
const ruct ion of auxiliar y Bzier point s. For an approximat ing spline, a
geomet r ic const ruct ion for B-splines is well-known (d e Boor, 1972).
Bar r y and Gold man represent geomet r ic const ru ct ions as a t r iangle
wit h t he four cont rol point s at t he bot t om, t he result point at t he t op, and
weight ing funct ions for t he int er med iat e result s on each arc; for example,
378
VIII.4 USING GEOMETRIC CONSTRUCTION TO INTERPOLATE ORIENTATION WITH QUATERNIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 378
t he nonunifor m B-spline const ruct ion:
P
0
3
(t )

t
q+1
t
t
q+1
t
q

t t
q
t
q+1
t
q
P
2
1
(t ) P
0
2
(t )

t
q+1
t
t
q+1
t
q1

t t
q1
t
q+1
t
q1

t
q+2
t
t
q+2
t
q

t t
q
t
q+2
t
q
P
1
2
(t ) P
1
1
(t ) P
0
1
(t )

t
q+1
t
t
q+1
t
q2

t t
q2
t
q+1
t
q2

t
q+2
t
t
q+2
t
q1

t t
q1
t
q+2
t
q1

t
q+3
t
t
q+3
t
q

t t
q
t
q+3
t
q
P
3
P
2
P
1
P
0
This not at ion can be compressed consid er ably, since each pair of point s
is blend ed wit h coefficient s t hat sum t o one (i.e., t he point s are linear ly
int er polat ed , or lerped). By collapsing such coefficient s and d elet ing t he
point s, we get t he six-ent r y t r iangle:

t t
q
t
q+1
t
q

t t
q1
t
q+1
t
q1

t t
q
t
q+2
t
q

t t
q2
t
q+1
t
q2

t t
q1
t
q+2
t
q1

t t
q
t
q+3
t
q
In t he unifor m case (wit h knot values t
i
= i), t his red uces t o:
t

t + 1
2
t
2

t + 2
3

t + 1
3

t
3
379
VIII.4 USING GEOMETRIC CONSTRUCTION TO INTERPOLATE ORIENTATION WITH QUATERNIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 379
Similar ly, t he Cat mull-Rom const r uct ion is
t

t + 1
2

t
2
t + 1 t t 1
and t he Bezier const ruct ion is simply
t
t t
t t t
For ou r p u r p oses, t he most u sefu l consequ ence of exp ressing t he
const r uct ions as ler ping pair s of point s t oget her is t hat t hey can be
read ily ap p lied t o any d omain wher e an analog t o lerp exist s. For
quat er nions, t he analog t o ler p is slerp, for spher ical linear int er polat ion
(Shoemake, 1985):
sler p(q
1
,q
2
,u) =

sin 1 u ( )
sin
q
1
+
sin u
sin
q
2
, where cos = q
1
q
2
.
For example:
functi on qCat mullRom(
q00, q01, q02, q03: quat er nion; t : real
): quat er nion;
q10, q11, q12, q20, q21: quat er nion;
begi n
q10 sler p(q00, q01, t + 1);
q11 sler p(q01, q02, t );
q12 sler p(q02, q03, t 1);
q20 sler p(q10, q11, (t + 1)/ 2);
q21 sler p(q11, q12, t / 2);
return [sler p(q20, q21, t )];
endproc qCat mullRom
380
VIII.4 USING GEOMETRIC CONSTRUCTION TO INTERPOLATE ORIENTATION WITH QUATERNIONS
GRAPHICS GEMS II Edit ed by JAMES ARVO 380
The implement at ion of t he ot her const ruct ions d iffer s only in t he t hird
argument s t o sler p().
See also VII.6 Quat er nions and 4 4 Mat r ices, Ken Shoemake;
(498) Using Quat ernions for Coding 3D Transformat ions,
Pat rick-Gilles Maillot
381
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 381
VIII.5 VIII.5 VIII.5 VIII.5 VIII.5
A AA AA HALF-ANGLE HALF-ANGLE HALF-ANGLE HALF-ANGLE HALF-ANGLE I II IIDENTITY FOR DENTITY FOR DENTITY FOR DENTITY FOR DENTITY FOR
D DD DDIGITAL COMPUTATION IGITAL COMPUTATION IGITAL COMPUTATION IGITAL COMPUTATION IGITAL COMPUTATION: :: ::
T TT TTHE JOYS OF THE HALVED TANGENT HE JOYS OF THE HALVED TANGENT HE JOYS OF THE HALVED TANGENT HE JOYS OF THE HALVED TANGENT HE JOYS OF THE HALVED TANGENT
Alan W. Paet h
NeuralWare Inc.
Pit t sburgh, Pennsylvania
Tr igonomet r ic t r ansfor mat ions are common t o d ist ant cor ner s of gr aph-
ics, r anging from car t ogr aphy t o r ay t r acing. However, t he for mulae t hat
und er pin t heir relat ed algor it hms oft en make heavy use of t he basic
t r igonomet r ic funct ions t an , sin , or cos , t heir reciprocals, and oft en
t heir half-angle for ms. The values t ypically occur in pair s; [cos , sin ] is
a common example. Algor it hms employing par allel t r igonomet r ic expres-
sions may benet from a t r ansfor mat ion t hat expresses all t r igonomet r ic
for ms in t er ms of one: t an(/ 2). This gem d er ives t he half-angle id ent it y
and reveals a wid e var iet y of uses.
Tr igonomet r ic for mulae are d er ived convent ionally t hrough geomet r ic
means on a r ight t r iangle of unit hypot enuse. We subst it ut e an isosceles
t r iangle symmet r ic about t he x axis on t he Car t esian plane and proceed
by way of analyt ic geomet r y. It s t hree ver t ices are locat ed at t he or igin
and at a pair of conjugat e point s (Fig. 1).
Here, t he base is of lengt h 2y, t he congruent sid es are

x
2
+ y
2
. By
regard ing t hese common sid es as vect or s, t he cosine of t heir includ ed
angle is equated to their dot (inner) product, normalized by the product of
t heir lengt hs (Fig. 2a). Because t he cosine represent s t he quot ient of t wo
sid es (ad jacent over hypot enuse) in a convent ional r ight t r iangle, applica-
t ion of Pyt hagor ass t heorem nd s t he t hird sid e of t his rect ied t r iangle
(Fig. 2b). It likewise has base angle . Thu s, sin = 2xy/ x
2
+ y
2
,
t an = 2xy/ x
2
y
2
. Not e t hat t he sid e equat ions in Fig. 2b cont ain no
root s: They are int egr al for int egr als x and y. Figure 2b t hus red er ives
t he familiar gener at or of all Pyt hagorean t r iangles (Paet h, 1990c). All
r ight t r iangles of int eger sid es (solving t he familiar i
2
+ j
2
= k
2
) may be
382
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 382
d ened by at least one int eger pair (x, y). For inst ance, t he pair (2, 1)
yield s t he [3, 4, 5] Egypt ian t r iangle of ant iquit y.
Bisect ing t he angle in Fig. 1 shows t hat t an(/ 2) = y/ x. Set t ing
x = 1 in t he equat ions for bot h t angent and half-t angent provid e t he basis
of for mulae int er relat ing funct ions of t he angle and half-angle. Alt hough
half-angle id ent it ies of full angles are common (Glassner, 1990a), t heir
inver ses are infrequent ly t abulat ed . Reexpressing t he t r igonomet r ic id en-
t it ies for t he r ight t r iangle in Fig. 2b in t er ms of x = 1, T = y = t an / 2
yield s:
cos

1 T
2
1 + T
2
, sin

2T
1 + T
2
, t an

2T
1 T
2
,
cos

2
=

1
1 + T
2
, sin

2
=

T
2
1 + T
2
, t an

2
= T()
By subst it ut ing t he t r igonomet r ic value T = t an / 2 for t he angular value
Figure 2.
Figure 1.
383
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 383
Figur e 3. a) Circle wit h r ad ials; b) circle wit h fan.
, equat ions involving t he sine, cosine, and t angent of may proceed
wit hout resor t ing fur t her t o r ad icals or t r ig libr ar ies; four-funct ion hard -
ware oat ing-point oft en sufces. The savings can be subst ant ial, as when
large (hemispher ical) car t ogr aphic [lat ,lon] d at a set s are precomput ed
off-line und er t he t r ansfor mat ion T. In t his case, fur t her savings exist
when t he half-t angent for m appear s explicit ly, as wit h Mercat or s confor-
mal project ion (Paet h, 1990c), or wit h t he st ereogr aphic confor mal pro-
ject ion, which follows.
The for m [cos, sin] is bound int imat ely t o t he unit circle by t he
found at ional id ent it y e
i
= cos + i sin . By t his expression, t he com-
plex Nt h root s of unit y for m t he ver t ices of a regular N-gon. Because
T() subst it ut es so freely for [cos, sin], int uit ion suggest s a geomet r ic
mod el involving t he half-angle and a circle, analogous t o t he convent ional
mod el. Bot h appear in Fig. 3.
A const ant rot at ion in Fig. 3a yield s linear circumferent ial mot ion.
Remar kably, t he same is t rue in Fig. 3b, where a viewer at t he ed ge need
t ur n at only half t he r at e and t hrough a half-circumference, while viewing
t he same inst ant aneous hor izon as a cent r al obser ver in Fig. 3a. In shor t ,
a chord s angular subt ense t o a point anywhere on t he circles per imet er
is half t he angular subt ense at t he cent er. A geomet r ic proof (omit t ed )
const r uct s congruent isosceles t r iangles t hat have t he circles base and
cent er in common, but which have d ifferent point s along t he per imet er.
Euclid d er ives a gener al case; a lucid account appear s in Polya (1962).
384
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 384
The id ent it ies given allow t he familiar r eexp ression of p ar amet r ic
circu lar p lot t ing t hrou gh r at ional p olynomials. Here, t he LHS is t he
familiar unit vect or of rot at ion wit h = 2 arct an(T) subst it ut ed . The RHS
may be d er ived from t he t ables previously given, yield ing:
[cos(2 arct an(T)),sin(2 arct an(T))] =

1 T
2
1 + T
2
,
2T
1 + T
2

]
]
]
,
as appear ing in Newman and Sproull (1979) and elsewhere. When T is a
half-t angent funct ion of angle a, t he circumferent ial mot ion is unifor m.
When T is t aken as t he (linear ) ind epend ent par amet er, t he angular r at e
is no longer const ant , but d oes not d eviat e consid er ably; The half-t angent
is st rongly linear t hrough much of it s d omain, as seen by t he Taylor
expansion of bot h t he funct ion and it s inver se about x = 0:
2T(x) = 2 t an

x
2
|
.

`
,
= x +

1
12
x
3
+

1
120
x
5
+ O(x)
7
,
2 arct an

x
2
|
.

`
,
= x

1
12
x
3
+

1
80
x
5
+ O(x)
7
.
This reveals t he alt er nat e for ms 2 t an(x/ 2) and 2 arct an(x/ 2), which
may be employed preferent ially t o inher it t he valuable proper t y x 0
F(x) x, shar ed by sin(x) and t an(x). This for m is familiar t o t he
geomet r y of viewpor t specicat ion and , more gener ally, t o problems of
geomet r ic opt ics: 2 t an(/ 2) relat es an angular eld of view t o a linear
eld viewed at a unit d ist ance. This occur s oft en enough t o mer it an
example.
A 35 mm for mat camer a (wit h 1.5 : 1 aspect r at io giving a 42 mm lm
d iagonal) equipped wit h a 210 mm t elephot o lens has a eld -d ist ance
r at io of 42 : 210 = 1/ 5. Subst it ut ion int o t he second Taylor expansion
gives t he angular eld : 2 t an
1
(1/ 10) ~ 2/ 10 r ad ians ~ 11.4 (half-eld
if t he lead ing 2 is omit t ed ). Here, merely t he approximat ions r st t er m is
ret ained , as t he eld is nar r ow.
Int er est ingly, a nonrect ilinear sh-eye lens enforces t his ap p roxima-
t ion at wid e angles; angular eld d ist ance t hen gives linear d isplacement
385
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 385
at t he lm plane, allowing t he imaging of a hemispher ical ext ent (or
more) in cases where an id eal pinhole lens would require an innit e lm
plane.
The close relat ion bet ween t he half-t angent and t he convent ional rot a-
t ion for m [cos , sin ] also may be implicit . For inst ance, r ast er rot at ion
using shear ing (Paet h, 1990a) employs t hree 2 2 id ent it y mat r ices,
each wit h one off-d iagonal, nonzero element . This element is t an(/ 2)
for t he cent r al mat r ix, br acket ed by mat r ices having sin on t he off-
d iagonal. Not sur pr isingly, t he algor it hm ad mit s par t icular ly accur at e
special cases when t he off-d iagonals are small r at ionals. These are relat ed
d irect ly t o Pyt hagorean for ms (Paet h, 1990c). In par t icular, t he gener at or
pair (1, 1) yield s a flat r ight t r iangle wit h sid es (0, 1, 1), allowing for
90-d egree rot at ion of all int eger coefficient s as a well-known special case
(Guibas and St ol, 1982).
This mod el reveals ot her d omains in which t he half-t angent appear s.
The d r awing in Fig. 3b is suggest ive of t he Lamber t ian r ad iosit y mod el,
which char act er izes id eal d iffuse reect ive sur faces. This specic mod el
also may be ext end ed t o 3-space by rot at ion about an axis cont aining t he
base point and cent er of t he opposit e chord . The lat t er becomes a circle
(all p oint s of common su bt ense) on t he sp here, while it s p roject ion
remains circu lar. This illu st r at es t he basis of t he st ereogr ap hic p olar
project ion (Paet h, 1990d ). A plot (Paet h, 1990d , Fig. 5) illust r at es t he
remar kable proper t y unique t o t his confor mal mapping: Circles are pre-
ser ved und er t r ansfor mat ion bet ween char t and globe. The equat ion t hat
relat es azimu t hal char t d ist ance t o sp her ical su bt ense is 2 t an(/ 2),
where is co-lat it ud e (zero at t he pole).
Elsewhere, t he funct ion is useful in problems of gener al t r igonomet r y.
A concise id ent it y (Glassner, 1990a) relat es t he half-t angent s of t wo base
angles in a plane t r iangle t o t he r at io of t heir respect ive legs (Fig. 4a).
Ext ension t o oblique spher ical t r iangles necessar ily ad d s a t r igonomet r ic
for m: The legs of spher ical t r iangles are measured in t er ms of angular
subt ense. Anot her int r od uct ion of t he half-t angent sufces (Fig. 4b).
Figure 4. a) Planar ; b) spher ical.
386
VIII.5 A HALF-ANGLE IDENTITY FOR DIGITAL COMPUTATION: THE JOYS OF THE HALVED TANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 386
From a comput at ional point of view, t he funct ion T(x) = t an(x/ 2) is
d esir able becau se it is od d -valu ed : T(x)= T(x ). In cont r ast , even
funct ions such as cos(x) and

x d iscard xs sign. Similar ly, t r ansfor ma-
t ions involving t he square root int rod uce a sign ambiguit y, recovered
t hrou gh cu mber some for ms su ch as sign(x)

F x ( ) . Und er su bst it u t ion,
T(x) remains su p er ior t o ot her od d t r igonomet r ic fu nct ions, su ch as
S = sin (x), wh ose exp r ession of t h e cosin e, cos(x) =

1 S
2
( ) , is
unst able for S ~ 1. However, t here are ot her means t o for m [cos, sin] in
par allel wit h high accur acy, e.g., Cord ic t echniques (Tur kowski, 1990).
T() moves the tangents bothersome singularity at t/ 2 outward to
t: the function is dened on the entire circumferential domain
( . . . + ), where its range is [ . . . ]. Note that the point-at-innity
is a pole having no sign; this is suggested by the stereographic projections
antipodal point, which lies in no unique direction away from the chart
origin. In many cases, a half-circle or hemispherical domain sufces for T
and the range then is the convenient [1. . .1], as was seen in the
rational-parametric circle drawer. The likewise may be removed from
the domain by reexpressing T(x) in circumferential units (Shoemake,
1990).
It is ironic t hat t r igonomet r ic id ent it ies based on a single for m are not
more common t od ay. In t imes past , problems of navigat ion and ast ron-
omywhich p rovid ed mat hemat ics many of it s r ichesp referent ially
employed half-angle for ms, such as t he haver sine (hav(x) = 1/ 2 ver s(x)
= 1/ 2[1 cos x] = sin
2
x/ 2 = T
2
/ 1 + T
2
). By t hese, t he r eckoner of
a ships company could (among his ot her d ut ies) navigat e d ur ing ad ver se
circumst ances wit h reference merely t o sums and t o a single t able. Tod ay,
a misplaced sign has less d ire consequences (usually!) for t he reckoner.
St ill, t he oppor t unit y t o opt imize cod e u nd er a u nied mod el while
implicit ly account ing for t he bot her some ambiguit ies of four-quad r ant
t r igonomet r y is not ignored easily.
387
VIII.6 AN INTEGER SQUARE ROOT ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 387
VIII.6 VIII.6 VIII.6 VIII.6 VIII.6
A AA AAN NN NN I II IINTEGER SQUARE ROOT NTEGER SQUARE ROOT NTEGER SQUARE ROOT NTEGER SQUARE ROOT NTEGER SQUARE ROOT
A AA AALGORITH LGORITH LGORITH LGORITH LGORITHM MM MM
Christ opher J. Musial
New Horizons Sof t ware
St . Louis, Missouri
Some algor it hms t hat per for m a square root oper at ion may requir e only
t he int eger por t ion of t he result , r at her t han t he ent ire oat ing-point
number. An example may be ar r anging a list of it ems int o a nearly
square t able: The t able will have t he same number of rows and columns,
wit h t he last r ow/ colu mn p ossibly being emp t y or incomp let e. The
overhead of a full oat ing-point calculat ion is not necessar y in t his case.
The algor it hm present ed here calculat es t he largest int eger, which is less
t han or equal t o t he square root of a given int eger n, i.e.,

n ].
Given n as t he number for which t he square root is required and s as
t he int eger square root we are seeking, it er at ively per for m t he oper at ion,
S
i+1


s
i
+
x
s
i
2
,
unt il s
i+l
becomes great er t han or equal t o s
i
, at which point s
i
is t he
int eger square root we are seeking. Pr ior t o st ar t ing t he it er at ion, s
i
is
assigned t he value n/ 2. Not e t hat t he d ivisions are car r ied out in int eger
ar it hmet ic. The pseud o-cod e for t his proced ure is:
procedure isqr (n: unsi gned l ong i nt);
begi n
next Tr ial: unsi gned i nt n/ 2;
cur rent Answer ;
388
VIII.6 AN INTEGER SQUARE ROOT ALGORITHM
GRAPHICS GEMS II Edit ed by JAMES ARVO 388
i f n 1 then return [n];
do
begi n
cur rent Answer next Tr ial;
next Tr ial (next Tr ial + n/ next Tr ial)/ 2;
end;
unti l next Tr ial cur rent Answer ;
return [cur rent Answer ];
end;
See a l so (424) A High Speed, Low Precision Square Root ,
Pau l Lal on de, Robert Dawson
389
VIII.7 FAST APPROXIMATION TO THE ARCTANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 389
VIII.7 VIII.7 VIII.7 VIII.7 VIII.7
F FF FFAST APPROXIMATION TO AST APPROXIMATION TO AST APPROXIMATION TO AST APPROXIMATION TO AST APPROXIMATION TO
T TT TTH HH HHE E E E E ARCTANGENT ARCTANGENT ARCTANGENT ARCTANGENT ARCTANGENT
Ron Capelli
IBM Corp.
Poughkeepsie, New York
Given t he component s of a vect or (dx, dy), t he inver se t r igonomet r ic
arct angent funct ion is used t o d et er mine precisely t he angle t hat t he
vect or makes wit h respect t o t he x axis. The funct ion arct an2(dy, dx) is
provid ed in many progr am libr ar ies so t hat t he funct ion can be d ened
for all values of dx and dy (except t he single case where bot h dx and
dy are zero).
A useful measure of vect or angle can be const ruct ed by a piecewise
cont inuous funct ion, using only t hree compar isons, one d ivision, and one
or t wo ad d / subt r act oper at ions. This represent s signicant ly fewer oper-
at ions t han a st and ard implement at ion of arct an2.
The segment s of t he piecewise cont inuous funct ion are d et er mined by
t he oct ant in which t he vect or lies. The oct ant can be d et er mined by t hree
compar isons of dx wit h respect t o 0, dy wit h respect t o 0, and dx wit h
resp ect t o dy. For oct ant s where abs(dx) > abs(dy), dy/ dx is evalu -
at ed . For oct ant s where abs(dx) < abs(dy), dx/dy is evaluat ed . Finally,
so t hat t he segment s join wit h bot h C
0
and C
1
cont inuit y, t he absolut e
value of t he quot ient is subt r act ed from 1 for t he od d oct ant s, and t he
oct ant number is ad d ed t o t he result . This algor it hm is summar ized in
Fig. 1, wit h t he compar isons sat ised for each oct ant shown insid e t he
circle, and t he p iecewise fu nct ion evalu at ion for each oct ant shown
out sid e t he circle.
Figure 2 is a gr aph of t he funct ion for all angles. The funct ion is
monot onically increasing, so it is id eal for use as a key for sor t ing vect or s
by angle. Such a sor t , for example, is used in d et er mining t he convex hull
of a set of point s using Gr ahams scan algor it hm (Gr aham, 1972; Lee and
Prepar at a, 1984).
390
VIII.7 FAST APPROXIMATION TO THE ARCTANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 390
Figure 2. Gr aph of piecewise cont inuous funct ion.
Figur e 1. Oct ant s and piecewise funct ion evaluat ion.
391
VIII.7 FAST APPROXIMATION TO THE ARCTANGENT
GRAPHICS GEMS II Edit ed by JAMES ARVO 391
Figur e 3. Gr aph of arct angent approximat ion er ror.
As present ed , t his funct ion ret ur ns a value great er t han or equal t o
zero, and less t han 8. This r ange oft en is useful as is, or it can be
remapped easily t o r ad ians (or d egrees) t o provid e an appr oximat ion t o
t he arct angent . Figure 3 is a gr aph of t he er ror of t he approximat ion. The
maximum er ror is less t han 4.1 d egrees, just over 1% of a full circle.
Thus, t he approximat ion is safe for point -in-polygon t est ing using alge-
br aic sums of angles when t he number of polygon ver t ices is small.
392
VIII.8 FAST SIGN OF CROSS PRODUCT CALCULATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 392
VIII.8 VIII.8 VIII.8 VIII.8 VIII.8
F FF FFAST SIGN OF CROSS AST SIGN OF CROSS AST SIGN OF CROSS AST SIGN OF CROSS AST SIGN OF CROSS
P PP PPRODUCT CALCULATION RODUCT CALCULATION RODUCT CALCULATION RODUCT CALCULATION RODUCT CALCULATION
Jack Rit t er
This gem provid es a quick met hod of d et er mining t he sign of a 2D cross
prod uct . (If t he plane d ened by t he t wo vect or s is a gener al 3D plane, a
t r ansfor mat ion t hat aligns t he plane t o one of t he t hree coord inat e planes
should be pre-applied t o all point s, t o conver t t he problem int o 2D.) In
comput er gr aphics, t here are many cases where t he cross prod uct is
comput ed , but only t he sign is really need ed . Four such cases are:
1. Back face culling (in screen space).
2. Det er mining t he wind ing, or hand ed ness, of t wo consecut ive ed ges in
a polygon, or looking at all consecut ive pair s t o d et er mine whet her
t he polygon is convex (e.g., if all signs agree). Hand ed ness also is
refer red t o as int o/out of t he page.
3. Det er mining t he t wo out er cor ner s of a pair of 2D wid e lines joined at
t he end s, so as t o ll in t he hole wit h a bevel joint , mit ered joint , et c.
4. Det er mining if a point is insid e a t r iangle.
Typically, t he full cross prod uct is comput ed , and compared t o zero.
The calculat ion of a oat ing-point 2D cross prod uct is of t he for m:
a*b c*d,
where t wo fp mult iplicat ions, one fp subt r act ion, and one fp compare (t o
0) are need ed . This can be simplied by conver t ing t he problem int o xed
p oint , and looking at t he signs of a, b, c, and d, before d oing t he
mult iplicat ion. Half t he t ime, no mult iplicat ions are necessar y, and t he
393
VIII.8 FAST SIGN OF CROSS PRODUCT CALCULATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 393
ot her half of t he t ime, t wo xed-point , 16-bit mu lt ip licat ions are r e-
quired . To conver t a fp number t o a xed point , scaling oft en is neces-
sar y. The algor it hm uses signed shor t int eger s, so t he fp number s should
scale t o t he ord er of: 32K 32K. This guar ant ees t hat only 16 16
xed -point mult iplicat ions will be compiled , and not calls t o complex
mat h rout ines (like _lmul). The C Implement at ion (Append ix 2) uses a
scaling of 16384; e.g., t he or iginal fp number s are assumed t o be in t he
r ange of 1.0 1.0. The scale fact or always should be a power of 2, so
t he compiler gener at es a fp shift , and not a fp mult iplicat ion.
Somet imes, t he quant it ies a, b, c, and d are known only as relat ive
d ifferences (e.g., a2 a1 inst ead of a). In t hese cases, it might be wor t h
it t o pass all eight oat ing-point number s t o t he rout ine, conver t all eight
t o xed point , and t hen d o t he four subt r act ions in xed point .
394
VIII.9 INTERVAL SAMPLING
GRAPHICS GEMS II Edit ed by JAMES ARVO 394
VIII.9 VIII.9 VIII.9 VIII.9 VIII.9
I II IINTERVAL SAMPLING NTERVAL SAMPLING NTERVAL SAMPLING NTERVAL SAMPLING NTERVAL SAMPLING
Ken Shoemake
Ot t er Ent erprises
Palo Alt o, Calif ornia
To sample an int er val evenly wit h a pred et er mined number of point s is
easy. Sampling evenly when t he number of point s need ed is not known in
ad vance is less obvious. What is need ed is a sequence of point s t hat
breaks t he int er val up as evenly as possible wit h each new point . Ramshaw
(1978) showed one special way t o d o t his is opt imal accord ing t o sever al
d ifferent cr it er ia. For simplicit y, assume your int er val is t he unit int er val.
(A simple linear map t (b a)t + a will conver t from [0. . .1] t o
[a. . .b].) Th en t h e sequ en ce of samp l e p oi n t s x
k
i s gi ven by x
k
=
(log
2
(2k + 1)) mod 1.0, where mod ulo 1.0 means t o t ake t he fr act ional
par t . Here in t he accompanying t able are t he r st few samples:
395
VIII.9 INTERVAL SAMPLING
GRAPHICS GEMS II Edit ed by JAMES ARVO 395
Figure 1.
Fi gu r e 1 i s a gr a p h i ca l d ep i ct i on of t h e p a r t i t i on i n g obt a i n ed . For k
sample point s, t he fr agment s obt ained are all roughly of lengt h 1/ (k + 1).
396
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 396
VIII.10 VIII.10 VIII.10 VIII.10 VIII.10
A AA AA RECURSIVE RECURSIVE RECURSIVE RECURSIVE RECURSIVE
I II IIMPLEMENTATION OF THE MPLEMENTATION OF THE MPLEMENTATION OF THE MPLEMENTATION OF THE MPLEMENTATION OF THE
P PP PPERLIN NOISE FUNCTION ERLIN NOISE FUNCTION ERLIN NOISE FUNCTION ERLIN NOISE FUNCTION ERLIN NOISE FUNCTION
Greg Ward
Lawrence Berkeley Laborat ory
Berkeley, Calif ornia
Since it s int rod uct ion at SIGGRAPH 85, Ken Per lins t hree-d imensional
noise funct ion has found it s way int o a great many rend erer s (Per lin,
1985). The id ea is t o creat e a basis funct ion t hat var ies r and omly bet ween
1 and 1 t hroughout 3-space wit h an aut ocor relat ion d ist ance of about 1
in ever y d irect ion. Such a funct ion can ser ve as t he build ing block for a
wid e var iet y of proced ur al t ext ures. An ad d it ional proviso of t he Per lin
noise funct ion is t hat it should not have pronounced har monics; i.e., it
should look like a sine funct ion wit h a wiggling amplit ud e and no or igin
(Fig. 1). This enables t he progr ammer t o build up almost any d esired
random function by summing harmonics of the basic function, similar to a
Fourier reconstruction.
There is no one cor rect way t o wr it e a r and om noise funct ion, but some
approaches are simpler or more efcient t han ot her s. One popular ap-
proach, suggest ed by Per lin in his 1985 paper, is t o use r and om values
and gr ad ient s assigned t o a rect ilinear gr id t hroughout 3-space, t hen
int er polat e bet ween t hem using Her mit e splines. Alt hough t his d oes not
prod uce a funct ion t hat is complet ely free of rot at ional biases, it is good
enough for most rend er ing applicat ions. The C Implement at ion (Append ix
II) is based on t his simple approach.
The init ial requ ir ement of t he imp lement at ion is a map p ing from
int eger 3-space t o r and om gr ad ient s and values, for which t here are t wo
basic approaches. The r st approach is t o use a hashing funct ion t o map
int eger t r iplet s t o a (possibly small) t able of r and om number s. The second
approach is t o use some unifor mly d ist r ibut ed r and om funct ion of t hree
int eger s. The r st met hod t end s t o be fast er and more reliable, alt hough
397
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 397
Figure 1. Per lin noise funct ion.
t he second met hod has t he pot ent ial t o prod uce more r and om result s (but
be carefulit is much easier t o wr it e a bad r and om funct ion t han one
might t hink!). Once an algor it hm has been chosen for assigning r and om
vect or s wit h component s bet ween 1 and 1 t o int eger lat t ice point s,
Her mit e int er polat ion can be used t o comput e t he funct ion value at any
point in 3-space.
The following pseud o-cod e funct ion ret ur ns a r and om real value be-
t ween 1 and 1 based on a single int eger argument . Since it s value from
one int eger t o t he next essent ially is uncor relat ed , r and om funct ions of
more argument s can be const r uct ed by using a sum of pr ime mult iples as
sh own for t h e ma r cr os rand3a, rand3b, rand3c, a n d rand3d t h a t
follow.
398
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 398
Frand: ret urn a pseudo-random real bet ween 1 and 1 from an int eger seed
The following assumes a 32-bit t wos-complement int eger archit ect ure
MAXINT: i nteger 1shift (1,32)-1; All ones except sign bit
functi on fr and (s: i nteger): real ;
begi n
First , hash s as a prevent ive measure
s 1shift (s,13) bi t-xor s;
Next , use a t hird order odd polynomial, bet t er t han linear
s (s*(s*s*15731 + 789221) + 1376312589) bi t-and MAXINT;
Convert result t o 1 t o 1 range
r val 1.0 s*2.0/ MAXINT;
return r val;
end; End of frand
Dene macros for different random funct ions of 3 int egers:
macro r and 3a(x,y,z) fr and (67*(x) + 59*(y) + 71*(z))
macro r and 3b(x,y,z) fr and (73*(x) + 79*(y) + 83*(z))
macro r and 3c(x,y,z) fr and (89*(x) + 97*(y) + 101*(z))
macro r and 3d (x,y,z) fr and (103*(x) + 107*(y) + 109*(z))
In our implement at ion of t hree-d imensional Her mit e int er polat ion, re-
cu r si on i s u sed t o r ed u ce t h e a p p a r en t comp l exi t y. A si n gl e
funct ionwhose job is t o int er polat e point s and t angent s in N d imen-
sionsis wr it t en. If N is great er t han 0, t hen it calls it self on each half of
t he next lower-ord er funct ion (N 1) and int er polat es t he result s wit h a
Her mit e cubic funct ion. If N is 0, t hen t he funct ion simply ret ur ns t he
point and t angent vect or at t he specied cor ner from t he r and om lat t ice
mapping.
Figure 2 shows eight lat t ice point s sur round ing a point in 3-space. The
r and om values at t hese point s are used t o comput e four point s int er po-
lat ed in x, which in t ur n are int er polat ed in y, t hen in z t o comput e t he
nal value.
The following pseud o-cod e implement s t his algor it hm. A macro d enes
t he Her mit e polynomial, and a home base rout ine assigns global var iables
and calls t he recur sive funct ion t hat per for ms t he act ual int er polat ion.
399
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 399
One-dimensional Hermit e polynomial:
macro her mit e(p0,p1,r 0,r 1,t )(p0*((2.*t 3.)*t *t + 1.) +
p1*(2.*t + 3.)*t *t +
r 0*((t 2.)*t + 1.)*t +
r 1*(t 1.)*t *t )
Global variable for t he cube cont aining t he point :
xlim: array [0..2] of array [0..1] of i nteger;
Figur e 2.
400
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 400
Global variable for t he fract ional part s for each coordinat e:
xarg: array [0..2] of real ;
Dene t ype for gradient plus value in 4D array
Gr ad V: array [0..3] of real ;
funct ion noise3(x: poi nt): Gr ad V;
nval: Gr ad V;
begi n
Assign global variables for cube and fract ional part
xlim[0][0] oor (x[0]);
xlim[0][1] xlim[0][0] + 1;
xlim[l][0] oor (x[1]);
xlim[l][1] xlim[1][0] + 1;
xlim[2][0] oor (x[2]);
xlim[2][1] xlim[2][0] + 1;
xarg[0] x[0] xlim[0][0];
xarg[1] x[1] xlim[1][0];
xarg[2] x[2] xlim[2][0];
Call recursive int erpolat ion funct ion
int er polat e(f, 0, 3);
return nval;
end; End of noise3
Int erpolat e n-dimensional noise funct ion
int er polat e(var f: Gr ad V; i, n: i nteger)
f0, 1: Gr ad V; result s for rst and second halves
begi n
i f n = 0
then begi n at zero, just ret urn lat t ice value
f[0] r and 3a(xlim[0][i bi t-and 1],
xlim[1][r shift (i, 1) bi t-and 1],
xlim[2][r shift (i, 2)]);
f[l] r and 3b(xlim[0][i bi t-and 1],
xlim[1][r shift (i, 1) bi t-and 1],
xlim[2][r shift (i, 2)]);
401
VIII.10 A RECURSIVE IMPLEMENTATION OF THE PERLIN NOISE FUNCTION
GRAPHICS GEMS II Edit ed by JAMES ARVO 401
f[2] r and 3c(xlim[0][i bi t-and 1],
xlim[1][r shift (i, 1) bi t-and 1],
xlim[2][4shift (i, 2)]);
f[3] r and 3d (xlim[0][i bi t-and 1],
xlim[1][r shift (i, 1) bi t-and 1],
xlim[2][r shift (i, 2)]);
return,
end;
n n 1; decrease order
int er polat e(f0, i, n); comput e first half
int er polat e(f1,i1 n,n); comput e second half
use linear int erpolat ion for slopes
f[0] ler p(xarg[n], f0[0], f1[0]);
f[1] ler p(xarg[n], f0[1], f1[1]);
f[2] ler p(xarg[n], f0[2], f1[2]);
use hermit e int erpolat ionfor value
f[3] her mit e(f0[3], f1[3], f0[n], f1[n], xarg[n]);
end; End of int erpolat e
Thanks t o t his algor it hms recur sive nat ure, it is easy t o ext end it t o
noise funct ions of higher d imensions. One only would need t o ad d ext r a
gr ad ient component s t o t he r and om number lat t ice mapping and increase
t he number of linear int er polat ions a like amount .
The aut hor s exper ience wit h t his implement at ion has proven it t o be
bot h fast and reliable, prod ucing pleasing pat t er ns wit hout d iscer nible
repet it ion or st at ist ical bias.
I X
CURVES AND
SURFACES
405
IX CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 405
IX IX IX IX IX
C CC CCURVES AND URVES AND URVES AND URVES AND URVES AND
S SS SSURFACES URFACES URFACES URFACES URFACES
The gems of t his Par t explore sever al t heoret ical and pr act ical aspect s of
cur ves and sur faces. The r st four gems provid e new t echniques for
efficient evaluat ion and manipulat ion of polynomial represent at ions, such
as t hose based on Bzier cur ves. These are comput at ionally convenient
and provid e a fair ly compact means of represent ing complex sur faces.
The last t hree gems focus on cur ves relat ed t o t he circle. It may be
sur pr ising t hat int erest ing and challenging problems remain even in t his
simple and familiar shape, but wit hin t he realm of comput er gr aphics,
t here always will be a need t o d r aw circles and arcs wit h increasing speed
and d elit y. Toward t his end , t he nal gems ad d ress approximat ion of
circular arcs, plot t ing great circles, and ant i-aliasing of circles.
4 0 6
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 0 6
IX.1 IX.1 IX.1 IX.1 IX.1
LEAST-SQUARES LEAST-SQUARES LEAST-SQUARES LEAST-SQUARES LEAST-SQUARES, ,, ,,
A AA AAPPROXIMATIONS TO BZIER PPROXIMATIONS TO BZIER PPROXIMATIONS TO BZIER PPROXIMATIONS TO BZIER PPROXIMATIONS TO BZIER
C CC CCURVES AN URVES AN URVES AN URVES AN URVES AND D D D D SURFACES SURFACES SURFACES SURFACES SURFACES
Doug Moore and Joe Warren
Rice Universit y
Houst on, Texas
Pr obl em Pr obl em Pr obl em Pr obl em Pr obl em
In comput er gr aphics, t he need t o approximat e a high-d egree cur ve or
sur face by a lower-d egree cur ve or sur face oft en ar ises. One popular
met hod used t o select approximat ions is t he least -squares t echnique. This
gem d iscusses t he use of least -squares t o prod uce opt imal approxima-
t ions of lower d egree t o Bzier cur ves and sur faces.
Uni var i at e Appr oxi mat i on Uni var i at e Appr oxi mat i on Uni var i at e Appr oxi mat i on Uni var i at e Appr oxi mat i on Uni var i at e Appr oxi mat i on
Let p(t ) be a polynomial of d egree n wr it t en in Ber nst ein basis for m:
p(t ) =

j 0
n
p
j
B
n
j
(t).
Here, t he Ber nst ein basis funct ions B
n
j
(t ) are of t he for m:
B
n
j
(t ) =

n!
j !(n j)!
t
j
(1 t )
n j
We wish t o comput e a polynomial q(t ) of d egree m,
q(t ) =

j 0
m

q
j
B
m
j
(t ),
4 0 7
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 0 7
t hat best approximat es p(t ) und er some mat hemat ically precise measure
of approximat ion er ror.
The least -squares met hod (Lawson and Hanson, 1974) provid es one
such measure. To use it , we d ene t he resid ual as t he aver age squared
d i ffer en ce bet ween p(t ) a n d q(t ) over t h e u n i t i n t er va l ,
R

0
1

and seek coefcient s q


j
. t hat minimize t he resid ual. For xed p(t ), t he
resid ual is a quad r at ic expr ession in t he coefficient s q
j
. It is minimized where
all of it s d er ivat ives / q
i
vanish. From element ar y calculus, t he vanishing
of t he d er ivat ives means t hat

0
1


q
j
i
m
B
(t )
j
m
B
(t )dt
j 0
m


0
1


q
j
i
m
B
(t )
j
n
B
(t )dt
j 0
m

for all 0 # i # m.
Such an equat ion can be simplied by applying t he rules for prod uct s
and int egr als of Ber nst ein p olynomials (Far in, 1988). The r esu lt is a
mat r ix equat ion of t he for m,
Aq= Bp, (1)
wh er e A i s i n
(m+l ) (m+l )
a n d B i s i n
(m+l ) (n+l )
. Th e en t r i es of A
and B can be wr it t en as:

(2m + 1)a
ij

j
m
|
.

`
,

i + j
2m
|
.

`
,

, (m + n + 1)b
ij

j
n
|
.

`
,

i + j
m+n
|
.

`
,

.
In pr act ice, t he d egrees of p(t ) and q(t ) u su ally are xed . In su ch
cases, it is possible t o precomput e t he mat r ix A
-1
B and avoid repeat ed ly
solving Eq.(1). If m = 1, t his mat r ix, C = A
-1
B, has a par t icular ly

q
j
B
j
m
(t ) p
j
B
j
n
(t )
j 0
n

j 0
m

|
.
`
,
2
dt ,
4 0 8
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 0 8
simple for m:

c
0 j

2
(n + 1)(n + 2)
(1 + 2n 3j),

c
1
j

2
(n + 1)(n + 2)
(1 n + 3j).
For example, t he best -t t ing linear funct ion q(t ) t o a given cubic polyno-
mial p(t ) has coefficient s:

q
0

1
10
(7p
0
+ 4p
1
+ p
2
2p
3
),

q
1

1
10
(2p
0
+ p
1
+ 4p
2
+ 7p
3
).
To approximat e a par amet r ic Bzier cur ve, we apply t he met hod t o
each of t he component polynomials x(t ) and y(t ) separ at ely. An example
of t he applicat ion of t his t echnique appear s in Fig. 1, in which a d egree
12 par amet r ic cur ve is red uced t o a d egree 3 cur ve. If t he line segment
L(t ) connect s t he p oint s p(t ) and q(t ) on t he t wo cu r ves, t hen t he
least -squ ares t t ing cu bic cu r ve minimizes t he aver age valu e of t he
squared lengt h of L(t ).
Figur e 1. Cubic cur ve approximat ing d egree 12 cur ve.
4 0 9
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 4 0 9
Mul t i var i at e Appr oxi mat i on Mul t i var i at e Appr oxi mat i on Mul t i var i at e Appr oxi mat i on Mul t i var i at e Appr oxi mat i on Mul t i var i at e Appr oxi mat i on
A more gener al problem is t he t t ing of a Bzier sur face, or it s higher-
d imensional analog, wit h a lower-d egree sur face. The mult ivar iat e Ber n-
st ein polynomials behave ver y much like t heir univar iat e count er par t s, so
wit h appropr iat e not at ion, an explanat ion of t he gener al mult ivar iat e
result is no more d ifcult t o und er st and t han t he univar iat e result .
A mult ivar iat e Ber nst ein polynomial (d e Boor, 1987) of d imension d is
d ened over a d-simplex, where a 2-simplex is a t r iangle and a 3-simplex
is a t et r ahed ron. For concret eness, consid er in par t icular t he simplex S
wit h ver t ices at t he or igin and at e
1
, . . . , e
d
, where e
i
is a point on t he x
i
axis one unit from t he or igin. For convenience, d ene x
0
as 1

i 1
d
x
i
.
The ind ex set for t he d egree n Ber nst ein polynomials of d imension d
is d enot ed as
n
d
; it consist s of all t he (d + 1)-t uples of nonnegat ive
int eger s t hat sum t o n. For an element i
n
d
, i
k
is t he kt h ind ex, i!
d enot es t he prod uct of t he fact or ials of t he ind ices, and x
i
d enot es t he
p r od u ct of t h e t er ms x
i
0
o
. . . x
i
d
d
. In t h i s n ot at i on , a Ber n st ei n basi s
funct ion can be expressed as:

B
i
(x)
n!
i!
x
i
,
and a polynomial in Ber nst ein basis for m as:
p(t) =

i
d
n

p
i
B
i
(t).
Using t his not at ion, t he d er ivat ion in t he mu lt ivar iat e case closely
mat ches t he d er ivat ion in t he univar iat e case. Given p(t), we wish t o nd
a q(t) t hat minimizes t he resid ual,
R =
S
q
j
B
j
(t) q
j
B
j
(t)
j
d
n

j
d
m

|
.

`
,

2
dt.
This expression is minimized where t he par t ial d er ivat ives

/ q
i
vanish,
410
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 410
so t hat


S
j
d
m
m

q
j
B
i
t ( )B
j
t ( )dt


S
j
d
m

p
j
B
i
t ( )B
j
t ( )dt
for each i


m
d
. Again, t he prod uct and int egr at ion r ules for mult ivar iat e
Ber nst ein p olynomials (d e Boor, 1987) p er mit simp licat ions of t his
expression t o t he mat r ix equat ion,
Aq= Bp,
where t he mat r ix A is in
|
m
d
|

|
m
d
|
and t he mat r ix B is in
|
m
d
|

|
m
d
|
,
where

|
d
k
|
k + d
k
|
.
`
,
.
The ent r ies of A and B are given by t he expressions,
a
ij

m!d!(i + j)!
(2m + d)! j!
, b
ij

m!d!(i + j)!
(m + n + d)! j!
.
In t he linear case, m = 1, t his expression can be simplied fur t her.
The element s of A
1
are given by:
ii
1
a
(d +1)
2
,
ij
1
a
(d +1) (i j).
Since m = 1, t he ind ices of t he coefficient s q
i
are in
1
d
, and each ind ex
i is of t he for m e
k
for 0 k d. The q
e
k
can be expressed in t er ms of
t he p
j
as:

q
e
k

n!(d + 1)!
(n + d + 1)!
(1
j
d
n
n + (d + 2)j
k
)p
j
,
where j
k
d enot es t he kt h ent r y of j.

n
411
IX.1 LEAST-SQUARES APPROXIMATIONS TO BZIER CURVES AND SURFACES
GRAPHICS GEMS II Edit ed by JAMES ARVO 411
For example, if n = d = 2, t hen

q
100

1
10
(7p
200
+ 3p
110
+ 3p
101
p
020
p
011
p
002
),

q
010

1
10
(7p
020
+ 3p
110
+ 3p
011
p
200
p
101
p
002
),

q
001

1
10
(7p
002
+ 3p
101
+ 3p
011
p
200
p
110
p
020
).
See also 9.2 Beyond Bzier Cur ves, Ken Shoemake; 9.6 Geo-
met r ically Cont inuous Cubic Bzier Cur ves, Hans-Pet er Seid el
412
IX.2 BEYOND BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 412
IX.2 IX.2 IX.2 IX.2 IX.2
B BB BBEYON EYON EYON EYON EYOND D D D D BZIER BZIER BZIER BZIER BZIER
C CC CCURVES URVES URVES URVES URVES
Ken Shoemake
Ot t er Ent erpnses
Palo Alt o, Calif ornia
Bzier cur ves are d eser ved ly popular, because t he cont rol point s have a
geomet r ical relat ionship t o t he cur ve, unlike polynomial coefcient s. By
associat ing a homogeneous weight wit h each cont rol point , it is possible
t o d escr ibe r at ional cur vesand hence, conicsas well. Sur faces can be
d escr ibed wit h t ensor prod uct s of cur ves, giving four-sid ed Bzier pat ches;
and solid s as well as higher-d imensional volumes can be d escr ibed by an
ext ension of t he same t echnique. This is not t he only way t o proceed ,
however. Inst ead , one can const ruct Bzier t r iangles, t et r ahed r a and so
on (d e Boor, 1987). Th ese Bz ier simplices h ave been exp loit ed r e-
cent ly by Loop and De Rose (1989, 1990) as a way t o const ruct pat ches
wit h any number of sid es, and from t hese, sur faces of ar bit r ar y t opology.
Evaluat ion t o nd point s on Bzier simplices can be accomplished by a
gener alizat ion of t he recu r sive geomet r ic d e Cast eljau algor it hm for
cur ves. One t r icky par t in d oing t his is simply managing t he bookkeeping,
since t he algor it hms and d at a st ruct ures are most nat ur ally expressed in
t er ms of what are called mult i-indices. For a cur ve, t hese may seem like
an unnecessar y complicat ion; for higher d imensions, t hey are a great
help. Here in Fig. 1 are examples of a cubic cur ve and a cubic t r iangle,
wit h cont rol point s labeled by t heir mult i-ind ices. The sum of t he ind ices
is t he par amet r ic d egree; here, it is 3.
Evaluat ion of t he cur ve or sur face recur sively red uces t he d egree t o
zero, which gives a point . A convenient way t o d escr ibe t he process is t o
give t he par amet er values for t he point as afne coord inat es wit h respect
t o a simplex. For a point 2/ 3 of t he way along t he cur ve, t he coord inat es
are (1/ 3, 2/ 3). Each ed ge of t he cont rol polygon for a cur ve has t wo
end point s, which are summed in t hese propor t ions t o give a point of t he
413
IX.2 BEYOND BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 413
Figur e 1. a) Cubic cur ve; b) cubic t r iangle.
next lower-d egree cont rol polygon. The affine coord inat es always sum t o
1, or else t his would not make sense; also, t his const r aint removes one
d egree of freed om, leaving only a single effect ive par amet er for a cur ve,
a s exp ect ed . Be ca r efu l n ot t o con fu se t h e i n d ex for a con t r ol
point which is only a labelwit h it s coord inat es. In implement at ion
t er ms, t he mult i-ind ex gives a locat ion in an ar r ay, while t he coord inat es
are t he cont ent s of t hat locat ion. Thus, t he point wit h mult i-ind ex {1, 2}
could have coord inat es (1.3, 2.4, 2) and cont rol a space cur ve, not just
a planar cur ve. For a d egree 2 cur ve, t he ind ices will be {2, 0}, {1, 1}, and
{0, 2}; for d egree 1 (a line), t hey will be {1, 0} and {0, 1}; and nally, for
d egree 0 (a point ), t he ind ex is {0, 0} (Table I).
Table 1.
414
IX.2 BEYOND BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 414
The d ep end ency follows a ver y simp le p at t er n: p[ i] = t [k]p[ + e
k
],
where i +
k
ad d s 1 t o each component of t he mult i-ind ex i in t ur n. For
t r iangles, t he pat t er n hold s, but t here now are t hree cont rol point s t o
su m, and t he afne coord inat es ar e t hree-t u p les, t = (t
0
, t
1
, t
2
), wit h
t
k
= 1. (See Fig. 1 and Table 2. To save space, t he t able shows only t he
evaluat ion of a quad r at ic t r iangle.) While it is possible t o st ore t he point s
in a mult i-d imensional ar r ay, it also is wast eful. The t r iangular cubic
pat ch would st ore only 10 point s in a 4
3
= 64 ent r y ar r ay, while t he
point s for one of Loop and De Roses S-pat ches of d ept h 6 and ve sid es
Figur e 2.
Table 2.
Degree 2 Degree 1 Degree 0
ind ex from ind ex from ind ex
415
IX.2 BEYOND BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 415
wou ld u se only 210 ou t of 7
5
= 16,807 ent r ies! For t u nat ely, one can
syst emat ically enumer at e t he cont rol point s t o allow syst emat ic ind exing,
and so use ent r ies in a one-d imensional ar r ay wit hout any wast e.
To enumer at e t hrough all mult i-ind ices for d egree d and n + 1 slot s,
d ecrement t he r st ind ex i
0
from d d own t o 0, and for each value of i
0
,
recur se t o enumer at e t he mult i-ind ices for d egree d i
0
and one less
slot . For d egree 0 or for only one slot (a special case), t here is only one
con t r ol p oi n t . For h i gh er d egr ees or mor e sl ot s, #Poi n t s(d, n) =
#Poi n t s(d 1, n) + #Poi n t s(d, n 1). Th e cl osed for m #Poi n t s(d, n)
= (d + n)!/ d!n! clear ly is symmet r ic in it s argument s. Wit h t his ord er,
evaluat ion is ver y regular, as can be seen in t he case of a cubic t r iangle
(Table 3).
St ud y of t his and similar examples reveals t hat for a given number of
slot s, t here really is only one d epend ency list , wit h lower d egrees using
smaller por t ions of it . Also, a point always d epend s on t he higher d egree
point at t he same ar r ay ind ex (and never on point s wit h lower ind ices); so,
for a mod est invest ment in p recalcu lat ed t ables, all t he mu lt i-ind ex
bookkeeping goes away.
To build t he d epend ency t ables, it helps t o know how t o comput e an
offset from a mult i-ind ex. This t ur ns out t o be anot her recur sive process.
The id ea behind t he offset calculat ion is t hat before we get t o t he offset
for t he lead ing ind ex i
0
, we r st must have enumer at ed all larger ind ices.
Table 3.
416
IX.2 BEYOND BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 416
When t he d egree is zero, t he offset is zero; t his is where t he recur sion
bot t oms ou t . Ot her wise, t he offset is t he su m of #Point s(d i
0
1,n)
and t he offset for t he shor t er mult i-ind ex, {i
1
, . . . , i
n
}. (For t he case when
i
0
= d, it is necessar y t o ext end t he d enit ion of #Point s t o ret ur n 0
when d is negat ive.) Remember t hat t he d egree is t he sum of t he ind ices,
so t he shor t er mu lt i-ind ex has d egr ee d i
0
, and t he r ecu r sion will
t er minat e aft er all t he nonzero ind ices have been picked off.
417
IX.3 A SIMPLE FORMULATION FOR CURVE INTERPOLATION WITH VARIABLE CONTROL POINT APPROXIMATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 417
IX.3 IX.3 IX.3 IX.3 IX.3
A AA AA SIMPLE FORMULATION FOR SIMPLE FORMULATION FOR SIMPLE FORMULATION FOR SIMPLE FORMULATION FOR SIMPLE FORMULATION FOR
C CC CCURVE INTERPOLATION WITH URVE INTERPOLATION WITH URVE INTERPOLATION WITH URVE INTERPOLATION WITH URVE INTERPOLATION WITH
V VV VVARIABLE CONTROL POINT ARIABLE CONTROL POINT ARIABLE CONTROL POINT ARIABLE CONTROL POINT ARIABLE CONTROL POINT
A AA AAPPROXIMATION PPROXIMATION PPROXIMATION PPROXIMATION PPROXIMATION
John Schlag
MacroMind, Inc.
San Francisco, Calif ornia
Cur ve int er polat ion for comput er animat ion oft en requires some sor t of
shape cont rol beyond t he values of t he cont rol point s. This gem present s
a hybr id schemebased on t echniqu es p resent ed by Kochanek and
Bar t els (1984) and Duff (1984)t hat provid es cont rol over t ension, bias,
cont inu it y, and ap p roximat ion. (The t er ms approximat ion and int erpo-
lat ion are used int erchangeably, alt hough t hey are complement ar y, simi-
lar t o t he t er ms t ransparency and opacit y in rend er ing.)
Kochanek and Bar t els (1984) provid e an elegant for mulat ion for t en-
sion, cont inuit y, and bias cont rol based on t he blend ing of t angent s:
P'
ii1

(1 t )(1 c)(1+ b)
2
(P
i
P
i 1
)

+
(1 t )(1+ c)(1 b)
2
(P
i +1
P
i
),
P'
ii1

(1 t )(1+ c)(1+ b)
2
(P
i
P
i 1
)

+
(1 t )(1 c)(1 b)
2
(P
i +1
P
i
).
where P'
i 1
(1) is t he incoming t angent at P
i
(i.e., t he t angent of arc i 1
evaluat ed at t = 1) and P'
i
(0) is t he out going t angent at P
i
, and t , c, and
b are t ension, cont inuit y, and bias. Two cont rol point s, P
i
and P
i + 1
, and
t he t angent s comput ed at t hese cont rol point s, P'
i
(0) and P
i
' (1) are t hen
used for Her mit e int er polat ion.
418
IX.3 A SIMPLE FORMULATION FOR CURVE INTERPOLATION WITH VARIABLE CONTROL POINT APPROXIMATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 418
Duff (1984), on t he ot her hand , provid es a five par t ner family of
splines wit h cont rol over bias, t ension, and approximat ion:
wher e , , , , and ar e int er p r et ed as slew, int erpolat ion, geo-
met ricit y, t ension, and direct ion, resp ect ively. Not e t hat , u nfor t u nat ely,
t he t er m t ension is used bot h for int er polat ing splines, in which t he
t ension cont rols t he velocit y at t he cont rol point s, and for appr oximat ing
splines, in which t he t ension cont rols t he d egree t o which t he cur ve
approaches t he cont rol point s.
The Kochanek-Bar t els for mulat ion provid es super ior cont rol over t an-
gent s by breaking t he t angent at a point int o incoming and out going
t angent s, t hus provid ing cont rol over cont inuit y. Duff' s for mulat ion pro-
vid es t he ad d it ional par amet er necessar y for cont rol over approximat ion.
These met hod s can be easily combined by using Duff' s for mulat ion wit h
= .5 t o calculat e t he end point s P(0) and P(1), and t he Kochanek-Bar t els
for mulat ion t o calculat e t he t angent s P(0) and P(1):

P(0) = lerp(P
i
, lerp(P
i 1
, P
i +1
, ), ),
P(1) = lerp(P
i +1
, lerp(P
i
, P
i +2
, ), ),
P' (0) = (1 ) lerp(P
i
P
i 1
, P
i +1
P , ),
P' (1) = lerp(P
i +1
+ P
i
, P
i +2
P
i +1
, ),

P (0) =
(1 t )(1+ c)(1+ b)
2
(P
i
P
i 1
)

+
(1 t )(1 c)(1 b)
2
(P
i +1
P
i
),

P (1) =
(1 t )(1 c)(1+ b)
2
(P
i +1
P
i
)

+
(1 t )(1+ c)(1 b)
2
(P
i +2
P
i +1
).

P(1) = lerp P
i +1
,
P
i
+ P
i +2
2
,
|
.

`
,

,

P(0) = lerp P
i
,
P
i 1
+ P
i +1
2
,
|
.

`
,


i
419
IX.3 A SIMPLE FORMULATION FOR CURVE INTERPOLATION WITH VARIABLE CONTROL POINT APPROXIMATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 419
Wit h t = c = b = 0, t he value = 1/ 3 gener at es B-splines, and = 0
gener at es Cat mull-Rom splines.
Not e t hat t he Kochanek-Bar t els for mulat ion includ es cor rect ions t o t he
t angent s for knot spacing (omit t ed unt il now for clar it y):
ad just ed P(0) = P(0)

2N
i 1
N
i 1
+ N
i
,
ad just ed P(1) = P(1)

2N
i 1
N
i
+ N
i +1
.
Now for some obser vat ions regard ing t he user int er face t o t hese pa-
r amet er s: The most obvious approach is t o provid e slid er s or some ot her
cont rols for t , b, c, and . Anot her approach is t o let t he user ed it t he
t angent s d irect ly. This wor ks especially well for 2D posit ion (Ad obe,
1988). This t echnique can be ext end ed t o 3D in a number of ways. Fir st ,
t he t echnique can be limit ed t o IDas in a funct ion ed it or and t hen
applied t o each scalar. This is oft en t he only alt er nat ive, especially when
t he mot ion par amet er being int er polat ed has no int uit ive geomet r ic mean-
ing. Alt er nat ively, we can obser ve t hat , accord ing t o t he rules of good
t r ad it ional animat ion (Lasset er, 1987), animat ion is oft en st aged from t he
sid e. This suggest s t hat mapping 2D int er act ion ont o a plane par allel t o
t he image plane of a 3D view wind ow would be accept able. Finally, of
cour se, t hree or t hogonal views can be used , if necessar y, t o pr ovid e
complet e cont rol.
420
IX.4 SYMMETRIC EVALUATION OF POLYNOMIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 420
IX.4 IX.4 IX.4 IX.4 IX.4
S SS SSYMMETRIC EVALUATION OF YMMETRIC EVALUATION OF YMMETRIC EVALUATION OF YMMETRIC EVALUATION OF YMMETRIC EVALUATION OF
P PP PPOLYNOMIALS OLYNOMIALS OLYNOMIALS OLYNOMIALS OLYNOMIALS
Terence Lindgren
Prime Comput ervision
Bedf ord, Massachuset t s
Par amet r ic cur ves and sur faces are wid ely used pr imit ives in comput er
gr aphics. PHIGS PLUS, in fact , makes NURBS cur ves and sur faces fund a-
ment al pr imit ives. It is ver y common t o rend erer s t o nd polyline repre-
sent at ions for cur ves and facet represent at ions for sur faces. Typically,
t hese represent at ions come from evaluat ing t he cur ve or sur face at a set
of point s and connect ing t hem in t he nat ur al way. The efcient evaluat ion
of t hese pr imit ives is impor t ant t o any rend erer int erest ed in speed . The
mat hemat ical for m of t he pr imit ive is impor t ant t o bot h t he applicat ion
and t he rend erer. Oft en, CAD/ CAM applicat ions represent geomet r y in
t he B-Spline basis or t he Ber st ein basis because t hese bases have signi-
cant geomet r ic int er pret at ions; ot her ap p licat ions might u se a p ower
ser ies wit h t he more familiar p ower basis, {1,t ,t *t ,...}. Unfor t u nat ely,
many of t hese d ifferent bases are d ifcult t o rend er quickly wit hin t he
const r aint s of most gr aphics subsyst ems. However, t he power basis is not
one of t he d ifcult ones, and rend erer s commonly change t o t he power
basis pr ior t o evaluat ion (Boehm, 1984).
Before t he ad vent of fast oat ing-point mult iplier s, t hese polynomials
might have been evaluat ed wit h for ward d ifferencing; but wit h mult iplier
sp eed s comp ar able t o ad d er sp eed s, a p olynomial can be evalu at ed
realist ically by Hor ner s rule; t hat is,

F[t ] ai t
i
i 0
N

421
IX.4 SYMMETRIC EVALUATION OF POLYNOMIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 421
can be evaluat ed at t by t he loop:
Fa
n
;
for i=N1 t o 0
begi n
FF*t +a
i
;
end
We will examine t his t echnique and subsequent calculat ions in t er ms of
t he number of mult iplicat ions and t he number of ad d it ions t he oper at ion
t akes. If t he d egree of t he polynomial is N, t hen Hor ner s rule requires N
mult iplicat ions and N ad d it ions t o evaluat e a point t in t he d omain. A
mult ivar iat e polynomial, like t hose t hat would be used t o represent t he
coord inat e funct ions of a par amet r ic sur face,

F[t , s] a
ij
j 0
M

i 0
N
s
j
t
i
,
would use (N + 1)(M + 1) 1 mult iplicat ions and (N + 1)(M + 1) 1
ad d it ions t o evaluat e a point (s, t ) in t he d omain by Hor ner s rule.
The polynomials we encount er in comput er gr aphics, especially t hose
ar ising or iginally as NURBS, are d ened neit her over an innit e d omain
nor over an int er val t hat is symmet r ic about t he or igin. Bot h t he int er val
of d enit ion [a, b] and t he point at which t he power ser ies is cent ered are
unrest r ict ed . For power ser ies cent ered at some point c, we can evaluat e
point s in t he d omain by applying Hor ner s r ule t o t he quant it y (t c),
red ucing t he problem of evaluat ing a power ser ies t o ones cent ered at 0.
Of par t icular int erest t o us ar e power ser ies cent ered at t he mid point m
of t he d omain [a, b]; t hat is,

F[t ]
i
i 0
N
(t m)
i
.
Hencefor t h, we will consid er only power ser ies cent ered at 0.
Cer t ain polynomials have some ver y simple proper t ies. Some are even
or od d funct ions. A funct ion H is even if
H[t] = H[t ],
422
IX.4 SYMMETRIC EVALUATION OF POLYNOMIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 422
and is od d if
H[t ] = H[t ].
Moreover, any polynomial is t he sum of an even and an od d funct ion. The
even funct ion is d et er mined by t hose t er ms wit h even power s, and t he
od d funct ion is d et er mined by t hose t er ms wit h od d power s,
F[t ] = E[t ] + O[t ].
Since O[t ] is all t er ms wit h od d power s from F, we immed iat ely see t hat
we may rewr it e O[t ] as
O[t] = t *E' [t] ,
where E' is an even funct ion. So we may wr it e F as
F[t ] = E[t ] + t *E' [t ] , (1)
and we now are free t o recognize
F[t ] = E[t ] t *E' [t ].
Wit h t his obser vat ion, we are in a posit ion t o st at e t he simple wor k
saving evalu at ion t echniqu e, which we will call symmet ric evaluat ion.
Not e t hat we d o assume t hat t he power ser ies is cent ered at t he mid point
of t he segment or pat ch.
f or t 0, gener at e F[t ] and F[t ].
Const ruct a power series (cent ered at t he midpoint of t he segment ).
Calcu lat e E and E as in Eq. (1)
Calcu lat e t *t .
Use Horners Rule t o evaluat e bot h E and E as polynomials in t *t .
Mu lt iply E by t .
Creat e t he su m, F[t ], and d ifference, F[t ], of E[t ] and t *E[t ].
The pr ice we pay for calculat ing t wo symmet r ic point s of a polynomial
of d egree N is a mult iplicat ion t o set u p t *t , N mu lt iplicat ions and
N 1 ad d it ions t o calculat e E and E' , and t wo ad d it ions t o calculat e t he
sum and t he d ifference; So, for a single polynomial, t he t ot al wor k is
423
IX.4 SYMMETRIC EVALUATION OF POLYNOMIALS
GRAPHICS GEMS II Edit ed by JAMES ARVO 423
N + 1 mult iplicat ions and N + 1 ad d it ions. Evaluat ion of polynomials in
t wo var iables present s an oppor t unit y for even great er savings. We cent er
a power ser ies at t he mid point of a pat ch just as we d id for t he mid point
of a segment and proceed in a similar way as before.
If we evaluat e t he mult ivar iat e polynomial as if it were N + 2 univar i-
at e polynomials, as

F[t , s]
ij
s
j
j 0
M

|
.
`
,
t
i
i 0
N

would ind icat e, our savings are more impressive. We may evaluat e sym-
met r ically four point s wit h a cost of (N + l)M + 2N + 2 mult iplicat ions
and (N + 1)(M + 3) ad d it ions. Compare t his t o t he 4((N + 1)(M + 1)
1) mult iplicat ions and 4((N + 1)(M + 1) 1) ad d it ions need ed for t r ad i-
t ional evaluat ion.
Act ually, t he savings are great er for a par amet r ic sur face; not only are
t her e at least t hree coord inat e p olynomials t o be evalu at ed , bu t t he
sur face,s par t ial d er ivat ives also will need t o be evaluat ed . Aft er all, we
will want t o shad e t he sur face, so we will need t he par t ials t o calculat e t he
sur face nor mal at t he evaluat ion point s. The cost for t his wor k t r ad it ion-
ally is 4*(number of coord inat e funct ions)*(3NM + 2(N + M) 2) mul-
t iplicat ions and ad d it ions; while t he cost for symmet r ic evaluat ion is
(nu mber of coord inat e fu nct ions)*(3NM + 5N + 3M 2) mu lt ip lica-
t ions and (number of coord inat e funct ions)*(3NM + 6N + 4M + 3) ad -
d it ions.
Finally, as an illust r at ion, let us look at t he act ual savings obt ained
evaluat ing symmet r ic point s and t heir par t ials on an int egr al bicubic
pat ch. Tr ad it ional evaluat ion cost s 444 mult iplicat ions and 444 ad d it ions,
whereas symmet r ic evaluat ion cost s only 149 mult iplicat ions and 180
ad d it ions.
424
IX.5 MENELAUS S THEOREM
GRAPHICS GEMS II Edit ed by JAMES ARVO 424
IX.5 IX.5 IX.5 IX.5 IX.5
M MM MMENELAUS S ENELAUS S ENELAUS S ENELAUS S ENELAUS S
THEOREM THEOREM THEOREM THEOREM THEOREM
I II II
Hans-Pet er Seidel
Universit y of Wat erloo
Wat erloo, Ont ario, Canada
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Menelauss t heorem has been known since t he ancient Greeks, but is
sur pr isingly unfamiliar t od ay. It oft en is a hand y t ool in cur ve and sur face
d esign, since it relat es t he r at ios bet ween d ifferent cont rol point s in a
simple int uit ive way. In par t icular, Menelauss t heorem can be used for
knot inser t ion in B-splines, -splines, and NURBS.
Menel aus s Theor em Menel aus s Theor em Menel aus s Theor em Menel aus s Theor em Menel aus s Theor em
Menelau ss t heorem can be st at ed as follows: Consid er t he t r iangle
(ABC) t oget her wit h t he point s D BC, E CA, and F AB as
sh own i n Fi g. 1. Men el a u ss t h eor em sa ys t h a t t h e p oi n t s

D, E, F are collinear iff
BD
DC

CE
EA

AF
FB
1
(The negat ive sign is d ue t o t he fact t hat t he r at io

BD/ DC for a point D
out sid e of

BC is negat ive).
1
This wor k has been su p p or t ed p ar t ly by t he Nat u r al Sciences and Engineer ing Re-
search Cou ncil of Canad a t hrou gh St r at egic Oper at ing Gr ant STR0040527.
425
IX.5 MENELAUS S THEOREM
GRAPHICS GEMS II Edit ed by JAMES ARVO 425
Figure 2. Knot inser t ion for cubic B-splines
Figure 1. Menelauss t heorem.
426
IX.5 MENELAUS S THEOREM
GRAPHICS GEMS II Edit ed by JAMES ARVO 426
Appl i cat i on Appl i cat i on Appl i cat i on Appl i cat i on Appl i cat i on
An applicat ion of Menelauss t heorem is shown in Fig. 2. The gure
illust r at es how Menelauss t heorem can be used for knot inser t ion int o
B-splines: Shown in t he it h segment of a cubic B-spline cur ve F over t he
kn ot vect or. kn ot vect or
t oget her wit h t he B-spline cont rol point s . . . , V
i 2
, V
i 1
, . . . and t he
Bzier point s . . . , P
i
l
-1
, . . . , P
i
2
+l
, . . . of t he ad jacent segment s. Also
d epict ed are t he new cont rol point s V
i2
* , . . . , V
i
* aft er inser t ing t he new
knot t bet ween t
i
and t
i + l
.
Not e t hat Fig. 2 cont ains t wo of Menelauss gures: One gur e comes
fr om t h e t r i a n gl e, (A
l
, B
l
, C
1
) = (P
i
2
-l
, V
i 2
, P
i
1
), t oget h er wi t h t h e
point s, D
1
= V
i1
* ,E
1
, and F
1
= V
i2
* , while t he ot her gure comes from
t he t r iangle, (A
2
, B
2
, C
2
) = (P
1
i+1
, V
i 1
, P
i
2
), t oget her wit h t he point s,
D2 = V*
i 1
, E2, and F2 = V
i
*.
Since t he point s,

E
1

t t
i
t
i +1
t
i
P
1
i
+
t
i +1
t
t
i +1
t
i
P
0
i
,


V
i 1

t t
i
t
i +1
t
i
P
2
i
+
t
i +1
t
t
i +1
t
i
P
1
i
,


E
2

t t
i
t
i +1
t
i
P
3
i
+
t
i +1
t
t
i +1
t
i
P
2
i
,
are given by t he d e Cast eljau algor it hm, a simple calculat ion using
Menelauss t heorem shows

V
i 2

t t
i
t
i +1
t
i
V
i 2
+
t
i +1
t
t
i +1
t
i
P
2
i 1
,
T = (. . . , t
i 1
, t
i
, t
i + 1
, t
i + 2
, . . . ),
427
IX.5 MENELAUS S THEOREM
GRAPHICS GEMS II Edit ed by JAMES ARVO 427
and

V
i

t t
i
t
i +1
t
i
P
1
i +1
+
t
i +1
t
t
i +1
t
i
V
i 1
,
and using t he relat ionship bet ween t he Bzier point s and t he B-spline
cont rol point s, we see t hat t he new cont rol point s V
j
* are given as:

V
j

t t
i
t
i +1
t
i
V
j
+
t
i +1
t
t
i +1
t
i
V
j 1
, j i 2, ... , i.
Thus, we have d er ived t he well-known inser t ion algor it hm for B-splines
from a simple t heorem on 2D geomet r y. In a similar fashion, Menelauss
t heorem can be u sed for knot inser t ion in nonu nifor m -sp lines and
NURBS.
428
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 428
IX.6 IX.6 IX.6 IX.6 IX.6
G GG GGEOMETRICALLY EOMETRICALLY EOMETRICALLY EOMETRICALLY EOMETRICALLY
C CC CCONTINUOUS CUBIC BZIER ONTINUOUS CUBIC BZIER ONTINUOUS CUBIC BZIER ONTINUOUS CUBIC BZIER ONTINUOUS CUBIC BZIER
C CC CCURVES URVES URVES URVES URVES
1 11 11
Hans-Pet er Seidel
Universit y of Wat erloo
Wat erloo, Ont ario, Canada
Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on
Tr ad it ionally, cur ves and sur faces in comput er gr aphics and comput er-
aid ed d esign have been requ ired t o be p ar amet r ically C
k
-cont inu ou s.
However, for many applicat ions, t his not ion of cont inu it y is far t oo
rest r ict ive: Figure 1 shows t wo cubic Bzier cur ves,

F(u) B
i
n
i 0
3

(u)P
i
,
and

H(u) B
i
3
i 0
3

(u)R
i
,
in t he plane. Here,

B
i
3
(u)
3
i
( )
u
i
(1 u)
3i
, i 0, ... , 3
are t he Ber nst ein polynomials, and t he point s P
0
, . . . , P
3
, and R
0
, . . .,R
3
respect ively, are t he Bzier point s. The problem is t o ll t he gap bet ween
1
This wor k has been su p p or t ed p ar t ly by t he Nat u r al Sciences and Engineer ing Re-
search Cou ncil of Canad a t hrou gh St r at egic Oper at ing Gr ant STR0040527.
429
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 429
Figure 1. Gap bet ween P
3
and R
0
.
P
3
and R
0
by an ot her cubic Bzier cur ve,

G(u) B
i
3
i 0
3

(u)Q
i
,
in such a way t hat t he result ing composit e cur ve is as smoot h as
possible.
Suppose we wish t o ll t he gap bet ween t he given cur ves F and H in
such a way t hat t he result ing composit e cur ve is par amet r ically C
1
-con-
t inuous. Using t he well-known d er ivat ive for mulas for Bzier cur ves,
G(0) = 3(Q
1
Q
0
),G(0) = 6(Q
2
2Q
1
+ Q
0
),
and
G(1) = 3(Q
3
Q
2
), G(1) = 6(Q
3
2Q
2
+ Q
1
),
we see t hat a C
1
-joint at F(1) = G(0) implies:
Q
0
= P
3
and Q
1
= 2P
3
P
2
,
while a C
1
-joint at G(1) = H(0) gives:
Q
3
= R
0
and Q
2
= 2R
0
R
1
.
430
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 430
Figure 2. C
1
-solut ion wit h a cusp.
In par t icular, our requirement for an over all C
1
-cur ve complet ely d et er-
mines t he Bzier cur ve G t hat br id ges t he gap bet ween F and H. So far,
it seems t hat t he preced ing t wo equat ions provid e an easy solut ion t o an
easy problem.
Second t hought s ar ise when we act ually t ake a look at t he cur ve G t hat
we have just comput ed (Fig. 2). Disast er has happened : By insist ing on
par amet r ic C
1
-cont inuit y at t he joint s G(0) and G(1), we act ually have
int rod uced a cusp. Our solut ion G is t ot ally unaccept able!
Par amet r i c ver sus Geomet r i c Cont i nui t y Par amet r i c ver sus Geomet r i c Cont i nui t y Par amet r i c ver sus Geomet r i c Cont i nui t y Par amet r i c ver sus Geomet r i c Cont i nui t y Par amet r i c ver sus Geomet r i c Cont i nui t y
The problem wit h our solut ion G in t he previous sect ion st ems from t he
fact t hat we have insist ed on paramet ric cont inuit y inst ead of geomet -
ric con t i n u i t y: In st ea d of l ooki n g a t t h e con t i n u i t y of a sp eci c
par amet r izat ion, we have t o look at t he cont inuit y of t he shape of t he
cur ve, which is ind epend ent und er possible repar amet r izat ion. Thus, we
say t hat t wo cu r ves join wit h geomet ric cont inuit y if t he cu r ves are
par amet r ically cont inuous und er repar amet r izat ion. In ot her word s, t wo
cur ves F and G are G
k
-cont inuous at a par amet er s if t here exist s a
repar amet r izat ion (which pr eser ves t he given or ient at ion of t he cur ve)
431
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 431
such t hat F( (u)) and G(u) are C
k
-cont inuous at s. Using t he chain r ule
of d ifferent iat ion, it easily is seen t hat G
k
-cont inuit y is equivalent t o t he
well-known -const r aint s:
G(s) =
1
F(s),
G(s) =
1
2
F(s) +
2
F(s),
G(s) =
3
1
F(s) + 3
1

2
F(s) +
3
F(s).


M
G
( k)
(s)
i
1
+i
2
+ . . . +i
k
j ,
i
1
+ 2i
2
+ . . . + k i
k
k,

j 0
k

k!
i
1
!(1!)
i
1
i
k
!(k!)
i
k

1
i
1

k
i
k
F
( j )
(s),
where
k
=

(k)
(s), and
1
> 0, since preser ves t he given or ient at ion.
Th e p a r a met er s
i
a l so a r e ca l l ed shape paramet ers. We p a u se t o
remar k t hat G
1
-cont inuit y is equivalent t o a cont inuous unit t angent ,
while G
2
-cont inuit y is equivalent t o a cont inuous cur vat ure vect or.
Geomet r i cal l y Cont i nuous Bzi er Cur ves Geomet r i cal l y Cont i nuous Bzi er Cur ves Geomet r i cal l y Cont i nuous Bzi er Cur ves Geomet r i cal l y Cont i nuous Bzi er Cur ves Geomet r i cal l y Cont i nuous Bzi er Cur ves
How can we exploit t he preced ing cond it ions t o join t wo cubic Bzier
cur ves wit h a given ord er of geomet r ic cont inuit y? Consid er t wo cubic
Bzier cur ves,

F( u) B
i
3
i 0
3

( u)P
i
and G( v) B
i
3
i 0
3

( v)Q
i
,
over t he int er vals [r, s] and [s, t ], r espect ively, so t hat t he local par ame-
t er s
u
and

v are given as:

u
u r
s r
(u [r, s]) and

v
v s
t s
(v [s, t ]).
432
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 432
Figur e 3. C
1
-joint bet ween t wo cubic Bzier cur ves.
To join F and G wit h G
1
-cont inuit y, it is necessar y and sufcient t hat
t he Bzier point s
P
2
, P
3
= Q
0
,Q
1
are collinear,
and sat isfy t he r at ios,

P
2
P
3
MQ
0
Q
1
(s r)M
1
(t s).
This follows immed iat ely from t he -const r aint s and t he well-known
d er ivat ive for mula for Bzier cur ves, and is d epict ed in Fig. 3.
Things become slight ly more complicat ed for G
2
-cont inuit y. (See Fig.
4.)
It can be shown t hat F and G are G
2
-cont inuous at s precisely if t he
Bzier point s,
P
1
, P
2
, P
3
= Q
0
,Q
1
,Q
2
, are coplanar,
Figure 4. G
2
-joint bet ween t wo cubic Bzier cur ves.
433
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 433
and sat isfy t he r at ios,

P
1
P
2
:P
2
V = (s r):
1
(t s) and

VQ
1
:Q
1
Q
2
= (s r):
2
(t s),
for par amet er s
1
,
2
, wit h

2
=

1
2
.
Thu s, inst ead of d irect ly u sing t he shap e p ar amet er s
1
and
2
, it
somet imes is ad vant ageou s t o u se t he shap e p ar amet er s
1
and
1
inst ead . For t hose who are cur ious, t he (ugly) relat ionship bet ween t he
s and t he s is given as:

1

2
1
2

1
t s ( ) + s r ( ) ( )

2
t s ( ) s r ( ) + 2
1

1
t s ( ) + s r ( ) ( )
and

2
t s ( ) s r ( ) + 2
1

1
t s ( ) + s r ( ) ( )
2
1
t s ( ) + s r ( ) ( )
Using geomet r ic cont inuit y inst ead of par amet r ic cont inuit y, it now is
easy t o come u p wit h a simp le sat isfact or y solu t ion t o ou r or iginal
problem of lling t he gap bet ween t wo given cubic Bzier cur ves F and
H by anot her cubic Bzier cur ve,

G u ( ) B
i
n
u ( )Q
i
,
i 0
3

in such a way t hat t he result ing composit e cur ve is as smoot h as possible.


All we have t o d o is move t he Bzier point s Q
1
and Q
2
somewhere on
t he lines P
2
P
3
and R
0
R
1
a lit t le bit closer t o t he end point s P
3
and R
0
.
This will avoid t he cusp in t he C
1
-solut ion, and , accord ing t o Fig. 3, will
prod uce a G
1
-cur ve over all; but we can d o even bet t er t han t hat . Not e
t hat t he exact posit ioning of t he ver t ices Q
1
and Q
2
on t he lines P
2
P
3
and R
0
R
1
st ill leaves us wit h one d egree of freed om for each point . Using
t he symmet r y of t he given problem, we can exploit t his freed om t o
434
IX.6 GEOMETRICALLY CONTINUOUS CUBIC BZIER CURVES
GRAPHICS GEMS II Edit ed by JAMES ARVO 434
Figure 5. G
2
-solut ion: The result ing composit e cur ve has a cont inuous unit t angent ,
and , in ad d it ion, is cur vat ure-cont inuous ever ywhere.
ar r ange t he Bzier point s Q
1
, and Q
2
of G in such a way t hat t he r at ios of
Fig. 4 are sat ised . Thus, t he result ing cur ve not only will be C
1
, but , in
ad d it ion, will have cont inuous cur vat ure t hroughout . This solut ion is
shown in Fig. 5.
See also 9.1 Least -Squares Approximat ions t o Bzier Cur ves
and Sur faces, Doug Moore, Joe War ren; 9.2 Beyond Bzier
Cur ves, Ken Shoemake
435
IX.7 A GOOD STRAIGHT-LINE APPROXIMATION OF A CIRCULAR ARC
GRAPHICS GEMS II Edit ed by JAMES ARVO 435
IX.7 IX.7 IX.7 IX.7 IX.7
A AA AA GOOD STRAIGHT-LI GOOD STRAIGHT-LI GOOD STRAIGHT-LI GOOD STRAIGHT-LI GOOD STRAIGHT-LINE NE NE NE NE
A AA AAPPROXIMATION OF A PPROXIMATION OF A PPROXIMATION OF A PPROXIMATION OF A PPROXIMATION OF A
C CC CCIRCULAR ARC IRCULAR ARC IRCULAR ARC IRCULAR ARC IRCULAR ARC
Christ opherJ. Musial
New Horizons Sof t ware
St . Louis, Missouri
Many geomet r ic algor it hms and spat ial mod eling syst ems wor k wit h
st r aight lines and st r aight -line polygons. Because t he wor ld d oes not
always consist of st r aight lines, t he need oft en ar ises for approximat ing a
circular arc wit h line segment s. The simplest approximat ion is t o select
point s along t he cur ve at a spacing t hat gives sufficient accur acy and t hen
join t hese point s t oget her int o a polyline. One of t he major d eciencies
wit h t his approach is t hat t he lengt h of t he result ing polyline is less t han
t he arc lengt h of t he or iginal cur ve. If per imet er calculat ion is a require-
ment , t his t ype of approximat ion is unaccept able.
In ad d it ion t o maint aining t he or iginal lengt h, t he polyline also must
st ar t and st op at t he same end point s as t he arc. Because we are imposing
t wo const r aint s on t he culve, t here are t wo var iables we must calculat e.
The r st is t he angle for med bet ween t he t angent vect or at t he st ar t of
t he arc wit h t he r st segment in t he approximat ing polyline (). (By
symmet r y, t his also is t he angle bet ween t he last segment and t he t angent
line at t he end of t he cur ve.)
The second var iable is t he increment al angle bet ween t wo ad jacent
polyline segment s (). Figure 1 shows t hese t wo angles. (In Fig. 1 and
t hroughout t his d iscussion, clockwise arcs are assumed . Count erclock-
wise arcs will be explained lat er.)
Before we can begin t he calcu lat ion, we r st mu st d et er mine t he
nu mber of segment s t o u se in t he p olyline based on t he maximu m
allowable d ist ance bet ween t he polyline and t he arc. If t he polyline
circumscr ibes t he arc, it will be longer t han t he arc; likewise, if t he
polyline is inscr ibed wit hin t he arc, it will be shor t er t han t he arc.
Therefore, a polyline wit h t he same lengt h as t he arc will be somewhere
436
IX.7 A GOOD STRAIGHT-LINE APPROXIMATION OF A CIRCULAR ARC
GRAPHICS GEMS II Edit ed by JAMES ARVO 436
Figur e 1.
bet ween being inscr ibed and circumscr ibed . By choosing t he number of
segment s based on t he cur ve-t o-chord d ist ance of er ror for an inscr ibed
polyline, we will be sure t o be wit hin t he t oler ance for t he polyline at
which we are aiming. Figure 2 shows t he cur ve-t o-chord d ist ance for an
inscr ibed polyline.
The d ist ance d bet ween a circular arc wit h an int er nal angle and a
r ad ius R, and t he chord joining it s t wo end point s, is

d R 1 cos

2
|
.
`
,
.
(1)
If t his d ist ance is t oo large, split t he cur ve by d ivid ing and t he arc
lengt h in half. Repeat ing t he preced ing proced ure unt il we get a cur ve-t o-
chord d ist ance wit hin t he accept able t oler ance, t he lengt h of each seg-
ment in t he polyline is t hat of t he last arc lengt h, and t he number of
segment s is 2
number of split s
.
The preced ing st ep sat ised t he r st cr it er ion we were aft er : The sum
of each segment in t he polyline will equal t he arc lengt h of t he cur ve. The
second cr it er ionhaving t he same st ar t and end point s as t he arcwill
Figur e 2.
437
IX.7 A GOOD STRAIGHT-LINE APPROXIMATION OF A CIRCULAR ARC
GRAPHICS GEMS II Edit ed by JAMES ARVO 437
be met by forcing t he hor izont al span of t he polyline t o equal t he chord
lengt h of t he cur ve.
The hor izont al span is t he sum of t he project ion of each segment ont o
t he x axis, which simply is t he segment lengt h t imes t he cosine of t he
segment s d irect ion vect or. This problem becomes one of calculat ing t he
segment d irect ions, and t hus t he t wo angles, and .
If T is t he t angent vect or at t he st ar t of t he arc, t he d irect ion vect or of
t he r st polyline segment is T , t he d irect ion vect or of t he next
segment is T , T 2, and so on. Thus, forcing t he t ot al
span t o be equal t o t he chord lengt h of t he arc, we get t he equat ion:
segLen

i 0
n 1

cos(T i) chord Len, (2)


where n is t he number of segment s in t he polyline, segLen is t he lengt h
of each segment in t he polyline, and chord Len is t he lengt h of t he chord
of t he arc.
Figure 3 shows t he values we need . Only four segment s are used in t he
approximat ion for ease of viewing.
We know t hat t he t ot al d eect ion of t he circular arc is t he same as it s
int er nal angle, . We also know t hat t he t ot al d eect ion of t he polyline
Figure 3.
438
IX.7 A GOOD STRAIGHT-LINE APPROXIMATION OF A CIRCULAR ARC
GRAPHICS GEMS II Edit ed by JAMES ARVO 438
plus t he t wo s at eit her end equals t he d eect ion of t he cur ve, so
2 + (n 1) = , or (3a)


n 1 ( )
2
. (3b)
Subst it ut ing for in Eq. (2) and rear r anging, we get
segLen

i 0
n 1

cos

T
n 1 ( )
2
i
|
.

`
,

chord Len = 0. (4)


From here, you may use your favor it e convergence algor it hm t o calcu-
lat e . Bot h and are posit ive, so using Eq. (3a), we can calculat e t he
r ange of values for and as:
0 < <

2
,
(5a)
0 < <

n 1
.
(5b)
Equat ion (4) is a well-behaved funct ion as shown in Fig. 4. This is a
gr aph of Eq. (4) for an arc wit h = 90, r ad ius = 100, T = 45, and
n = 32. The chord lengt h is calculat ed as 141.4214 and t he segment
lengt h as 4.9087. Along t he x axis are values of . The y axis is t he left
sid e of Eq. (4). The value of we need is where t he plot crosses y = 0.
The result of t he left sid e of Eq. (4) for t he d ifferent t r ial values of is
t he er ror t o be minimized , which is t he d ifference bet ween t he span of t he
polyline and t he chord lengt h of t he arc. Once Eq. (4) gives an answer
wit hin t he accept able t oler ance, use Eq. (3b) t o calculat e .
For count erclockwise cur ves, use t he same proced ure as before, and
t hen negat e t he values of and .
In t his d iscussion, we or ient ed t he cur ve such t hat t he chord is par allel
wit h t he x axis. When t his is not t he case (and it usually is not ), calculat e
and as if it were, but use t he t r ue t angent vect or of t he arc when
439
IX.7 A GOOD STRAIGHT-LINE APPROXIMATION OF A CIRCULAR ARC
GRAPHICS GEMS II Edit ed by JAMES ARVO 439
Figure 4.
calculat ing t he d irect ion vect or s of t he polyline segment s as d escr ibed in
t he following.
Knowing t he st ar t ing point and d irect ion of t he r st segment (T ),
and t he d irect ion vect or for each succeed ing segment (T (i 1)),
t he polyline now may be const ruct ed .
The C lmplement at ion (Append ix 2) uses linear int er polat ion as t he
conver gence met hod , and also shows how t o calcu lat e t he p olyline
ver t ices once and are available.
440
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 440
IX.8 IX.8 IX.8 IX.8 IX.8
G GG GGREAT CIRCLE PLOTTING REAT CIRCLE PLOTTING REAT CIRCLE PLOTTING REAT CIRCLE PLOTTING REAT CIRCLE PLOTTING
Alan W. Paet h
NeuralWare Inc.
Pit t sburgh, Pennsylvania
A great circle compr ises t hose point s common t o a sphere and a plane,
t he lat t er passing t hrough t he for mer s cent er. Great circles par t it ion a
sp here int o equ al hemisp her es and for m geodesics: lines of minimal
lengt h spanning t wo point s on t he spheres sur face. These proper t ies
make t hem ubiquit ous t o char t s and ot her applicat ions involving spher i-
cal coord inat es. Examples includ e t he inst ant aneous ground t r ack of a
sat ellit e (wit h or bit al p lanes cont aining t he cent er of t he bod y), t he
Ear t hs present d ay/ night t er minat or (t he sun illuminat ing one hemi-
sphere), and t he way followed by a long-haul air line rout e or a r ad io wave
(t he shor t est pat h having t he least expend ed energy). By d er iving t he
equ a t i on s for a gr ea t ci r cl e i n a n a l yt i c for m, t h e equ a t i on s of
project ionor algor it hms for plot t ingcan be creat ed easily. A simple
[lat / lon] char t (Fig. 1) illust r at es t he great circles for ming t he d ay/ night
t er minat or s on consecut ive mont hs d ur ing fall in t he Nor t her n Hemi-
sphere.
Plot t ing great circles is especially d ifficult when t he t r ack passes near a
pole: Pronounced shift s in inst ant aneous head ing ar ise. In par t icular,
cylind r ical project ions for pat hs of high inclinat ion are d ecid ed ly cur ved .
Great circles cannot be approximat ed suit ably by gener at ing point s along
t he linear pat h spanning (lat 1, lon1) and (lat 2, lon2). Common char t s
cannot easily account for t his cur ves shape, save for t wo azimut hal
project ions: t he st ereogr aphic and gnomonic (Paet h, 1990g). Neit her of
t hese can d epict an ent ire globe on a char t of nit e ext ent .
A simple analyt ic expression for t he gr eat circle int er relat es t he circles
lat it ud e and longit ud e by way of par amet r ic longit ud e and inclinat ion. The
nal for mula t hen may be easily reexpressed in ot her project ions such as
441
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 441
Autumn Termi nator
Northern Hemi sphere
Figure 1. Aut umn t er minat or (Nor t her n Hemisphere)
442
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 442
Mercat or s. Alt hough problems of navigat ion t r ad it ionally were bot h d if-
cu lt and of cent r al imp or t ance t o Renaissance mat hemat ics (Dr re,
1965), t he analyt ic vect or geomet r y of t he last cent ur y simplies t he
d er ivat ion consid er ably; explicit reference t o spher ical t r igonomet r y is
not need ed .
Wit hout loss of gener alit y, consid er t he cent r al sect ion of a sphere by a
plane. If t he plane fully cont ains t he equat or (a great circle wit h d ening
plane XY), t he problem is solved immed iat ely. Ot her wise, t he equat or is
int er sect ed at t wo nod es. Wit hout loss of gener alit y, t hese may be placed
at t he locat ions t90, i.e., rot at ed ont o t he Y axis wit h su bsequ ent
offset t ing of all values of longit ud e. Any great circle now may be mod eled
as a par amet r ic equat or ial circle (no Z component ) and local longit ud e L:
[cos L, sin L, 0], which may be expressed in rect angular coord inat es. This
circle t hen is rot at ed abou t t he Y axis by an inclinat ion . This is
expressed by t he mat r ix prod uct in t he RHS:

X
Y
Z

]
]
]
]

cos cos L
sin L
sin cos L

]
]
]
]

cos 0 sin
0 1 0
sin 0 cos

]
]
]
]

cos L
sin L
0

]
]
]
]
.
The LHS vect or gives t he (X, Y, Z) space posit ion for a unifor m angular
mot ion by L along t he circle. (L is bot h a subt end ed angle and linear
circumferent ial d ist ance along t he t r ack.) As a check, not e t hat X
2
+ Y
2
+ Z
2
= 1, as expect ed : All point s for med lie upon t he sur face of t he unit
sphere. Conver sion bet ween rect angular and spher ical coord inat es (Paet h,
1990b) st at es t hat t an lon = Y/ X, and t an lat = z/

X
2
+ Y
2
. Subst it u-
t ion yield s:
t an lon =

sin L
cos cos L
=sec t an L,
implying t hat
t an L = cos t an lon. (1)
443
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 443
Similar ly,
t an lat =

sin cos L
cos
2
cos
2
L + sin
2
L
. (2)
A simplicat ion of Eq. (2) is sought t o rewor k it in nonpar amet r ic for m,
t hereby yield ing an expression for lat it ud e in t er ms of longit ud e and
inclinat ion. This is possible by subst it ut ing Eq. (1) in Eq. (2), wit h ot her
t r igonomet r ic fu nct ions of L reexpressed in t er ms of t he t angent , as
need ed :
t an lat = t t an cos lon, (3a)
or (wit h proper choice of sign)
lat = arct an (t an cos lon). (3b)
444
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 444
As a d ouble-check of t he equat ion, not e t hat :
lon = 0 lat = (inclinat ion being t he maximum lat it ud e at cent er ),
lon = t 90 lat = 0 (nod es crossed at t 90 for any inclinat ion).
For illust r at ion, four annot at ed values of inclinat ion are plot t ed und er a
global Plat e Car res cylind r ical equid ist ant char t (Paet h, 1990g; Maling
1973). The maximum inclinat ion occur s at t he equinox, when d ay equals
night ever ywhere on t he globe. Here, t he su ns d eclinat ion (celest ial
lat it ud e) is zero; it lies over t he equat or. Thus, t he colat it ud e (angle t o t he
Nor t h Pole) is 90 d egrees and t he t an in Eq. (3b) goes t o innit y.
Minimu m inclinat ion (colat it u d e) cor resp ond s t o t he su ns maximu m
d eclinat ion (lat it u d e) at 23.5. The su n achieves t his maximu m on
December 21 and moment ar ily is st at ionar y in celest ial d eclinat ion; hence
t he t er m wint er solst ice. The globes su bsolar p oint s on t he solst ice
likewise are at 23.5 and d ene t he Tropic of Capr icor n, appear ing as a
d ot t ed line on t he char t . (Capr icor n, Lat in for goat , is t he name of t he
const ellat ion in which t he sun resid ed on t he solst ice at t he t ime of t he
naming of t he const ellat ions; owing t o t he precession of t he equinoxes,
Sagit t ar ius, Lat in for archer, would now be t he proper choice).
To use t he t echnique t o plot a great circle bet ween t wo point s on t he
sur face of a sphere, vect or geomet r y aid s t he d er ivat ion of inclinat ion
angle. Point s (lat 0, lon0) and (lat 1, lon1) are t reat ed as unit vect or s in
sp her ical coord inat es (R = 1) and t hen t r ansfor med int o rect angu lar
coor d in at es (Paet h , 1990g). Th e cr oss-p r od u ct [x
0
, y
0
, z
0
] [x
1
, y
1
, z
1
]
= [y
0
z
1
y
1
z
0
, x
0
z
1
x
1
z
0
, x
0
y
1
x
1
y
0
), i s t h e u n i t n or mal vect or t o
t hat plane common t o bot h vect or s and t o t he or igin. The cross-axis t hen
may be ret ur ned t o spher ical coord inat es, yield ing a longit ud e and lat i-
t ud e value.
The lat it ud e is conver t ed t o colat it ud e: colat = 90 lat t o for m an
inclinat ion value. For inst ance, east ward t r avel along t he equat or (lat = 0)
yield s a nor mal vect or t hrough t he Nor t h Pole (lat = 90, colat = 0);
t r avel t hus is in a plane having zero inclinat ion. The longit ud e of t his
nor mal vect or likewise provid es t he offset angle in longit ud e for proper
placement of t he nod es.
For use in for ming analyt ic, closed -for m for mulae, t he t an lat t er m of
t he RHS of Eq. (3a) may be subst it ut ed d irect ly for project ion for mulae
445
IX.8 GREAT CIRCLE PLOTTING
GRAPHICS GEMS II Edit ed by JAMES ARVO 445
expressed in t er ms of t his funct ion. For inst ance, Mercat or s project ion,
y = ln t an(lon/ 2 + / 4), may be rewr it t en using t he lit t le-known subst i-
t ut ion, t an(x/ 2 t / 4) = tt an x t

1 + tan
2
x (d er ived by t he aut hor
and u sed t o great ad vant age in Paet h (1990a)), which t hen may be
expressed as y = sinh
1
(t an cos lon), yield ing a simple analyt ic ex-
p r ession for great cir cles p lot t ed on cylind r ical, confor mal map s of
globular scale.
446
IX.9 FAST ANTI-ALIASED CIRCLE GENERATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 446
IX.9 IX.9 IX.9 IX.9 IX.9
F FF FFAST ANTI-ALIASED CIRCLE AST ANTI-ALIASED CIRCLE AST ANTI-ALIASED CIRCLE AST ANTI-ALIASED CIRCLE AST ANTI-ALIASED CIRCLE
G GG GGENERATION ENERATION ENERATION ENERATION ENERATION
Xiaolin Wu
Universit y of West ern Ont ano
London, Ont ario, Canada
This gem proposes an elegant t echnique t o rend er ant i-aliased circles
wit h even fewer number of oper at ions t han Bresenhams increment al
circle algor it hm (1977). The success is cred it ed t o a simple t wo-point
ant i-aliasing scheme and t he use of a t able of size

2 / 4R
max
, where R
max
is t he maximum circle r ad ius allowed by t he new algor it hm.
Si mpl e Two- Poi nt Ant i - Al i asi ng Scheme Si mpl e Two- Poi nt Ant i - Al i asi ng Scheme Si mpl e Two- Poi nt Ant i - Al i asi ng Scheme Si mpl e Two- Poi nt Ant i - Al i asi ng Scheme Si mpl e Two- Poi nt Ant i - Al i asi ng Scheme
Due t o t he eight -way symmet r y of t he circle, it sufces t o consid er t he
circle x
2
+ y
2
= r
2
in t he r st oct ant . To suppress t he image jaggies
caused by insufcient spat ial sampling on a gr ayscale d isplay, we may
plot all pixels immed iat ely t o t he r ight and left of t he t rue circular arc
(Fig. 1) wit h t heir int ensit ies inver sely propor t ional t o t heir d ist ances t o
t he arc. To keep even int ensit y on t he d igit al circle, we let t he t ot al
int ensit y I of t wo hor izont ally ad jacent pixels be a const ant . Let I(i, j) be
t he pixel value at t he r ast er point (i, j); t hen t he linear int ensit y int er po-
lat ion bet ween t he t wo ad jacent pixels is given by:

I r
2
j
2
]
, j
( )
I r
2
j
2
]
r
2
j
2
( )
,

I r
2
j
2
]
, j
( )
I I r
2
j
2
]
, j
( )
,
1 j

r
2
.
(1)
Now we d er ive t he algor it hm t o comput e Eq. (1) as j marches in t he y
axis from 0 t o r/

2 in scan-conver t ing t he r st oct ant circular arc. The
447
IX.9 FAST ANTI-ALIASED CIRCLE GENERATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 447
Figure 1. Ant i-aliasing pixel band .
r st issue is t o d et er mine when t he int eger-valued funct ion

r
2
j
2
]
d ecreases by 1 as j increases. We need t he cr it ical values t such t hat

r
2
t 1 ( )
2
]


r
2
t
2
]
= 1 t o move t he pixel band being plot t ed
t o t he left by one st ep . This comp u t at ion can be simp lied by t he
following lemma.
LEMMA 1 The relat ion

r
2
t 1 ( )
2
]


r
2
t
2
]
= 1
holds if and only if

r
2
t 1 ( )
2
]


r
2
t 1 ( )
2
>

r
2
t
2
]


r
2
t
2
.
448
IX.9 FAST ANTI-ALIASED CIRCLE GENERATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 448
Proof. Since

r
2
j
2
is d ecreasing monot onically in j,

r
2
t 1 ( )
2
]


r
2
t 1 ( )
2
>

r
2
t
2
]


r
2
t
2
implies

r
2
t 1 ( )
2
]


r
2
t
2
]
> 0;
but in t he fir st oct ant , we have

r
2
t 1 ( )
2


r
2
t
2
1,
prohibit ing

r
2
t 1 ( )
2
]


r
2
t
2
]
> 1;
hence,

r
2
t 1 ( )
2
]


r
2
t
2
]
= 1.
Figure 2. Wus ant i-aliased circle algor it hm for r st oct ant .
449
IX.9 FAST ANTI-ALIASED CIRCLE GENERATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 449
The only-if par t can be proven by cont r ad ict ion. Assume t hat

r
2
t 1 ( )
2
]


r
2
t
2
]
= 1,
but

r
2
t 1 ( )
2
]


r
2
t 1 ( )
2


r
2
t
2
]


r
2
t
2
.
This requires

r
2
t 1 ( )
2


r
2
t
2
> 1, an impossibilit y in t he
fir st oct ant .
For given r, t he values

r
2
j
2
]


r
2
j
2
, 1 j r/

2 , ser ve
d u al p u r p oses: d et er mining t he p ixel p osit ions as su ggest ed by t he
preced ing lemma and d et er mining t he pixel int ensit ies as in Eq. (1). Let
t he int ensit y r ange for t he d isplay be from 0 t o 2
m
1, and d ene t he
int eger var iable:
D(r,j) =

2
m
1
( )
r
2
j
2
]
r
2
j
2
( )
+ 0. 5
]
.
(2)
Figure 3. Bresenhams circles (left ) and Wus ant i-aliased circles (r ight ).
450
IX.9 FAST ANTI-ALIASED CIRCLE GENERATION
GRAPHICS GEMS II Edit ed by JAMES ARVO 450
Then it follows from Eq. (1) t hat

I r
2
j
2
]
, j
( )
= D(r, j),

I r
2
j
2
]
, j
( )
=

D r, j
( )
,
1 j

r
2
,
(3)
where

D r, j
( ) is t he int eger valu e obt ained t hr ou gh bit wise-inver se
op er at i on on D(r, j), si n ce

I r
2
j
2
]
, j
( )
+

I r
2
j
2
]
, j
( )
= I =
2
m
1, and since t he int ensit y values are int eger s. By Eq. (2), ever y
d ecr ement of t he fu nct ion,

r
2
j
2
]


r
2
j
2
as j incr eases, is
reect ed by a d ecrement of D(r, j); t hus, D(r, j) can be used t o cont rol
t he scan conver sion of t he circle. The new ant i-aliased circle algor it hm
based on precomput ed D(r, j) is ext remely simple and fast . The algo-
r it hm for t he r st oct ant is d escr ibed by t he owchar t in Fig. 2.
The inner loop of t he ant i-aliased circle algor it hm r equires even fewer
oper at ions t han Bresenhams circle algor it hm. Of cour se, t he gains in
image qu alit y and scan-conver sion sp eed are obt ained by u sing t he
D(r, j) t able. If R
max
is t he maximu m r ad iu s hand led by t he cir cle
gener at or, t hen t he t able size will be

2 / 4R
max
It is my opinion t hat t he
r apid ly d ecreasing memor y cost makes t he preced ing simple id ea a viable
solut ion t o real-t ime ant i-aliased circle gener at ion. For inst ance, for a
64K-byt es ROM, t he preced ing algor it hm can d isplay ant i-aliased circular
arcs of r ad ius up t o 430. Wit hout t he precomput ed t able D(r, j), t he
ant i-aliased circle algor it hm can be implement ed by comput ing t he func-
t ion D(r, j).
The per for mance of t he new ant i-aliased circle algor it hm is d emon-
st r at ed by Fig. 3.
See a l so (105) Rendering A nt i-A liased Lines, Kelv in
Thompson
451 GRAPHIC GEMS II Edit ed by DAVID KIRK 451
REFERENCES
R RR RREFERENCES EFERENCES EFERENCES EFERENCES EFERENCES
Ad obe Sys t ems , In c. (1988). User s Guide t o A dobe Illust rat or 88. (IX. 3 A Si mp l e
For mu lat ion for Cu r ve Int er polat ion wit h Var iable Cont rol Point Appr oximat ion)
Ad obe Syst ems, Inc. (1985a). POSTSCRIPT

Language Reference Manual, ISBN 0-201-


10174-2. Ad d ison-Wesley, Read ing, MA (I.9 Scanline Coher ent Shape Algebr a)
Ad obe Syst ems, In c. (1985b). POSTSCRIPT

Language Tut orial and Cookbook, ISBN


0-201-10179-3. Ad d ison-Wesley, Read ing, MA (I.9 Scanline Coherent Shape Algebr a)
Air ey, John M., Rohlf, John H., and Br ooks, Fred er ick P. (1990). Toward s Image Realism
wit h Int er act ive Upd at e Rat es in Complex Vir t u al Bu ild ing Environment s, Comput er
Graphi cs A CM Workshop on Int eract i v e Graphi cs Proceedi ngs 24(1), 4150. (VI. 4
Rad iosit y via Ray Tr acing)
Amanat id es, John, and Mit chell, Don P. (1990). Ant ialiasing of Int er laced Vid eo Anima-
t ion, Comput er Graphics 4(24), 7785. (III.6 Television Color Encod ing and Hot
Br oad cast Color s)
Amanat id es, J. and Woo, A. (1987). A Fast Voxel Tr aver sal Algor it hm for Ray Tr acing,
EuroGraphics 87. (V.7 Avoid ing Incor r ect Shad ow Int er sect ions for Ray Tr acing)
And er berg, M. R. (1973). Clust er Analysis for Applicat ions. Acad emic Press, New Yor k.
(III.2 Efcient St at ist ic Compu t at ions for Opt imal Color Qu ant izat ion)
Ap p l e Comp u t er (1988). Insi de Maci nt osh, Vol ume V, Ch a p t er 6. Ad d i s on -Wes l ey,
Read ing, MA. (III.l Efcient Inver se Color Map Compu t at ion)
Ar nald i, Bru no, Pr iol, Thier r y, and Bou at ou ch, Kad i (1987). A New Space Su bd ivision
Met hod for Ray Tr acing CSG Mod elled Scenes, The Visual Comput er, 3(3), 98108.
(V.4 Imp roved Ray Tagging for Voxel-Based Ray Tr acing; V.5 Efciency Improvement s
for Hier archy Tr aver sal in Ray Tr acing; V.7 Avoid ing Incor rect Shad ow Int er sect ions for
Ray Tr acing)
At kinson, William D. (Nov. 11, 1986). Met hod and Appar at u s for Image Compr ession and
Manip u lat ion, Unit ed St at es Pat ent nu mber 4,622,545. (I.9 Scanline Coherent Shap e
Algebr a)
Ball, W. W. R. (1939). Mat hemat ical Recreat ions & Essays. McMillan , Lon d on . (IV.3
Exact Dihed r al Met r ics for Common Polyhed r a)
452 GRAPHIC GEMS II Edit ed by DAVID KIRK 452
REFERENCES
Bar r y, Phillip J., and Goldman, Ronald N. (1988). A Recur sive Evaluat ion Algor it hm for a
Class of Cat mu ll-Rom Splines, Comput er Graphics 22(4), 199204. (VIII.4 Using Geomet r ic
Const r u ct ions t o Int er polat e Or ient at ion wit h Qu at er nions)
Bau m, Daniel R., Ru shmeier, Holly E., and Winget , James M., Improving Rad iosit y
Sol u t i on s t h r ou gh t h e Use of An al yt i cal l y Det er mi n ed For m-Fact or s, Comput er
Graphi cs (SIGGRA PH89 Proceedi ngs), 23, (3), p p . 325334. (VI . 1 Imp l emen t i n g
Progressive Rad iosit y wit h User-Provid ed Polygon Display Rou t ines)
Bau mgar t , B. G. (1975). A Polyhed r on Rep r esent at ion for Comp u t er Vision, Proc.
NCC. (IV.6 Maint aining Winged -Ed ge Mod els)
Bau mgar t , B. G. (1974). Geomet r ic Mod eling for Compu t er Vision, St anfor d AI Project
memo 249. (IV.6 Maint aining Winged -Ed ge Mod els)
Beeler, M., Gosper, R. W., and Schroeppel, R. (1972). HAKMEM, Massachuset t s Inst it ut e
of Technology Art icial Int elligence Laborat ory Report AIM239. (VII.3 Of Int eger s,
Field s, and Bit Cou nt ing)
Behnke, H., Bachmann, F., Flad t , K., and Su ss, W. (1983). Fundament als of Mat hemat -
ics, Vol. III, Analysis. MIT Press, Cambr id ge, MA, 191195. (I.6 Ap p oloniu ss 10t h
Problem)
Bier i, H., and Nef, W. (1984). Algor it hms for t he Eu ler Char act er ist ic and Relat ed
Ad d i t i ve Fu n ct i on a l s of Di gi t a l Object s, Comput er Vision, Graphics, and Image
Processing 28, 166175. (II.12 Compu t ing t he Area, t he Circu mfer ence, and Genu s of
a Binar y Digit al Image)
Boeh m, W. (1984). Efci en t Eva l u a t i on of Sp l i n es, Comput ing 33, 171177. (X. 4
Symmet r ic Evalu at ion of Polynomials)
Boot h, Kellogg (1989). Graphics Int erface 89 (London), pr ivat e conver sat ion. (VIII.3 Of
Int eger s, Field s, and Bit Cou nt ing)
Bor n, M., and Wolf, E. (1975). Principles of Opt ics, 5t h ed. Pergamon Press, Oxfor d .
(V.8 A Bod y Color Mod el: Absor pt ion of Light t hrou gh Tr anslu cent Med ia; V.9 More
Shad ow At t enu at ion for Ray Tr acing Tr ansparent or Tr anslu cent Object s)
Bou knight , W. I. (1970). A Pr oced u re for t he Gener at ion of 3D Halft oned Compu t er
Gr ap hics Present at ions, Comm. ACM 13(9), 527536. (IV.9 Int er Phong Shad ing)
Br ainar d , David H. (1989). Calibr at ion of a Compu t er Cont rolled Color Monit or, Color
Research and Applicat ion 14, 2334. (III.7 An Inexp ensive Met hod of Set t ing t h e
Monit or Whit e Point )
Br esenham, J. E. (1977). A Linear Algor it hm for Increment al Digit al Display of Circu lar
Arcs, Comm. ACM 20(2), 750752. (IX.9 Fast Ant i-Aliased Circle Gener at ion)
Bu r r u s, C. S., and Par ks, T. W. (1985). DFT/FFT and Convolut ion Algorit hms. Wiley
and Sons, New Yor k. (VIII.2 Fast er Fou r ier Tr ansfor m)
Bu t z, Ar t hu r R. (1971). Alt er nat ive Algor it hm for Hilber t s Space-Filling Cu r ve, IEEE
Transact ions on Comput ers, C-20, 424426. (I.7 A Pean o Cu r ve Gen er at i on Al go-
r it hm)
Car ling, Richard (1990). Mat r ix Inver sion, Graphics Gems (And rew S. Glassner, ed .).
Acad emic Press, Bost on, 470471. (VII.5 Fast Mat r ix Inver sion)
453 GRAPHIC GEMS II Edit ed by DAVID KIRK 453
REFERENCES
Cashwell, E. D., and Ever et t , C. J. (1969). Int ersect ion of a Ray wit h a Surface of Third
or Fourt h Degree, Los Alamos Scient ic Labor at or y Rep or t LA-4299 UC32 Mat hemat -
ics and Comp u t er s TID-4500, Los Alamos, New Mexico. (V.2 Int er cep t ing a Ray wit h an
Ellip t ical Toru s)
Ca t mu l l , Ed wi n (1979). A Tu t or i a l on Comp en sa t i on Ta bl es, Comput er Graphics 13,
1-7. (III.8 Some Tip s for Making Color Har d cop y)
Cohen, Michael F., Chen, Shenchang Er ic, Wallace, John R., and Gr eenberg, Donald P.
(1988). A Pr ogr essi ve Ren emen t Ap p r oa ch t o Fa st Ra d i osi t y Ima ge Gen er a t i on ,
Comput er Graphi cs (SIGGRA PH 88 Proceedi ngs) 22(4) 7584. (VI. l Imp l emen t i n g
Progressive Rad iosit y wit h User-Provid ed Polygon Disp lay Rou t ines; VI.4 Rad iosit y via
Ray Tr acing)
Coh en , Mi ch a el F. , a n d Gr een ber g, Don a l d P. (1985). Th e Hemi -Cu be: A Ra d i os i t y
Sol u t i on for Comp l ex En v i r on men t s , Comput er Graphi cs (SIGGRA PH 85 Proceed-
i ngs) 19(3), 3140. (VI. 1 Imp l emen t i n g Pr ogr es s i v e Ra d i os i t y wi t h Us er -Pr ov i d ed
Pol ygon Di sp l ay Rou t i n es; Vl .2 A Cu bi c Tet r ah ed r al Ad ap t at i on of t h e Hemi -Cu be
Algor it hm; Vl.4 Rad iosit y via Ray Tr acing)
Cook, R. L. (1982). A Reect ion Mod el for Realist ic Image Synt hesis, Mast er s Thesis,
Cor nell Univer sit y, It haca, New Yor k. (V.9 More Shad ow At t enu at ion for Ray Tr acing
Tr ansp arent or Tr anslu cent Object s)
Cook, R. L., and Tor r ance, K. (1982). A Reect ance Mod el for Comp u t er Gr ap hics ACM
Transact ions on Graphics 1(1), 724. (V.9 Mor e Sh ad ow At t en u at i on for Ray Tr aci n g
Tr ansp arent or Tr anslu cent Object s)
Cowan, William B. (1987). Color imet r ic Prop er t ies of Vid eo Monit or s, Not es for OSA
Short Course. (III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Cowan, William B. (1983). An Inexp ensive Scheme for Calibr at ion of a Colou r Monit or in
Ter ms of CIE St a n d a r d Coor d i n a t es , Comput er Graphi cs 17, 315321. (III. 7 An
Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Cowan, William B., and Rowell, Nelson (1986). On t he Gu n Ind ep end ence and Phosp hor
Con s t a n cy of Col ou r Vi d eo Mon i t or s , Color Research and A pplicat ion 11, S34-S38.
(III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Coxet er, H. S. M. (1948). Conv ex Pol y t opes. Met h u en , Lon d on . (IV. 3 Exa ct Di h ed r a l
Met r ics for Common Polyhed r a)
d e Boor, C. (1987). B-for m ba s i cs , Geomet ri c Model i ng: A l gori t hms and New Trends
(G. Far in, ed .). SIAM, 131148. (IX.1 Least -Squ ares Ap p r oximat ions t o Bzier Cu r ves
and Su r faces; IX.2 Beyond Bzier Cu r ves)
d e Boor, Ca r l (1972). On Ca l cu l a t i n g wi t h B-Sp l i n es , Journal of A pprox i mat i on
Theory 6, 5062. (VIII . 4 Geomet r i c Con s t r u ct i on s t o In t er p ol a t e Or i en t a t i on wi t h
Qu at er nions)
Dit chbu r n, R. W. (1976). Light , Third Ed. Acad emic Press, Lond on. (V.9 Mor e Shad ow
At t enu at ion for Ray Tr acing Tr ansp arent or Tr anslu cent Object s)
Don a t o, Nol a , a n d Rocch et t i , Rober t (1988). Tech n i qu es for Ma n i p u l a t i n g Ar bi t r a r y
Regions, u np u blished . Su n Microsyst ems, Inc. (I.3 Scanline Coherent Shap e Algebr a)
454 GRAPHIC GEMS II Edit ed by DAVID KIRK 454
REFERENCES
Dr r e, Heinr ich (1965). The Loxod r ome Pr oblem, (76 and 77), 100 Great Problems of
Element ary Mat hemat ics (t r anslat ed from Ger man). Dover, Lond on. (IX.8 Great Cir cle
Plot t ing)
Du ff, Tom (1984). Fa mi l i es of Loca l Ma t r i x Sp l i n es , The Mat hemat i cs of Comput er
Graphics (SIGGRAPH 1984 Cou r se Not es #15). (IX.3 A Simp le For mu lat ion for Cu r ve
Int er p olat ion wit h Var iable Cont rol Point Ap p r oximat ion)
Du ff, T. (1979). Smoot hly Shad ed Rend er ings of Polyhed r al Object s on Rast er Disp lays,
Comput er Graphics SIGGRAPH 79 Proc. 13(2), 270275. (IV.9 Int er Phong Shad ing)
Dyer, C. R. , Rosen fel d , A. , a n d Sa met , H. (1980). Regi on Rep r esen t a t i on : Bou n d a r y
Cod es fr om Qu a d t r ees , Comm. A CM 23(3), 171179. (IV. 7 Qu a d t r ee/ Oct r ee-t o-
Bou nd ar y Conver sion)
Eu cl i d , El ement s, Book III, Proposi t i on 20. (VIII. 5 A Ha l f-An gl e Id en t i t y for Di gi t a l
Comp u t at ion: The Joys of t he Halved Tangent )
Evans, David M. W. (1987). An Imp roved Digit -Rever sal Per mu t at ion Algor it hm for t he
Fa s t Fou r i er a n d Ha r t l ey Tr a n s for ms , IEEE Trans. A SSP. (VIII. 2 Fa s t er Fou r i er
Tr ansfor m)
Fa r i n , G. (1988). Curv es and Surf aces f or Comput er A i ded Geomet ri c Desi gn: A
Pract ical Guide. Acad emi c Pr ess, New Yor k. (IX. 1 Least -Squ ar es Ap p r oxi mat i on s t o
Bzier Cu r ves and Su r faces)
Fa u x, I. D. , a n d Pr a t t , M. J. (1979). Comput at ional Geomet ry for Design and Manufac-
t ure. Ellis Hor wood Lt d ., Chichest er, England 73. (IV.2 Get t ing Arou nd on a Sp her e)
Floyd , R. W., and St einberg, L. (1975). An Ad ap t ive Algor it hm for Sp at ial Gr ay Scale,
Int ernat i onal Sy mposi um Di gest of Techni cal Papers, Soci et y for In for ma t i on Di s -
p lays, 36. (II.2 A Comp ar ison of Digit al Halft oning Techniqu es; II.3 Color Dit her ing)
Fol ey, Ja mes D. , a n d va n Da m, An d r i es (1982). Fundament als of Int eract iv e Comput er
Graphics. Ad d ison-Wesley, Read ing, MA. (VII.5 Fast Mat r ix Inver sion)
Fol ey, Ja mes D. , va n Da m, An d r i es , Fei n er, St even K. , a n d Hu gh es , Joh n F. (1990).
Comput er Graphi cs Pri nci pl es and Pract i ce. Ad d i s on Wes l ey, Rea d i n g, MA. (I. 9
Scanline Coherent Shap e Algebr a; II.3 Color Dit her ing; IV.8 Three-Dimensional Homo-
geneou s Clip p ing of Tr iangle St r ip s; VI.4 Rad iosit y via Ray Tr acing)
Fr eema n , H. (1974). Comp u t er Pr ocessi n g of Li n e-Dr a wi n g Ima ges, A CM Comput er
Surveys 6, 5797. (IV.7 Qu ad t ree/ Oct ree-t o-Bou nd ar y Conver sion)
Gar gant ini, I. (1982a). An Effect ive Way t o Rep resent Qu ad t r ees, Comm. ACM 25(12),
905-910. (IV.7 Qu ad t r ee/ Oct ree-t o-Bou nd ar y Conver sion)
Gar gant ini, I. (1982b). Linear Oct rees for Fast Processing of Three-Dimensional Object s,
Comput er Graphi cs and Image Processi ng 20(4), 365374. (IV. 7 Qu a d t r ee/ Oct r ee-
t o-Bou nd ar y Conver sion)
Gar gan t i n i , I., an d Hen r i ci , P. (1972). Ci r cu l ar Ar i t h met i c an d t h e Det er mi n at i on of
Pol yn omi a l Zer os , Numeri sche Mat hemat i k 18, 305320. (I. 6 Ap p ol on i u s s 10t h
Problem)
455 GRAPHIC GEMS II Edit ed by DAVID KIRK 455
REFERENCES
Ger vau t z, Michael, and Pu rgat hofer, Wer ner (1990). A Simp le Met hod for Color Qu ant i-
z a t i on : Oct r ee Qu a n t i z a t i on , Graphi cs Gems (A. Gl a s s n er, ed . ). Aca d emi c Pr es s ,
Bost on. (III. 1 Efcient Inver se Color Map Comp u t at ion; 111.2 Efcient St at ist ic Comp u -
t at ions for Op t imal Color Qu ant izat ion; 111.5 Map p ing RGB Tr ip les ont o 16 Dist inct
Valu es)
Gi l ber t , Wi l l i a m J. (1976). Modern A l gebra wi t h A ppl i cat i ons. Joh n Wi l ey a n d Son s ,
New Yor k. (VII.5 Fast Mat r ix Inver sion)
Glassner, And rew S. (199Oa). Usefu l Tr igonomet r y, Graphics Gems (A. Glassner, ed .).
Acad emic Press, Bost on, 1317. (Vlll.5 A Half-Angle Id ent it y for Digit al Comp u t at ion:
The Joys of t he Halved Tangent )
Gl a s s n er, An d r ew S. (1990b). Us efu l 2D Geomet r y, Graphi cs Gems (An d r ew S.
Glassner, ed .). Acad emic Press, Bost on, 311. (1.6 Ap p oloniu ss 10t h Problem)
Glassner, A. S., et al. (1989). An Int roduct ion t o Ray Tracing. Acad emic Pr ess, Lond on,
92-93. (V.2 Int er cep t ing a Ray wit h an Ellip t ical Tor u s); 121160 (V.9 Mor e Shad ow
At t enu at ion for Ray Tr acing Tr ansp arent or Tr anslu cent Object s)
Gol d man , Ron al d (1990a). Mat r i ces an d Tr an sfor mat i on s, Graphics Gems (An d r ew S.
Glassner, ed .). Acad emic Pr ess, Bost on. (Vll.2 Recover ing t he Dat a from t he Tr ansfor-
mat ion Mat r ix; Vll.3 Tr ansfor mat ions as Exp onent ials)
Gol d ma n , Ron a l d (1990b). Tr i a n gl es , Graphi cs Gems (An d r ew S. Gl a s s n er, ed . ).
Acad emic Press, Bost on, 2023. (1.1 The Ar ea of a Simp le Polygon)
Gold smit h, Jeffrey, and Salmon, John (1987). Au t omat ic Cr eat ion of Object Hier ar chies
for Ra y Tr a ci n g, IEEE Comput er Graphi cs and A ppl i cat i ons 7(5), 1420. (V. 5
Efciency Imp rovement s for Hier ar chy Tr aver sal in Ray Tr acing)
Gon zal ez, Rafael C., an d Wi n t z, Pau l (1987). Digit al Image Processing, Second Edit ion.
Ad d i son -Wesl ey, Rea d i n g, MA. (II. 1 Ima ge Smoot h i n g a n d Sh a r p en i n g by Di scr et e
Convolu t ion)
Gor a l , Ci n d y M. , Tor r a n ce, Ken n et h E. , Gr een ber g, Don a l d P. , a n d Ba t t a i l e, Ben n et t
(1984). Mod el i n g t h e In t er a ct i on of Li gh t Bet ween Di ffu s e Su r fa ces , Comput er
Graphi c. s (SIGGRA PH 84 Proceedi ngs) 18(3), 213222. (Vl . 1 Imp l emen t i n g Pr ogr es -
sive Rad iosit y wit h User -Pr ovid ed Polygon Disp lay Rou t ines; Vl.4 Rad iosit y via Ray
Tr acing)
Gosling, James (1986). Cu r ves Mad e Tr ivial, u np u blished . (1.9 Scanline Coherent Shap e
Algebr a)
Gou r a u d , H. (1971). Con t i n u ou s Sh a d i n g of Cu r ved Su r fa ces, IEEE Transact ions on
Comput ers C-20(6), 623629. (IV. 9 In t er Ph on g Sh a d i n g; VI. 1 Imp l emen t i n g Pr ogr es-
sive Rad iosit y wit h User-Provid ed Polygon Disp lay Rou t ines)
Gr aham, R. L. (1972). An Efcient Algor it hm for Det er mining t he Convex Hu ll of a
Pl a n a r Set , Inf ormat i on Processi ng Let t er. s 1, H32133. (Vl l l . 7 Fa s t Ap p r oxi ma t i on
t o t he Arct angent )
Gr a s s ma n n , E. , a n d Rokn e, J. (1979). Th e Ra n ge of Va l u es of a Ci r cu l a r Comp l ex
Polynomial over a Cir cu lar Comp lex Int er val, Comput ing 23, 139169. (1.4 An Easy
Bou nd ing Cir cle)
456 GRAPHIC GEMS II Edit ed by DAVID KIRK 456
REFERENCES
Gu bareff, G., Janssen, J., and Tor borg, R. (1960). Thermal Radiat ion Propert ies Survey:
A Review of t he Lit erat ure. Honeywell Resear ch Cent er, Minneap olis. (V.8 A Bod y
Color Mod el: Absor pt ion of Light t hrou gh Tr anslu cent Med ia)
Gu ibas, Leo, and St ol, Jorge (1982). A Langu age for Bit map Manip u lat ion, ACM
Transact ions on Graphics 1(3), 191214. (VIII.5 A Half-An gle Id en t it y for Digit al
Comp u t at ion: The Joys of t he Halved Tangent )
Haines, Er ic A., and Gr eenberg, Donald P. (1986). The Light Bu ffer : A Ray Tr acer
Sh a d ow Tes t i n g Accel er a t or, IEEE Comput er Graphi cs and A ppl i cat i ons 6(9),
616. (V.5 Efciency Imp rovement s for Hier archy Tr aver sal in Ray Tr acing; V.6 A
Recu r sive Shad ow Voxt el Cache for Ray Tr acing)
Hall, E. L., et al. (1971). A Su r vey of Pr eprocessing and Feat u re Ext r act ion Techniqu es
for Rad iogr aphic Images, IEEE Trans. Comp. 20(9), 1033. (II.9 Image File Compr es-
sion Mad e Easy)
Ha l l , R. (1990). Il l umi nat i on and Col or i n Comput er Generat ed Imagery. Sp r i n ger -
Ver lag, New Yor k. (II.3 Color Dit her ing; III.6 Television Color Encod ing and Hot
Br oad cast Color s)
Hall, R. (1986). A Char act er izat ion of Illu minat ion Mod els and Shad ing Techniqu es, The
Visual Comput er 2(5), 268277. (IV.9 Int er Phong Shad ing)
Hall, R. A. (1983). A Met hod ology for Realist ic Image Synt hesis, Mast er s Thesis,
Cor nell Univer sit y, It haca, New Yor k. (V.8 A Bod y Color Mod el: Absor pt ion of Light
t hr ou gh Tr anslu cent Med ia; V.9 Mor e Shad ow At t enu at ion for Ray Tr acing Tr ansparent
or Tr anslu cent Object s)
Hall, R. A., and Greenberg, D. P. (1983). A Test bed for Realist ic Image Synt hesis, IEEE
Comput er Graphi cs and A ppl i cat i ons 3(10), 1020. (V. 8 A Bod y Col or Mod el :
Absor p t ion of Light t hrou gh Tr anslu cent Med ia; V.9 More Shad ow At t enu at ion for Ray
Tr acing Tr ansparent or Tr anslu cent Object s)
Hanr ahan, P. (1982). Cr eat ing Volu me Mod els From Ed ge-Ver t ex Gr aphs, SIGGRAPH
82, 7784. (IV.6 Maint aining Winged -Ed ge Mod els)
Hawley, St ep hen (1990). Ord er ed Dit her ing, Graphics Gems (And rew S. Glassner, ed .).
Acad emic Press, Bost on, 176178. (II.2 A Comp ar ison of Digit al Halft oning Tech-
niqu es; II.3 Color Dit her ing)
Heckber t , Pau l S. (1990). Ad apt ive Rad iosit y Text u res for Bid ir ect ional Ray Tr acing,
Comput er Graphics SIGGRAPH 90 Pr oceed ings 24(4), 145154. (III.5 Det ect ion of
Shad ow Bou nd ar ies for Ad apt ive Meshing in Rad iosit y)
Heckber t , P. (1982). Color Image Qu ant izat ion for Fr ame Bu ffer Disp lay, Comput er
Graphics 16(3), 297307. (III.l Efcient Inver se Color Map Comp u t at ion; III.2 Ef-
cient St at ist ic Compu t at ions for Opt imal Color Qu ant izat ion)
Hong, M. T., Magnenat Thalmann, N., and Thalmann, D. (1988). A Gener al Algor it hm For
3D Shap e Int er p olat ion in a Facet -Based Rep r esent at ion, Graphics Int erface Proc.
88, Ed mont on, Canad a. (IV.9 Int er Phong Shad ing)
457 GRAPHIC GEMS II Edit ed by DAVID KIRK 457
REFERENCES
Jar vis, J. F., Ju d ice, N., and Ninke, N. H. (1976). A Su r vey of Techniqu es for t he Disp lay
of Con t i n u ou s Ton e Pi ct u r es on Bi l ev el Di s p l a ys , Comput er Graphi cs and Image
Processing 5(1), 1340. (11.2 A Comp ar ison of Digit al Halft oning Techniqu es)
Jen ki n s, F., an d Wh i t e, H. (1937). Fundament als of Physical Opt ics. McGr aw-Hi l l , New
Yor k. (V.8 A Bod y Color Mod el: Absor p t ion of Light t hrou gh Tr anslu cent Med ia; V.9
More Shad ow At t enu at ion for Ray Tr acing Tr ansp arent or Tr anslu cent Object s)
Joh n s on , N. W. (1966). Con vex Pol yh ed r a wi t h Regu l a r Fa ces , Canadian Journal of
Mat hemat ics 18(1), 169200. (IV.3 Exact Dihed r al Met r ics for Common Polyhed r a)
Kailat h, Thomas (1980). Linear Syst ems. Pr ent ice-Hall, Englewood Cliffs, NJ. (Vll.5 Fast
Mat r ix Inver sion)
Ka y, D. S. , a n d Gr een ber g, D. P. (1979). Tr a n s p a r en cy for Comp u t er Syn t h es i z ed
Ima ges , A CM Comput er Graphi cs (SIGGRA PH 79) 13(2), 158164. (V. 8 A Bod y
Color Mod el: Absor p t ion of Light t hrou gh Tr anslu cent Med ia)
Kay, Timot hy L., and Kajiya, James T. (1986). Ray Tr acing Comp lex Scenes, Comput er
Graphi cs 20(4), 269278. (V. l Fa s t Ra y-Con v ex Pol yh ed r on In t er s ect i on ; V. 5 Ef-
ciency Imp r ovement s for Hier archy Tr aver sal in Ray Tr acing)
Ki r k, Da vi d , a n d Ar vo, Ja mes (1988). Th e Ra y Tr a ci n g Ker n el , Proceedings of A us-
graph 88, Mel bourne, A ust ral i a. (V. 4 Imp r ov ed Ra y Ta ggi n g for Voxel -Ba s ed Ra y
Tr acing)
Koch a n ek, Dor i s , a n d Ba r t el s , Ri ch a r d H. (1984). In t er p ol a t i n g Sp l i n es wi t h Loca l
Ten s i on , Con t i n u i t y, a n d Bi a s Con t r ol , Comput er Graphi cs 18(3), 3341. (IX. 3 A
Simp le For mu lat ion for Cu r ve Int er p olat ion wit h Var iable Cont rol Point Ap p r oximat ion)
La sset er, Joh n (1987). Pr i n ci p l es of Tr a d i t i on a l An i ma t i on Ap p l i ed t o 3D Comp u t er
An i mat i on , Comput er Graphics 21(4), 3544. (IX.3 A Si mp l e For mu l at i on for Cu r ve
Int er p olat ion wit h Var iable Cont rol Point Ap p r oximat ion)
Lawson , C. L., an d Han son , R. J. (1974). Solving Least Squares Problems (Prent ice-Hall
Series in A ut omat ic Comput at ion). Pr en t i ce-Ha l l . (IX. 1 Lea st -Squ a r es Ap p r oxi ma t i on s
t o Bzier Cu r ves and Su r faces)
Lee, D. T., an d Pr ep ar at a, Fr an co (1984). Comp u t at ion al Geomet r yA Su r vey, IEEE
Transact i ons on Comput ers C33(12), 1072-1101. (VIII . 7 Fa s t Ap p r oxi ma t i on t o t h e
Arct angent )
Lee, M. E. (1986). Develop ment of a Ray Tr acing Mod el for Realist ic Image Synt hesis,
Mast er s Thesis, Univer sit y of Tu lsa, Tu lsa, Oklahoma. (V.9 More Shad ow At t enu at ion
for Ray Tr acing Tr ansp ar ent or Tr anslu cent Object s)
Lee, M. E., Red ner, R. A., and Uselt on, S. P. (1985). St at ist ically Op t imized Samp ling for
Di s t r i bu t ed Ra y Tr a ci n g, Comput er Graphi cs 19(3), 6167. (V. 9 Mor e Sh a d ow
At t enu at ion for Ray Tr acing Tr ansp arent or Tr anslu cent Object s)
Li n s t er n i k, L. A. (1963). Conv ex Fi gures and Pol y hedra (t r a n s l a t ed fr om Ru s s i a n ).
Dover, New Yor k. (IV.3 Exact Dihed r al Met r ics for Common Polyhed r a)
Li u , C. L. (1968). Int roduct ion t o Combinat orial Mat hemat ics. McGr a w-Hi l l , New Yor k.
(III.2 Efcient St at ist ic Comp u t at ions for Op t imal Color Qu ant izat ion)
458 GRAPHIC GEMS II Edit ed by DAVID KIRK 458
REFERENCES
Loop , Ch ar l es, an d DeRose, Ton y (1990). Gen er al i zed B-Sp l i n e Su r faces of Ar bi t r ar y
Top ology, ACM, SIGGRAPH 90 24(4), 347356. (IX.2 Beyond Bzier Cu r ves)
Loop , Char les, and DeRose, Tony (1989). A Mu lt isid ed Gener alizat ion of Bezier Su r faces,
ACM Transact ions on Graphics 8(3), 204234. (IX.2 Beyond Bzier Cu r ves)
Lor i g, G. (1986). A dv anced Image Sy nt hesi s: Shadi ng (G. En d er l e, M. Gr a v e, a n d F.
Lillegen, ed s.). Sp r inger-Ver lag. (IV.9 Int er Phong Shad ing)
Lu cassen, Marcel P., and Walr aven, Jan (1990). Evalu at ion of a Simp le Met hod for Color
Mon i t or Reca l i br a t i on , Col or Research and A ppl i cat i on 15, 321326. (III. 7 An
Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Ma gn en a t Th a l ma n n , N. , a n d Th a l ma n n , D. (1987a ). Image Sy nt hesi s: Theory and
Pract ice, Sp r inger-Ver lag, Tokyo. (IV.9 Int er Phong Shad ing)
Magnenat Thalmann, N., and Thalmann, D. (1987b). The Dir ect ion of Synt het ic Act or s in
t h e Fi l m Rendez -Vous Mont ral , IEEE Comput er Graphi cs and A ppl i cat i on
7(12), 919. (IV.9 Int er Phong Shad ing)
Maillot , Pat r ick-Gilles (1986). Cont r ibu t ion lt u d e d es Syst mes Gr ap hiqu es: Archit ec-
t u r es Logicielle et Mat r ielle, Ph.D. Thesis, Univer sit y Clau d e Ber nard , Lyon I, Lyon,
Fr ance. (IV.8 Thr ee-Dimensional Homogeneou s Clip p ing of Tr iangle St r ip s)
Mal i n g, D. H. (1973). Coordinat e Syst ems and Map Project ions, Lon d on , Geor ge Ph i l i p
and Son, (Descr ibing t he Equ id ist ant Cylind r ical Plat e Car r e of Anaximand er, circa
550 B.C.) (IX.8 Great Circle Plot t ing)
Ma l l ey, Th oma s J. V. (1988). A Sh a d i n g Met h od for Comp u t er Gen er a t ed Ima ges ,
Mast er s Thesis, Univer sit y of Ut ah. (VI.4 Rad iosit y via Ray Tr acing)
Meyer, Ga r y W. (1990). Th e Imp or t a n ce of Gu n Ba l a n ci n g i n Mon i t or Ca l i br a t i on ,
Percei v i ng, Measuri ng, and Usi ng Col or (Mi ch a el H. Br i l l , ed . ). Proc. SPIE 1250,
6979. (III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Meyer, Gar y W. (1986). Color Calcu lat ions for and Percep t u al Assessment of Comp u t er
Gr ap hic Images, Ph.D. d isser t at ion, Cor nell Univer sit y. (III.7 An Inexp ensive Met hod
of Set t ing t he Monit or Whit e Point )
Meyer, Gar y W., and Gr eenberg, Donald P. (1987). Per cep t u al Color Sp aces for Com-
p u t er Gr a p h i cs , Col or and t he Comput er (H. Joh n Du r et t , ed . ). Aca d emi c Pr es s ,
Bost on, 83100. (III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Mon t a n i , C. (1984). Regi on Rep r es en t a t i on : Pa r a l l el Con n ect ed St r i p es , Comput er
Vi si on, Graphi cs and Image Processi ng 28, 139165. (IV. 7 Qu a d t r ee/ Oct r ee-t o-
Bou nd ar y Conver sion)
Mor t on , M. (1990). A Di gi t a l Di s s ol v e Effect , Graphi cs Gems (A. Gl a s s n er, ed . ).
Acad emic Press, Bost on. (III.l Efcient Inver se Color Map Comp u t at ion)
Newman , Wi l l i am M., an d Sp r ou l l , Rober t F. (1979). Principles of Int eract ive Comput er
Graphics. McGr aw-Hill, New Yor k. (VII.5 Fast Mat r ix Inver sion; VIII.5 A Half-Angle
Id ent it y for Digit al Comp u t at ion: The Joys of t he Halved Tangent )
459 GRAPHIC GEMS II Edit ed by DAVID KIRK 459
REFERENCES
Paet h, Alan W. (1990a). A Fast Algor it hm for Gener al Rast er Rot at ion, Graphics Gems
(A. Glassner, ed .). Acad emic Press, Bost on, 189. (VIII.3 Of Int eger s, Field s, and Bit
Cou nt ing; VIII.5 A Half-Angle Id ent it y for Digit al Compu t at ion: The Joys of t he Halved
Tangent )
Paet h, Alan W. (1990b). A Fast Ap p roximat ion t o t he Hyp ot enu se, Graphics Gems
(And rew S. Glassner, ed .). Acad emic Pr ess, Bost on, 427431. (III.6 Television Color
Encod ing and Hot Broad cast Color s)
Paet h, Alan W. (1990c). Circles of Int egr al Rad iu s on Int eger Lat t ices, Graphics Gems
(A. Glassner, ed .). Acad emic Pr ess, Bost on, 5760. (VIII.5 A Half-Angle Id ent it y
for Digit al Compu t at ion: The Joys of t he Halved Tangent )
Paet h, Alan W. (1990d ). Digit al Car t ogr aphy for Compu t er Gr aphics, Graphics Gems
(A. Glassner, ed .). Acad emic Press, Bost on, 307320. (VIII.5 A Half-Angle Id ent it y for
Digit al Compu t at ion: The Joys of t he Halved Tangent ; IX.8 Great Circle Plot t ing)
Pa et h , Al a n W. (1990e). Ma p p i n g RGB Tr i p l es on t o Fou r Bi t s , Graphi cs Gems
(A. Glassner, ed .). Acad emic Press, Bost on, 233245. (III.5 Mapping RGB Tr iples ont o
16 Dist inct Valu es; IV.3 Exact Dihed r al Met r ics for Common Polyhed r a)
Pa et h , Al a n W. (1990f). Pr op er Tr ea t men t of Pi xel s a s In t eger s, Graphics Gems
(A. Glassner, ed .). Acad emic Press, Bost on, 249256. (III.5 Mapping RGB Tr iples ont o
16 Dist inct Valu es)
Paet h, Alan W. (1990g). Tr igonomet r ic Fu nct ions al. Select Point s, Graphics Gems
(A. Glassner, ed .). Acad emic Press, Bost on, 1819. (IV.3 Exact Dihed r al Met r ics for
Common Polyhed r a; IX.8 Great Circle Plot t ing)
Paet h , A. W. (1987). The IM Rast er Toolkit Design, Implement at ion and Use. In st i -
t u t e for Compu t er Research Repor t UW/ ICR 8703. (II.9 Image File Compression Mad e
Easy)
Paet h, A. W. (1986). The IM Rast er Toolkit Design, Implement at ion and Use. Univer-
sit y of Wat er loo, Technical Repor t CS-86-65. (II.9 Image File Compression Mad e Easy)
Pa p ou l i s , At h a n a s i os (1965). Probabi l i t y, Random Vari abl es, and St ochast i c Pro-
cesses. McGr aw-Hill, 195. (II.ll Noise Thr eshold ing in Ed ge Images)
Peano, G. (1980). Select ed Works of Guiseppe Peano. Allen and Unwin, Winchest er, MA.
(I.7 A Peano Cu r ve Gener at ion Algor it hm)
Pearce, A. (1990). Shad ow At t enu at ion for Ray Tr acing Tr ansparent Object s, Graphics
Gems. Acad emic Press, Bost on, 397399. (V.9 Mor e Shad ow At t enu at ion for Ray
Tr acing Tr ansparent or Tr anslu cent Object s)
Pearce, A. (1987). An Implement at ion of Ray Tr acing Using Mu lt iprocessing and Spat ial
Su bd ivision, Mast er s Thesis, Univer sit y of Calgar y, Dept . of Compu t er Science. (V.7
Avoid ing Incor r ect Shad ow Int er sect ions for Ray Tr acing)
Per l i n , K. (1985). An Ima ge Syn t h esi z er, Comput er Graphics 19(3), p p . 287296.
(VIII.10 A Recu r sive Implement at ion of t he Per lin Noise Fu nct ion)
460 GRAPHIC GEMS II Edit ed by DAVID KIRK 460
REFERENCES
Phong, Bu i-Tu ong (1975). Illu minat ion for Compu t er-Gener at ed Pict u res, Comm. ACM
18(6), 311317. (IV.9 Int er Phong Shad ing)
Polya, George (1962). Mat hemat ical Discovery. John Wiley and Sons, 104105. (VIII.5
A Half-Angle Id ent it y for Digit al Compu t at ion: The Joys of t he Halved Tangent )
Post , Davi d L. , an d Cal h ou n , Ch r i st op h er S. (1989). An Eval u at i on of Met h od s for
Pr od u ci n g Des i r ed Col or s on CRT Mon i t or s , Col or Research and A ppl i cat i on 14,
172186. (III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
Pr at t , William K. (1978). Digit al Image Processing. John Wiley and Sons, New Yor k, NY.
(II.1 Image Smoot hing and Shar p ening by Discr et e Convolu t ion)
Pr ep a r a t a , F. P. , a n d Sh a mos , M. I. (1985). Comput at i onal Geomet ry. Sp r i n ger -Ver l a g
New Yor k. (III.1 Efcient Inver se Color Map Comp u t at ion)
Pr ess, Wi l l i am H. , Fl an n er y, Br i an P. , Teu kol sky, Sau l A. , an d Vet t er l i n g, Wi l l i am T.
(1988). Numeri cal Reci pes i n C. Ca mbr i d ge Un i v er s i t y Pr es s , Ca mbr i d ge, En gl a n d .
(VII.5 Fast Mat r ix Inver sion; VIII.2 Fast er Fou r ier Tr ansfor m)
Pu r d u e Un i v er s i t y (1970a ). Thermophy si cal Propert i es of Mat t er, Vol . 7: Thermal
Radiat ive Propert ies of Met als. Plenu m, New Yor k. (V.8 A Bod y Color Mod el: Absor p -
t ion of Light t hrou gh Tr anslu cent Med ia)
Pu r d u e Un i v er s i t y (1970b). Thermophy si cal Propert i es of Mat t er, Vol . 8: Thermal
Radi at i v e Propert i es of Nonmet al l i c Sol i ds. Pl en u m, New Yor k. (V. 8 A Bod y Col or
Mod el: Absor p t ion of Light t hrou gh Tr anslu cent Med ia)
Pu r d u e Un i v er s i t y (1970c). Thermophy si cal Propert i es of Mat t er, Vol . 9: Thermal
Radi at i v e Propert i es of Coat i ngs. Pl en u m, New Yor k. (V. 8 A Bod y Col or Mod el :
Absor p t ion of Light t hrou gh Tr anslu cent Med ia)
Ra d ema ch er, H. , a n d Toep l i t z , 0. (1957). The Enj oy ment of Mat hemat i cs. Pr i n cet on
Univer sit y Press, Pr incet on, NJ. (I.4 An Easy Bou nd ing Cir cle)
Ra msh a w, Lyl e (1978). On t h e Ga p St r u ct u r e of Sequ en ces of Poi n t s on a Ci r cl e,
Proceedi ngs of t he Koni nkl i j ke Nederl andse A kademi e v an Wet enschappen, A ms-
t erdam, Series A 81(4), 527-541. (VIII.9 Int er val Samp ling)
Ri t t er, Ja ck (1990). An Efci en t Bou n d i n g Sp h er e, Graphi cs Gems (An d r ew S.
Glassner, ed .). Acad emic Press, Bost on, 301303. (1.4 An Easy Bou nd ing Circle)
Roger s , D. F. (1985). Procedural El ement s f or Comput er Graphi cs, McGr a w-Hi l l , New
Yor k. (IV.9 Int er Phong Shad ing)
Rot h , Scot t D. (1982). Ra y Ca s t i n g for Mod el i n g Sol i d s , Comput er Graphi cs and
Image Processing 18(2), 109144. (V.1 Fast Ray-Convex Polyhed ron Int er sect ion)
Ru bin, St even M., and Whit t ed , Tu r ner (1980). A 3-Dimensional Rep r esent at ion for Fast
Ren d er i n g of Comp l ex Scen es , Comput er Graphi cs (SIGGRA PH 80 Proceedi ngs)
14(3), 110116. (V.5 Efciency Imp r ovement s for Hier archy Tr aver sal in Ray Tr acing)
Sa met , Ha n a n (1990b). A ppl i cat i ons of Spat i al Dat a St ruct ures, ISBN 0-201-50300-X.
Ad d i s on -Wes l ey, Rea d i n g, MA. (I. 9 Sca n l i n e Coh er en t Sh a p e Al gebr a ; IV. 7
Qu ad t ree/ Oct ree-t o-Bou nd ar y Conver sion)
461 GRAPHIC GEMS II Edit ed by DAVID KIRK 461
REFERENCES
Sa met , Ha n a n (1990a ). The Desi gn and A nal y si s of Spat i al Dat a St ruct ures. ISBN
0-201-50255-0. Ad d ison-Wesley, Read ing, MA. (I.9 Scanline Coherent Shap e Algebr a)
Samet , H., and Webber, R. E. (1988). Hier ar chical Dat a St r u ct u res and Algor it hms for
Comp u t er Gr a p h i cs Pa r t I: Fu n d a men t a l s , IEEE Comput er Graphi cs and A ppl i ca-
t ions, 4868. (IV.7 Qu ad t ree/ Oct ree-t o-Bou nd ar y Conver sion)
Samet , H. (1982). Nei gh bor Fi n d i n g i n Images Rep r esen t ed by Qu ad t rees, Comput er
Graphi cs and Image Processi ng 19, 3757. (IV. 7 Qu a d t r ee/ Oct r ee-t o-Bou n d a r y Con -
ver sion)
Sch u ma ch er, D. (1990). Usefu l l -t o-l Pi xel Tr a n sfor ms, Graphics Gems (A. Gl a ssn er,
ed .). Acad emic Press, Bost on. (II.3 Color Dit her ing)
Shoemake, Ken (1990). Bit Pat t er ns for Encod ing Angles, Graphics Gems (A. Glassner,
ed .). Acad emic Press, Bost on, 442. (VIII.5 A Half-Angle Id ent it y for Digit al Comp u t a-
t ion: The Joys of t he Halved Tangent )
Shoemake, Ken (1985). Animat ing Rot at ion wit h Qu at er nion Cu r ves, Comput er Graph-
ics 19(3), 245254. (VII.6 Qu at er n i on s an d 4 4 Mat r i ces; VIII.4 Usi n g Geomet r i c
Const ru ct ions t o Int er p olat e Or ient at ion wit h Qu at er nions)
Shoemake, Ken (1989). Qu at er nion Calcu lu s for Animat ion, SIGGRAPH Course Not es,
23, Mat h for SIGGRAPH. (VII.6 Qu at er nions and 4 4 Mat r ices)
Si egel , Rober t , a n d Howel l , Joh n R. (1981). Thermal Radi at i on Heat Transf er.
McGr aw-Hill, New Yor k. (VI.4 Rad iosit y via Ray Tr acing)
Sillion , Fr an cois, an d Pu ech , Clau d e (1989). A Gen er al Two-Pass Met h od In t egr at in g
Sp ecu l a r a n d Di ffu se Reect i on , Comput er Graphics A CM, SIGGRA PH 89 Proceed-
ings 23(3), 335344. (VI.4 Rad iosit y via Ray Tr acing)
SMPTE* (1990b). Pr op osed Amer ican Nat ional St and ar d Thr ee-Channel Par allel Com-
p onent Analog Vid eo Int er face, SMPTE Journal 253, 699702. (III.6 Television Color
Encod ing and Hot Broad cast Color s)
SMPTE (1988). SMPTE St an d ar d : Si gn al Par amet er s1125/ 60 Hi gh -Den i t i on Pr od u c-
t i on Sys t em, SMPTE. Al s o SMPTE (1990a ). SMPTE Journal 240M, 723725. (III. 6
Television Color Encod ing and Hot Broad cast Color s)
SMPTE (1987). SMPTE Recommen d ed Pr a ct i ce: Col or Mon i t or Col or i met r y, SMPTE
RP-145. (III.6 Television Color Encod ing and Hot Broad cast Color s)
SMPTE (1984). SMPTE Recommend ed Pr act ice: Bit -Par allel Digit al Int er face for Comp o-
n en t Vi d eo Si gn a l s , SMPTE RP-125. (III. 6 Tel ev i s i on Col or En cod i n g a n d Hot
Broad cast Color s)
SMPTE d ocu men t n ot e: Th e SMPTE i s t h e Soci et y for Mot i on Pi ct u r e an d Tel evi si on
En gi n eer s . It p u bl i s h es a s er i es of St andards, Recommended Pract i ces, and Gui de-
lines cover ing var iou s t op ics in t elevision and lm engineer ing. Ind ivid u al cop ies of
t hese d ocu ment s may be obt ained fr om SMPTE head qu ar t er s at 595 West Har t sd ale
Avenu e, Whit e Plains, NH 10607. These d ocu ment s also are p u blished in t he SMPTE
Journal, and cop ies of t his may be easier t o nd in a libr ar y. The d at a of ap p ear ances
in t he Journal is not ed if known. In ad d it ion, u nap p r oved st and ard s are p u blished in
t he Journal for comment .
462 GRAPHIC GEMS II Edit ed by DAVID KIRK 462
REFERENCES
SMPTE (1977). SMPTE Recommend ed Pr act ice: Set t ing Chromat icit y and Lu minance of
Wh i t e for Col or Tel ev i s i on Mon i t or s Us i n g Sh a d ow-Ma s k Pi ct u r e Tu bes , SMPTE
RP-71. (III.7 An Inexp ensive Met hod of Set t ing t he Monit or Whit e Point )
SMPTE (1969). SMPTE Recommend ed Pr act ice: Color Temp er at u re for Color Television
St u d i o Mon i t or s, SMPTE RP-37. (III. 6 Tel evi si on Col or En cod i n g a n d Hot Br oa d -
cast Color s)
Sp ar r ow, E. , an d Cess, R. (1970). Radiat ion Heat Transfer. Br ooks/ Col e, Bel mon t , CA,
6364. (V. 9 Mor e Sh a d ow At t en u a t i on for Ra y Tr a ci n g Tr a n sp a r en t or Tr a n sl u cen t
Object s)
St ei n er, Ja kob (1971). Jakob St ei ner s Gesammel t e Werke. Ch el s ea , Br on x, NY. (III. 5
Map p ing RGB Tr ip les ont o 16 Dist inct Valu es)
St einhar t , Jonat han E. et al. (1990). Int r od u ct ion To Wind ow Management , SIGGRAPH
90, Cou r se #11 Not es. (I.9 Scanline Coherent Shap e Algebr a)
St einhar t , Jonat han E. et al. (1989). Int r od u ct ion To Wind ow Management , SIGGRAPH
90, Cou r se #11 Not es. (I.9 Scanline Coherent Shap e Algebr a)
St evens, R. J., Lehar, A. F., and Pr est on, F. H. (1983). Manip u lat ion and Pr esent at ion of
Mu l t i d i men si on al Image Dat a Usi n g t h e Pean o Scan , IEEE Transact ions on Pat t ern
A nalysis and Machine Int elligence, PAMI-5(5), 520526. (I. 7 A Pean o Cu r ve Gen er a-
t ion Algor it hm)
St on e, Ma u r een C. , Cowa n , Wi l l i a m B. , a n d Bea t t y, Joh n C. (1988). Col or Ga mu t
Map p i n g an d t h e Pr i n t i n g of Di gi t al Col or Images, ACM Transact ions on Graphics
7(4), 249292. (III.8 Some Tip s for Making Color Har d cop y)
St one, M. G. (1986). A Mnemonic for t he Ar ea of Polygons, Amer. Mat h. Mont hly 93,
479480. (I.1 The Area of a Simp le Polygon)
St u cki, P. (1981). MECCAa mu lt ip le-er ror cor r ect ing comp u t at ion algor it hm for bilevel
i ma ge h a r d cop y r ep r od u ct i on , Research Report RZ 1060, IBM Res ea r ch La bor a t or y,
Zu r ich, Swit zer land . (II.2 A Comp ar ison of Digit al Halft oning Techniqu es)
Su t h er l an d , I. E., an d Hod gman , G. W. (1974). Reen t r an t Pol ygon Cl i p p i n g, CACM
17(1), 3242. (IV.8 Three-Dimensional Homogeneou s Clip p ing of Tr iangle St r ip s)
Th omp son , Kevi n (1990). Ar ea of In t er sect i on : Two Ci r cl es, Graphics Gems (An d r ew
S. Glassner, ed .). Acad emic Press, Bost on, 4346. (I.5 The Smallest Cir cle Cont aining
t he Int er sect ion of Two Circles)
Th omp s on , Kel v i n (1990). Fa s t Ma t r i x Mu l t i p l i ca t i on , Graphi cs Gems (An d r ew S.
Glassner, ed .). Acad emic Press, Bost on, 460461. (VII.5 Fast Mat r ix Inver sion)
Tu r kows ki , Ken (1990). Fi xed -Poi n t Tr i gon omet r y wi t h Cor d i c It er a t i on s , Graphi cs
Gems (A. Gl a s s n er, ed . ). Aca d emi c Pr es s , Bos t on , 494497. (VIII. 5 A Ha l f-An gl e
Id ent it y for Digit al Comp u t at ion: The Joys of t he Halved Tangent )
Tu r kowski, Ken (1990). Prop er t ies of Su r face-Nor mal Tr ansfor mat ions, Graphics Gems
(An d r ew S. Gl a s s n er, ed . ). Aca d emi c Pr es s , Bos t on , 539547. (VII . 5 Fa s t Ma t r i x
Inver sion)
Ulichney, R. (1988). Digit al Halft oning. MIT Pr ess, Cambr id ge, MA. (II.3 Color Dit her-
ing)
463 GRAPHIC GEMS II Edit ed by DAVID KIRK 463
REFERENCES
Wallace, John R., Elmqu ist , Kells A., and Haines, Er ic A. (1989). A Ray Tr acing
Algor it hm For Progressive Rad iosit y, Comput er Graphics (SIGGRAPH 89 Proceed-ings)
23(3), 335344. (VI. 1 Imp l emen t i n g Pr ogr es s i v e Ra d i os i t y wi t h Us er -Pr ov i d ed
Polygon Display Rou t ines; VI.4 Rad iosit y via Ray Tr acing; VI.5 Det ect ion of Shad ow
Bou nd ar ies for Ad apt ive Meshing in Rad iosit y)
Wan, S., Wong, S., and Pr u sinkiewicz, P. (1968). An Algor it hm for Mu lt id imensional Dat a
Cl u st er i n g, A CM Trans. on Mat h. Soft ware 14(2), 153162. (III.2 Efci en t St at i st i c
Comp u t at ions for Opt imal Color Qu ant izat ion)
Wat son, And rew B., Nielson, Kennet h R. K., Poir son, Allen, Fizt hu gh, And r ew, Bilson,
Amjyo, Ngu yen, Khan, and Ahmu d a, Alber t J. Jr. (1986). Use of a Rast er Fr ame Bu ffer
i n Vi s i on Res ea r ch , Journal of Behav i or Research Met hods, Inst rument s, and
Comput ers 18(6), 587-594. (III.8 Some Tips for Making Color Hard copy)
Weghor st , Hank, Hooper, Gar y, and Greenberg, Donald P. (1984). Improved Compu t a-
t ional Met hod s for Ray Tr acing, ACM Transact ions on Graphics 3(1), 5269. (V.5
Efciency Improvement s for Hier archy Tr aver sal in Ray Tr acing)
Welch, Ter r y A. (1984). A Techniqu e for High-Per for mance Dat a Compression, IEEE
Comput er 6(17), 820. (II.9 Image File Compression Mad e Easy)
Whit t ed , Tu r ner (1980). An Improved Illu minat ion Mod el for Shad ed Display, Comm.
ACM, 23(6), p. 343349. (V. Int rod u ct ion: Ray Tr acing)
Whit t en, I. H., and Neal, R. M. (1982). Using Peano Cu r ves for Bilevel Display of
Cont inu ou s-Tone Images, IEEE Comput er Graphics and Applicat ions, 82(3), 4752.
(I.7 A Peano Cu r ve Gener at ion Algor it hm)
Wiebelt , J. A. (1966). Engineering Radiat ion Heat Transfer. Holt , Rin eh ar t an d Win -
st on, New Yor k, 1922. (V.9 More Shad ow At t enu at ion for Ray Tr acing Tr ansparent or
Tr anslu cent Object s)
Winkler, Dean M. (1990). Vid eo Technology for Compu t er Gr aphics, Cou r se Not es #22
at SIGGRAPH 90. (III.6 Television Color Encod ing and Hot Broad cast Color s)
Wu , X., and Wit t en, I. (1985). A Fast k-Means Type Clu st er ing Algor it hm, Research
Report No. 85/197/10, Dep t . of Comp u t er Science, Univ. of Calgar y. (III.2 Efcient
St at ist ic Compu t at ions for Opt imal Color Qu ant izat ion)
Zavad a, Roland J. (1988). Challenges t o t he Development of a St and ard ized Professional
St u d i o Col or -Pi ct u r e Mon i t or, SMPTE Journal, 703710. (III. 6 Tel evi si on Col or
Encod ing and Hot Broad cast Color s)
464 464
INDEX
I II IIN NN NND DD DDEX EX EX EX EX
A
Absor p t ion coefcient , 279280
Absor p t ion ind ex, 280
Adaptive meshing, radiosity, shadow boundary
d et ect ion, 311315
Adaptive predictioncorrection coders, 9495
Ad jacent facet s, nor mals, 239
Afne mat r ix
grou p , 345
inver se, 348349
Aggregat e object s, 264
Aliasing, nar row d omains, 123124
Angle-p reser ving mat r ix grou p , 345
Ant i-aliased cir cle gener at ion, 445449
Ap p le p at ent , 3132
Ap p oloniu ss 10t h p roblem, 1924
Archimed ean solid s, semi-regu lar, 177
Archival med ia, 165
Arct angent , ap p roximat ion, 389391
Area
comp u t ing, binar y d igit al image, 107111
p olygon, 56
Area-t o-d ifferent ial-area for m fact or, 313
Asymmet r ic lt er, 5253
Au t u mn t er minat or, 440441
B
Ber nst ein basis, 406, 409
Ber nst ein p olynomials, 407, 409410, 428
Bet acam, 154
Bzier cont r ol p oint s, d er ivat ion, 377
Bzier cu r ves and su r faces, 412416
cu bic, 428429
geomet r ically cont inu ou s, 428434
d er ivat ive for mu las, 429
least -squ ar es ap p roximat ions, 406
mu lt ivar iat e ap p roximat ion, 409411
p ar amet r ic ver su s geomet r ic cont inu it y,
430431
u nivar iat e ap p r oximat ion, 406408
Bzier simp lices, 412
Binar y d igit al image, 107
computing area, circumference, and genus,
107111
algor it hm, 109111
met hod , 107109
Binar y r ecu r sive su bd ivision, r ay-t r iangle
int er sect ion, 257263
Bit map rot at or, 90-d egree, 8485
Bit p icking, 366367
Bits, under mask, counting through, 372373
Bit -t allying, 373376
Blu egreen p lane, d omain, 120122
Blu e scanlines, ad ju st ing minimu m and
maximu m, 122123
Bod y color mod el, 277282
t heor et ical basis, 277278
Bot t om-Up, 206, 208-209
Bou nd ing box, r ad iosit y, 304305
Bou nd ing met hod , t or u s, 254255
Bou nd ing volu mes, sor t ing, 272
Box lt er, 5152
Br esenhams circles, 448449
465 465
INDEX
B-sp lines, 377378
cu bic, knot inser t ion, 425427
Bu mp map p ing, 106
Bu t zs algor it hm, 25
C
Cache p er for mance, increasing, 87
Caching, 268
Chain ru le, 184
Chr ominance, 150
Cibachr ome, 164165
Cibat r ans, 164165
Cir cle
ant i-aliased gener at ion, 445449
bou nd ing, 1416
containing intersection of two circles, 1718
wit h r ad ials, 383
t ou ching t hree given cir cles, 1924
Cir cu lar arc, st r aight -line ap p r oximat ion,
435439
Circumference, computing, binary digital image,
107111
C
1
joint , bet ween cu bic Bzier cu r ves, 432
Clip p ing
comp lex, 44
3D homogeneou s, t r iangle st r ip s, 219231
Clu st ered -d ot d it her, 63
Coherence, 26
measu r e, 28, 30
Color d escr ip t or t able, 144
Color d it her ing, 7277
convent ions, 72
er ror -p rop agat ion d it her ing, 7577
gamma cor rect ion, 7273
or d ered d it her ing, 7375
Color hard cop y, fr ame bu ffer, 163165
Color map p ing
animat ion, r and om algor it hm, 134137
p seu d o, PHIGS PLUS, 138140
Color p r int er s, 165
Color qu ant izat ion
algor it hm d et ails and analysis, 131132
based on var iance minimizat ion, 127
color st at ist ic comp u t at ions, 128131
er ror, 126128
exp er iment al resu lt s, 133
op t imal, st at ist ical comp u t at ions, 126133
Color r eference fr ame, 148
Color st at ist ics, comp u t at ions, 128131
Color t elevision monit or, calibr at ion, 159162
Combinat or ics, inclu sion-exclu sion, 129130
Comp act ion algor it hm, 89
Comp lex clip p ing, 44
Comp r ession, 49
image le, 93100
Comp r ession r at ios, 97, 100
Comp r ession t echniqu es, 89
Cond u ct ing med iu m, light r eect ion, 286
Convolu t ion ker nel, 5051
C-Pr int , 164165
Cr ack p revent ion, sp ace p acking lat t ices, 174
Cr oss p rod u ct , 333334
sign calcu lat ion, 392393
Cu be, d ihed r al, 174175
Cu bic cu r ve, 413
Cu bic t et r ahed r on, ad ap t at ion of hemi-cu be
algor it hm, 299302
Cu bic t r iangle, 413
Cu r r ent object area, 28
Cu r ves and su r faces, 405
ant i-aliased circle gener at ion, 445449
Bzier, see Bzier cu r ves and su r faces
great circle p lot t ing, 440444
int er p olat ion wit h var iable cont rol p oint
ap p roximat ion, 417419
Menelau ss t heor em, 424427
nu mber of segment s, 435436
Peano, 2526
p olynomials, symmet r ic evalu at ion, 420423
st r aight -line app roximat ion of circu lar ar c,
435439
D
Dat a st r u ct u res, scanline coherent shap e
algebr a, 3234
Delt a for m fact or, 313
Dielect r ic mat er ials, fresnel for mu las, 287289
Difference, scanline coherent shap e algebr a,
3940
Diffu se r eect ion, 233
Digit al comput at ion, half-angle ident it y,
381386
Digit al lt er ing, see Discr et e convolu t ion
Digit al halft oning, 5771
clu st ered -d ot d it her, 63
cont r ast ad ju st ment d u r ing, 6364
er r or d iffu sion d it her ing, 6571
hor izont al lines, 6061
magic-squ ar e d it her, 6062
466 466
INDEX
t o mu lt ip le ou t p u t levels, 6465
ord er ed d it her mat r ix, 5860
t hr eshold d it her ing, 5863
Digit al images, color har d cop y, 163165
Discr et e convolu t ion, image smoot hing and
shar p ening, 5056
Discr et e lap lacian lt er, 5354
Dod ecahed ron, 176
d ihed r als, 175, 177
t r ansfor mat ion of sp here, 241
Du ffs for mu lat ion, 418
Du r at r ans, 164165
E
Ed ge d et ect or s, 105
Ed ge images, noise t hreshold ing, 105106
Ed ge-shar p ening convolu t ions, 55
ap p lied before halft oning, 7071
Ed ge st r u ct u re, 8687
Eigenvalu es, 324325
Ellip t ical t oru s
cross sect ion, 251252
equ at ion, 251252
int er sect ion wit h r ay, 251256
Encod ed image d at a, rot at ion, 8688
Encod ing, ad ap t ive r u nlengt h, 8991
Er ror d iffu sion d it her ing, 6571
blu e noise ad d ed , 70
ed ge-enhanced , 7071
int rod u ct ion of r and om noise, 69
ser p ent ine r ast er p at t er n, 67, 69
Er ror p rop agat ion d it her ing, 7577
Eu ler nu mber, comp u t ing, binar y d igit al
image, 107111
Eu ler op er at or s, winged ed ge mod els, 197
Exp onent ial mat r ix, 332333
Exp onent ials, t r ansfor mat ions as, 332337
Ext inct ion coefficient , 279
F
Face d ihed r als, 174175
Facet ed shad ing, 234, 236
Fast anamor p hic image scaling, 7879
Fast Fou r ier t r ansfor m algor it hms, 368370
Fat cu r ve, gener at ion, 43
Filt er, nonu nifor m qu ad r at ic sp line, 101102
Fir st d er ivat ive lt er s, 105
Flip p ed bit cou nt , 368
Float ing p oint p ixel for mat , 8182
Floyd -St einber g er ror p rop agat ion, 7576
Floyd -St einber g lt er, 68
4 4 mat r ices, 351354
Fou r ier t r ansfor m, 368370
Fr ame bu ffer, 115
color har d cop y, 163165
color qu ant izat ion st at ist ical computat ions,
126133
inver se color map , comp u t at ion, 116125
map p ing RGB t r ip les, 143146
PHIGS PLUS, 138142
r and om color map animat ion algor it hm,
134137
set t ing monit or whit e p oint , 159162
t elevision color encod ing, 147158
Fr esnel for mu las
ap p r oximat ions for ap p lying, 287289
d ielect r ic mat er ials, 287289
wavelengt h-d ep end ent r eect ion and
refr act ion, 286287
Fr esnel reect ance cu r ve, 284, 289
Fr esnel t r ansmission cu r ve, 284, 288289
Fr exp , 82
G
Gamma cor rect ion, color d it her ing, 7273
Gau ssian r and om nu mber s, 136
Gau ssian weight ed lt er, 5153
Gau ss-Jord an eliminat ion, 349
Genus, comp ut ing, binar y digit al i mage,
107111
Geod esics, 440
Geomet r ic const r u ct ions, int er p olat ion of
or ient at ion wit h qu at er nions, 377380
Geomet r ic cont inu it y, 430431
G
2
joint , bet ween cu bic Bzier cu r ves, 432
Gou r au d shad ing, 235236
Gr ay r amp , 163164
Gr eat circle p lot t ing, 440444
Gr ou p t heor y, 343344
H
Half-angle id ent it y, d igit al comp u t at ion,
381386
Half-t angent , 381386
Halft oning, see Digit al halft oning
Halft oning mat r ix, 58
467 467
INDEX
HDTV, 154155
Heckber t s algor it hm, 127
Hemi-cu be algor it hm, 299
cu bic t et r ahed r al ad ap t at ion, 299302
Her mit e p olynomial, 398399
Hier archy t r aver sal, 267272
bot t om-u p met hod , 270271
caching, 268
combining t op -d own and bot t om-u p
ap p roaches, 270271
t op -d own list for mat ion, 268269
High coherence, 28, 30
Hilber t cu r ve, 2728
Homgeneou s med ia, light absor p t ion 278280
Hor ner s ru le, 420421
Hot color s, 147, 152153
Hot p ixels
r ep air ing, 155156
t est , 155157
Hybr id p red ict or, 97100
Hyp ercones, 117
I
Icosahed ron, d ihed r als, 175, 177
Image le comp r ession, 93100
hybr id p red ict or, 97100
p r ed ict ion-cor rect ion cod ing, 9394
ad ap t ive, 9495
Image p r ocessing, 49, see also Digit al halftoning
ad ap t ive r u n-lengt h encod ing, 8991
color d it her ing, 7277
fast anamor p hic image scaling, 7879
image le comp ression, 93100
image smoothing and sharpening by discrete
convolu t ion, 5056
90-d egree bit map rot at or, 8485
noise t hreshold ing in ed ge images, 105106
op t imal lt er for reconst ru ct ion, 101104
p ixels, 8083
run-length encoded image data rotation, 8688
Image reconst ru ct ion, op t imal lt er, 101104
Image scaling, fast anamor p hic, 7879
Image shar p ening, by d iscret e convolu t ion,
5056
Image smoothing, by discrete convolution ,5056
Inclu sion-exclu sion, combinat or ics, 129130
Inhomogeneou s med ia, light absor p t ion,
280281
Input Face, 196
Input Vert ex, 196
Insert Bridge, 199201
Int eger s, 371372
cou nt ing t hrou gh bit s u nd er mask, 372373
t allying on bit s, 373376
Int eger squ are r oot algor it hm, 387388
Int ensit y, 233, 278279
int er p olat ion bet ween ad jacent p ixels, 445
Int er Phong shad ing, 232241
analysis of for mu la, 238240
ap p licat ions, 241
Int er sect ion
line, see Line, int er sect ions
scanline coher ent shap e algebr a, 37
of t wo circles, cir cle cont aining, 1718
Int er val samp ling, 394395
Inver se color map , 116
ad ju st ing blu e scanlines, 122123
aliasing, 123124
comp u t at ion, 116125
convexad vant age, 119124
d omain in blu e-gr een p lane, 120122
incr ement al d ist ance calcu lat ion, 117119
or d er ing, 124125
IRE u nit es, 152
J
Jacobian mat r ix, 184
Jar vis, Ju d ice, and Nanke lt er, 68
K
Knot , inser t ion int o B-sp lines, 425427
Kochanek-Bar t els for mu lat ion, 417419
L
Lamber t ian r ad iosit y mod el, 385
Lamber t s law of absor p t ion, 279
Ld exp , 8283
468 468
INDEX
Least-squares approximations, Bzier curves and
su r faces, 406411
Lengt h-p reser ving mat r ix grou p , 344345
Light
absor p t ion
homogeneou s med ia, 278280
inhomogeneou s med ia, 280281
t r anslu cent med ia, 277282
r eect ion, 282
Light sensing d evice, 161162
Line
d ist ance t o p oint , 1013
intersections, see also Scanline coherent shape
algebr a Ap p oloniu ss lOt h p roblem,
1924
bou nd ing circle, 1416
cir cle cont aining int er sect ion of t wo
circles, 1718
d ist ance fr om p oint t o line, 1013
int er sect ion of line segment s, 79
Peano cu r ve gener at ion algor it hm,
2526
segment s, 79
sp ace-lling cu r ve, 2728
t r ansver sal, 2627
Linear t r ansfor mat ions, 335337
Look-u p t able color, 139
LU d ecomp osit ion, 349
Lu minaires, p ower from, 307
Lu mninancecolor d ifference sp ace, 147
Lu minance met er, 159160
M
M2, 154
Mach band effect , 235236
Magic squ are
d it her, 6062
as ou t er p rod u ct , 74
Mailbox, 264
algor it hm, 268
Manhat t an d ist ance, 258259
Map p ing, RGB t r ip les, 143146
Mat r ix
d ecomp osit ion int o simp le t r ansfor mat ions,
320323
exp onent ial, 332333
Mat r ix grou p s, 344
afne, 345
angle-p reser ving, 345
inver se, 348349
lengt h-p r eser ving, 344345
member ship and p r ivileges, 346347
nonsingu lar, 345
inver se, 350
wind ow-t o-viewp or t , 344
inver se, 348
Mat r ix inver sion, 342350
element ar y, 347
evalu at ion st r at egy, 347348
p r oblem st at ement , 342
Mat r ix t echniqu es, 319
cr oss p rod u ct , 333334
d at a r ecover y from t r ansfor mat ion mat r ix,
324331
4 4 mat r ices, 351354
linear t r ansfor mat ions, 335337
not at ion, 338
p seu d o-p er sp ect ive, 340341
qu at er nions, 351354
r and om r ot at ion mat r ices, 355356
shear, 339340
small sp ar se mat r ix classicat ion, 357361
t ensor p r od u ct , 333334
t r ansfor mat ions as exp onent ials, 332337
Mat r ix-vect or, 360361
Menelau ss t heorem, 424427
Mir r or image, d at a recover y from
t r ansfor mat ion
mat r ix, 327
Mod ied facet shad ing, 236237
Monit or, whit e p oint , set t ing, 159162
Monochr omat ic t r ip les, 146
Mu lt i-ind ices, 412
Mu lt ip le ou t p u t levels, halft oning t o, 6465
Mult ivar iat e appr oximat ion, Bzier cur ves and
su r faces, 409
N
Nar r ow d omains, aliasing, 123124
Nat ional Television Syst ems Commit t ee,
encod ing basics, 148152
Next FaceAroundVert ex, 195196
Noise t hr eshold ing, ed ge images, 105106
Nonlocalit y t ension, 238
Nonsingu lar mat r ix gr ou p , 345
inver se, 350
NTSC encod ing basics, 148152
469 469
INDEX
Nu mer ical and p rogr amming t echniqu es, 365
arct angent , ap p r oximat ion, 389-391
bit p icking, 366367
Fou r ier t r ansfor m, 368370
half-angle id ent it y, 381386
int eger squ ar e root algor it hm, 387388
int er val samp ling, 394395
Per lin noise fu nct ion, recu r sive
imp lement at ion, 396401
sign of cross p rod u ct calcu lat ion, 392393
using geomet r ic const ruct ions t o int er polat e
or ient at ion wit h qu at er nions, 377380
O
Object area, 2627
Object -sp ace rend er ing, 26
Oct ahed r on, d ihed r als, 174175
Oct ree-t o-Boundary conver sion, 214218
Oct ree-t o-PCS, 214215
Offset p r int s, 165
Op cod e, 36
Or d ered d it her ing
color, 7375
mat r ix, 5860
P
PAL encod ing, 153154
Par allel connect ed st r ip es rep resent at ion,
203204
Par amet r ic cont inu it y, 430431
Pat ch visibilit y ind ex, 313
Pat t er n mask, 57
PCS-t o-bou nd ar y conver sion, 205
PCS-t o-Chain p roced u re, 205206
Peano cu r ve, 2728
coherence of t r ansver sal sequ ences, 2830
gener at ion algor it hm, 2526
Perlin noise function, recursive implementation,
396401
PHIGS PLUS, 138142, 420
imp lement at ion, 141142
p seu d o color
int er p olat ion, 140141
map p ing, 138140
Phosp hor s
chr omat icit y, 151
coor d inat es, 161
sp ect r al emission cu r ve, 160161
Pixels, 8083
band , ant i-aliasing, 445446
comp onent s, 109110
gamma-cor r ect ed byt e st or age, 80
locat ions, 3334
r emap p ing, 78
r ep licat ion, 79
su b-samp ling, 79
u np or t able bit s, 81
Planar p olygon, area, 170
Point
d ist ance t o line, 10-13
gener at ion equ at ion, 179
Point -t r iangle int er sect ion, 259261
Polygon
ar ea, 56
u ser -p rovid ed d isp lay rou t ines, r ad iosit y,
295298
Polyhed r on
convex, r ay int er sect ion, 247250
exact d ihed r al met r ics, 174178
r egu lar, 174175
volu me, 170171
Polyline, cir cu lar arc, 435437
Polynomials
Hor ner s r u le, 420421
symmet r ic evalu at ion, 420423
Pred ict ion-cor r ect ion cod ing, 9394
Progr amming t echniqu es, see Nu mer ical and
p rogr amming t echniqu es
Project ion
d at a r ecover y from t r ansfor mat ion mat r ix,
329331
equ at ions, view cor r elat ion, 182183
Pseu d o color
int er p olat ion, PHIGS PLUS, 140141
map p ing, PHIGS PLUS, 138140
Pseu d o-p er sp ect ive, 340341
Pyr amid geomet r y, rend er ing wit h it er at ed
p ar amet er s, 186187
Q
Qu ad r at ic sp line, nonu nifor m, 101102
Qu ad t ree/ oct r ee-t o-bou nd ar y conver sion,
202218
Bot t om-Up, 206, 208209
Oct ree-t o-Boundary conver sion, 214218
Oct ree-t o-PCS, 214215
p ar allel connect ed st r ip es r ep resent at ion,
203204
470 470
INDEX
Qu ad t ree/ oct ree-t o-bou nd .-conv. (Cont d )
PCS-t o-bou nd ar y conver sion, 205
PCS-t o-Chain p roced u re, 205206
qu ad t ree-t o-bou nd ar y conver sion, 211213
Quusdt ree-o-PCS, 211213
Top-Down, 206-208, 210
Qu ad t rees, 31
Quadt ree-t o-PCS, 211213
Qu at er nions, 351354
geomet r ic const r u ct ion int er p olat ion of
or ient at ion, 377380
R
Rad iosit y, 293294
ad apt ive meshing, shadow bou ndar y
det ect ion,
311315
ad vant age, 295
ext ensions, 308309
fast ver t ex u p d at e, 303305
for m fact or s, 295
hemi-cu be algor it hm, cu bic t et r ahed r al
ad ap t at ion, 299302
p r ogressive, 296297
imp lement at ion, 297298
p r ogressive renement , 306307
r ay-t r aced for m fact or s, 312313
by r ay t r acing, 306310
send ing p ower wit h r ays, 307308
u ser-p rovid ed p olygon d isp lay r ou t ines,
295298
Rand om color map animat ion algor it hm,
134137
Random noise funct ion, see Per lin noise
fu nct ion
Rand om-nu mber gener at or, 136
Rand om rot at ion mat r ices, 355356
Rast er image, 90-d egr ee rot at ion, 86
Rast er rep resent at ion, 111
Ray
d enit ion, 248
int er sect ion wit h ellip t ical t oru s, 251256
Ray-convex p olyhed ron int er sect ion, 247250
Ray equ at ion, 180
Rayleigh p robabilit y d ensit y fu nct ion, 106
Rayobject int er sect ion t ags, 264266
Rayp lane int er sect ion, 258259
Rayp olyhed ron t est , 247250
Rayshad e, 186, 188190
Ray t agging, voxel-based r ay t r acing, 264266
Ray t r acing, 245-246
avoid ing incor rect shad ow int er sect ions,
275-276
bod y color mod el, 277-282
hier archy t r aver sal, 267-272
r ad iosit y by, 306-310
r ay-convex p olyhed r on int er sect ion, 247-250
recu r sive shad ow voxel cache, 273-274
shad ow at t enu at ion, 283289
voxel-based , 264266
Ray-t r iangle int er sect ion, binar y r ecu r sive
su bd ivision, 257263
const r aint s, 257
p oint -t r iangle int er sect ion, 259261
r ay-p lane int er sect ion, 258259
U, V comp u t at ion, 261262
Recu r sive shad ow voxel cache, 273274
Reect ion, wavelengt h-d ep end ent , 286287
Refr act ion, wavelengt h-d ep end ent , 286287
Remove Edge, 198
Rep resent at ive color, 116
RGB-t o-YIO encod ing, 151
RGB t r ip les, map p ing, 143146
RGB valu es
gamma-cor r ect ed , 157
u nencod able, 147
RMS er ror, 104
Rober t ss met hod , 96
Rot at ion
d at a recovery fr om t r ansfor mat ion mat r ix,
326
r u n-lengt h encod ed image d at a, 8688
Rot at ion mat r ix
homogeneou s, 352
r and om, 355356
Ru n-lengt h encod ing, ad ap t ive, 8991
S
Scaling, d at a r ecover y from t r ansfor mat ion
mat r ix, 327328
Scanline coherent shap e algebr a, 3145
algor it hm, 3437
ap p licat ions, 4144
backgr ou nd , 3132
d at a st r u ct u res, 3234
d ifference, 3940
imp rovement s, 4445
int er sect ion, 37
u nion, 3839
u t ilit y fu nct ions, 4041
Segment d at a st r u ct u res, 3334
471 471
INDEX
Ser p ent ine r ast er p at t er n, 67, 69
Set Wings, 194195
Shad ing r ays, caching, 268
Shading techniques, incremental and empirical,
233236
Shad ing t ension, 238
Shad ow algor it hm, 284285
Shad ow at t enu at ion, 283289
naive scheme, 283284
wavelengt h-d ep end ent reect ion and
r efr act ion, 286287
Shad ow bou nd ar ies
d et ect ion, ad ap t ive meshing in r ad iosit y,
311315
su bd ivision cr it er ia, 313315
visibilit y ind ex, 313
Shad ow cache, 273
Shad ow gener at ion, ap p r oximat ions, 283
Shad ow int er sect ions
avoid ing incor rect , 275276
Shad ow object caching, 268
Shad ow voxel cache, 273274
Shap e
algebr a op cod es, 36
d ecomp osit ion, 32
p ar amet er s, 431, 433
Shape-box rou t ine, 4041
Shape representations, stored as linked lists, 32
Shar p ening lt er, 5355
Shear, 339340
d at a recover y fr om t r ansfor mat ion mat r ix,
328329
geomet r y, 339
Small sp ar se mat r ix, classicat ion, 357361
Smoot hing, 5354
Snu b d isp henoid , 178
Snu b gu res, 177178
Sobel and Pr ewit t op er at or s, 105
Solid s, qu asi-regu lar, 174175
Sp ace-lling cu r ves, 34, 2728
Sp ace p acking lat t ices, cr ack p r event ion, 174
Sp an
d at a st ru ct u r e, 33
p r ocessing, 34235
Sp ar se mat r ix
classicat ion, 357361
zero st ru ct u r es, 357358
mu lt ip lying a vect or, 360361
Sp ecu lar reect ion, 234
Sp here, moving on, 172173
Split Edge, 197198
Squ are r oot algor it hm, 387388
St at e, cod e gener at ion, 35
St u cki lt er, 69
Su r face nor mal, t or u s, d et er minat ion, 256
Su r faces, see Cu r ves and su r faces
Su r face shad ing, 234
Su t her land -Hod gman algor it hm, 220, 231
Symmet r ic evalu at ion, p olynomials, 420423
Synt het ic act or, 241
T
Television color encod ing, 147158
chr ominance, 150
color r eference fr ame, 148
comp onent syst ems, 154
HDTV, 154155
hot -p ixel t est , 155157
IRE u nit es, 152
lu minance-color d ifference sp ace, 147
NTSC encod ing basics, 148152
PAL encod ing, 153154
u nencod able RGB valu es, 147
Tensor p rod u ct , 333334
Tent lt er, 5152
Tet r ahed ron, d ihed r als, 174175
3 3 mat r ix, zer o st ru ct u res for, 358359
Thr ee-d imensional geomet r y, 169
homogeneou s clip p ing, t r iangle st r ip s,
219231
Int er Phong shad ing, 232241
moving on a sp her e, 172173
p lanar p olygon, ar ea, 170
p olyhed r a
exact d ihed r al met r ics, 174178
volu me, 170171
qu ad t r ee/ oct ree-t o-bou nd ar y conver sion,
202218
view cor relat ion, 181190
viewing geomet r y, 179180
winged -ed ge mod el maint enance, 191201
Thr ee-d imensional homogeneou s clip p ing,
t r iangle st r ip s, 219231
against non-nor malized clip p ing volu me,
224225
algor it hm st u d y, 220223
d at a st u d y, 219220
imp lement at ion, 225229
memor y consid er at ions, 223224
Thr eshold d it her ing, 5863
Thr eshold ing mat r ix, 57
Top-Down, 206208, 210
472 472
INDEX
Tor u s
d et er mining su r face nor mal, 256
efcient bou nd ing, 254255
Tr ansfor mat ion mat r ix, d at a recover y, 324331
mir ror image, 327
p r oject ion, 329331
r ot at ion, 326
scaling, 327328
shear, 328329
t r anslat ion, 326
Tr ansfor mat ions, as exp onent ials, 332337
Tr anslat ion, d at a r ecover y from
t r ansfor mat ion
mat r ix, 326
Tr anslu cent med ia, light absor p t ion, 277282
Tr anslu cent object s, r ay t r acing, shad ow
at t enu at ion, 283289
Tr ansmission coefcient , 278
Tr ansp arent object s, r ay t r acing, shad ow
at t enu at ion, 283289
Tr aver sal, 2627
coherence, 30
Tr iangle, int er sect ion wit h r ay, 257263
Tr iangle lt er, 5152
Tr iangle st r ip s, t hr ee-d imensional
homogeneou s
clip p ing, 219231
Tr ist imu lu s valu es, 159160
Two-d imensional geomet r y, 34
ar ea, p olygon, 56
Two-d imensional p red ict ion, 95
Two-d imensional screen p oint , 181
Two-d imensional t emp lat e, minimu m, 95
U
Union, scanline coherent shape algebr a, 3839
Univar iat e ap p r oximat ion, Bzier cu r ves and
su r faces, 406407
Ut ilit y fu nct ions, scanline coherent shap e
algebr a, 4041
U, V valu es, 261262
V
Var iable cont rol p oint ap p roximat ion, cu r ve
int er p olat ion, 417419
Variance minimization, color quantization based
on, 127
Ver t ex d ep end ence, 238239
Vid eo signal amp lit u d es, 152
View cor r elat ion, 181190
chain r u le, 184
examp le, 188190
imp lement at ion d et ails, 185188
it er at ion p ar amet er s, 184185
mat hemat ical basis, 182185
p r oject ion equ at ions, 182183
p yr amid geomet r y, rend er ing wit h it er at ed
p ar amet er s, 186187
2D screen p oint , 181
Viewing geomet r y, 179180
Visibilit y ind ex, 313
Vor onoi d iagr am, 117
Voxel cache, 273274
W
Wavelengt h-d ep end ent r eect ion and
refr act ion,
286287
WEdgeDat a st r u ct u re, 192194
Whit ening lt er, 95
Whit e p oint
chr omat icit ies, 148149
monit or, set t ing, 159162
Wind ow d at a st r u ct u re, 42
Wind ow-t o-viewp or t mat r ix grou p , 344
inver se, 348
Wind ow t ree, 42
Winged -ed ge libr ar y, fu nd ament al op er at ions,
191
Winged -ed ge mod els, maint aining, 191201
Eu ler op er at or s, 197
input Face, 196
input Vert ex, 196
Insert Bridge, 199201
Next FaceAround Vert ex, 195196
RemoveEdge, 198
Set Wings, 194195
Split Edge, 19 7198
WEdgeDat a st ru ct u r e, 192194
WShape, 192
Wu s algor it hm, 127
Wu s ant i-aliased cir cles, 448449
algor it hm, 447
Z
Zer o st ru ct u r es, 357358
for 3 3 mat r ix, 358359
473 473
INDEX
GRAPHICS GEMS II
Cover
and int er ior
d esigned by Camille
Pecoul. Chapt er opening gr aphics
d r awn by And rew S. Glassner. Composed
by Science Typogr apher s Incor por at ed in Cent ur y
Schoolbook, Tegr a Humanist 521. Pr int ed
and bound by t he Maple Vail
Book Manufact ur ing
Group.

Vous aimerez peut-être aussi