Graphics Gems 3

  • Upload
    mirthyn

  • View
    180

  • Download
    25

Embed Size (px)

Citation preview

iGRAPHIC GEMS II Edit ed by DAVID KIRKi iGRAPHIC GEMS II Edit ed by DAVID KIRKThis is a volume inThe 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 esA Collect ion of Pract ical Techniquesf or t he Comput er Graphics ProgrammerSeries Edit orAndrew S. GlassnerXerox Palo Alt o Research Cent erPalo Alt o, Calif omiaiiiGRAPHIC GEMS II Edit ed by DAVID KIRKG GG GGRAPHICS RAPHICSRAPHICS RAPHICS RAPHICSG GG GGEMS EMSEMS EMS EMS III IIIIII III IIIedit ed byDAVID KIRKCal i f or ni a Inst i t ut e of Technol ogy Cal i f or ni a Inst i t ut e of Technol ogy Cal i f or ni a Inst i t ut e of Technol ogy Cal i f or ni a Inst i t ut e of Technol ogy Cal i f or ni a Inst i t ut e of Technol ogyComput er Gr aphi cs Labor at or y Comput er Gr aphi cs Labor at or y Comput er Gr aphi cs Labor at or y Comput er Gr aphi cs Labor at or y Comput er Gr aphi cs Labor at or yPasadena, Cal i f or ni a Pasadena, Cal i f or ni a Pasadena, Cal i f or ni a Pasadena, Cal i f or ni a Pasadena, Cal i f or ni aAP PROFESSIONALBost on San Diego NewYor k London Sydney Tokyo Tor ont oCopyright (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 TERMScopyright (c) 1993 by Academic Press, Inc.RADIOSITY AND REALISTIC IMAGE SYNTHESIScopyright (c) 1993 by Academic Press Inc.VIRTUAL REALITY APPLICATIONS AND EXPLORATIONScopyright (c) 1993 by Academic Press Inc.All rights reserved.No part of this product may be reproduced or transmitted in any form or by anymeans, electronic or mechanical, including input into or storage in any informationsystem, other than for uses specified in the License Agreement, without permissionin writing from the publisher.Except where credited to another source, the C and C++ Code may be used freely tomodify or create programs that are for personal use or commercial distribution.Produced in the United States of AmericaISBN 0-12-059756-XvGRAPHIC GEMS II Edit ed by DAVID KIRKAbout t he Cover About t he Cover About t he Cover About t he Cover About t he CoverCover image cop yr ight 1992 The VALIS Grou p , Rend er Man image cr eat ed by The VALIS Grou p ,reprinted from Graphics Gems III, edited by David Kirk, copyright 1992 Academic Press, Inc. Allr ight s reser ved . This cover image evolved ou t of a t eam effor t bet ween The VALIS Gr ou p , And r ew Glassner,Acad emic Press, and t he generous cooper at ion and sponsor ship of t he folks at Pixar. Special t hanksgo t o Tony Ap od aca at Pixar for p ost -p rocessing t he gems in t his p ict u re u sing ad vanced Rend er-Man t echniqu es. The ent ire cover image was creat ed u sing Rend er Man fr om Pixar. We saw t he Graphics Gems III cover as bot h an aest het ic challenge and an op p or t u nit y t od emonst r at e t he kind of images t hat can be rend er ed wit h VALIS prod uct s and Pixar s Rend er Man. Given the time constraints, all of the geometry had to be kept as simple as possible so as not torequire any complex and lengthy modeling efforts. Since RenderMan works best when the geometricentities used in a 3-D scene are described by high order surfaces, most of the objects consisted ofsurfaces made up of quadric primitives and bicubic patches. Andrews gem data and the Archimedeansolid s from t he VALIS Pr ime RIBTM libr ar y are-t he only p olygonal object s in t he p ict u re. Once all of t he object s were d ened , we u sed Pixar s Showp laceTM, a 3-D scene ar r angingapplication on the Mac, to position the objects and compose the scene. Showplace also allowed us top osit ion t he camer a and t he st and ard light sou r ces as well as at t ach shad er s t o t he object sIn Rend er Man, shad er s lit er ally end ow ever yt hing in t he image wit h t heir own char act er ist icap p ear ances, from t he light s and t he object s t o t he at mosp here. The shad er s t hemselves arep roced u r al d escr ip t ions of a mat er ial or ot her p henomenon wr it t en in t he Rend er Man Shad ingLangu age. We d id not u se any scanned t ext u res or 2-D p aint ret ou ching soft ware t o p r od u cet his p ict u re.Where appropr iat e, we used exist ing shad er s on t he sur faces of object s in t his pict ure, t aken fromour commercially available VG Shad er sTM + VG LooksTM libr ar ies. For example,we used Hewn St oneMasonr y (Volu me 3) t o creat e t he t emp le wall and well; St one Aggregat e (Volu me 3) for t hejungle-oor, and polished met al (Volume 2) for t he gold d ish. In ad d it ion t o t hese and ot her exist ingshaders, several new shaders were created for this image. The custom shaders include those for thebanana leaves, the steamy jungle atmosphere, the well vapor, and the forest canopy dappled light ingeffect .Shad er s also allowed u s t o d o more wit h t he su r faces t han merely effect t he way t hey are colored .In Rend er Man, shad er s can t r ansfor m simp le su r faces int o more comp lex for ms by moving t hesurface geometry to add dimension and realistic detail. Using shaders we turned a cylinder into astone well, spheres into boulders and rocks, and a at horizontal plane into a jungle oor made up ofst ones and p ebbles.Similar ly, we alt ered t he sur face opacit y t o creat e holes in sur faces. In t his inst ance, we prod ucedt he r agged ed ges of t he banana leaves and t he well vap or by ap p lying ou r cu st om Rend er Man,shad er s t o at p ieces of geomet r y before rend er ing wit h Phot oRealist ic Rend er Man.Init ially, t his image was comp osed at a screen resolu t ion of 450 600 p ixels on a MacIIfx u singShowplace. Rendering was done transparently over the network on a Unix workstation using Pixar sNetRenderManTM. This conguration afforded us the convenience and exibility of using a Mac ford esign and a wor kst at ion for qu ick rend er ing and p r eview d u r ing t he p ict u re-making p rocess.Once the design was complete, the nal version of the image was rendered at 2250 3000 pixelr esolut ion. The nal rend er ing of t his image was d one on a 486 PC/ DOS machine wit h TruevisionsRend er PakTM and Hor izon860TM car d cont aining 32 MByt es of RAM.Dur ing t he rend er ing process, Rend er Man separ at es shad ows int o a t empor ar y le called ashad ow map. The 2k 2k shad ow map for t his image was rend ered in less t han an hour. However,u sing shad er s t o alt er t he su r face geomet r y increases rend er ing t ime and memor y r equ ir ement sdramatically. As a result, we had to divide the image into 64 separate pieces and render each oneindividually. The total rendering time for all 64 pieces was 41.7 hours. Once these were computed,viGRAPHIC GEMS II Edit ed by DAVID KIRKt he TIFF t ools from Pixar s Rend er Man ToolkitTM wer e used t o join t he pieces t oget her int o a single,33 MByt e image le.When t he image was read y for ou t p u t t o lm, we t r ansfer red t he image le t o a removablecar t r id ge and sent it t o a local out put ser vice. They out put t he elect ronic le ont o 4 5 Eckt achromecolor lm and had it d evelop ed . The t r ansp arency was t hen sent t o Acad emic Press in Cambr id ge,Massachu set t s where t hey ad d ed t he t it le and ot her element s t o t he nal (over and had ever yt hingscanned and t u r ned int o fou r-color sep ar at ions which wer e t hen su p p lied t o t heir p r int er.We hope you like t his image. Prod ucing it was fun and ed ucat ional. As you might guess, manygr ap hic gems were emp loyed in t he soft ware u sed t o p rod u ce t his p ict u r e.Mit ch Pr at er, Senior Par t nerDr. Bill Kolomyjec, Senior Par t nerRoseAnn Alsp ekt or, Senior Par t nerThe VALIS GroupPt . Richmond, CAMarch, 1992ABOUT THE COVERviiCONTENTS CONTENTS CONTENTS CONTENTS CONTENTS CONTENTSThe Symbol C denotes gems that have accompanying C implentations in the Appendix.Foreword By Andrew Glassner xviiPreface xixMat hemat ical Not at ion xxiPseudo-Code xxiiiCont ribut ors xxviiiI II III II IIMAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSING MAGE PROCESSINGInt rod uct ion 31. Fast Bit map St ret ching C 4Tomas Mller2. Gener al Filt ered Image Rescaling C 8Dale Schumacher3. Opt imizat ion of Bit map Scaling Oper at ions 17Dale Schumacher4. A Simple Color Red uct ion Filt er C 20Dennis BraggviiiCONTENTS5. Compact Isocont our s from Sampled Dat a 23Douglas Moore and Joseph Warren6. Gener at ing Isovalue Cont our s from a Pixmap C 29Tim Feldman7. Composit ing Black-and -Whit e Bit maps 34David Salesin and Ronen Barzel8. 2 12-D Dept h-of-Field Simulat ion for Comput er 36Animat ionCary Scoeld9. A Fast Bound ar y Gener at or for Composit ed 39Regions CEric Furman II II II II IIN NN NNUMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMING UMERICAL AND PROGRAMMINGT TT TTECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUES ECHNIQUESInt rod uct ion 471. IEEE Fast Square Root C 48St eve Hill2. A Simple Fast Memor y Allocat or C 49St eve Hill3. The Rolling Ball C 51Andrew J. Hanson4. Int er val Ar it hmet ic C 61Jon Rokne5. Fast Gener at ion of Cyclic Sequences C 67Alan W. Paet h6. A Gener ic Pixel Select ion Mechanism 77Alan W. Paet hi xCONTENTS7. Nonunifor m Rand om Point s Set s via War ping 80Pet er Shirley8. Cross Prod uct in Four Dimensions and Beyond 84Ronald N. Goldman9. Face-Connect ed Line Segment Gener at ion in ann-Dimensional Space C 89Didier Badouel and Charles A. Wt hrichIII III III III IIIM MM MMODELING AND TRANSFORMATIONS ODELING AND TRANSFORMATIONS ODELING AND TRANSFORMATIONS ODELING AND TRANSFORMATIONS ODELING AND TRANSFORMATIONSInt rod uct ion 951. Quat er nion Int er polat ion wit h Ext r a Spins C 96Jack Morrison2. Decomposing Project ive Tr ansfor mat ions 98Ronald N. Goldman3. Decomposing Linear and Afne Tr ansfor mat ions 108Ronald N. Goldman4. Fast Rand om Rot at ion Mat r ices C 117James Arvo5. Issues and Techniques for Keyfr aming Tr ansfor mat ions 121Paul Dana6. Unifor m Rand om Rot at ions C 124Ken Shoemake7. Int er polat ion Using Bzier Cur ves C 133Gershon Elber8. Physically Based Superquad r ics C 137A. H. BarrxCONTENTSI II IIV VV VV2 - D 2 - D 2 - D 2 - D 2 - D GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMSInt rod uct ion 1631. A Par amet r ic Ellipt ical Arc Algor it hm C 164Jerry Van Aken and Ray Simar2. Simple Connect ion Algor it hm for 2-D Dr awing C 173Claudio Rosat i3. A Fast Circle Clipping Algor it hm C 182Raman V. Srinivasan4. Exact Comput at ion of 2-D Int er sect ions C 188Clifford A. Shaffer and Charles D. Feust el5. Joining Two Lines wit h a Circular Arc FilletC193Robert D. Miller6. Fast er Line Segment Int er sect ion C 199Franklin Ant onio7. Solving t he Problem of Apollonius and Ot her 203Relat ed ProblemsConst ant ina SeviciV VV VV3 - D 3 - D 3 - D 3 - D 3 - D GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMS GEOMETRY AND ALGORITHMSInt rod uct ion 2131. Tr iangles Revisit ed 215Fernando J. Lpez-Lpez2. Par t it ioning a 3-D Convex Polygon wit h an 219Ar bit r ar y Plane CNorman Chin3. Signed Dist ance from Point t o PlaneC223Pramos GeorgiadesxiCONTENTS 4. Grouping Near ly Coplanar Polygons int o CoplanarSet s C 225David Salesin and Filippo Tampieri 5. Newells Met hod for Comput ing t he Plane Equat ionof a Polygon C 231Filippo Tampieri 6. Plane-t o-Plane Int er sect ion C 233Pramos Georgiades 7. Tr iangle-Cube Int er sect ion C 236Douglas Voorhies 8. Fast n-Dimensional Ext ent Over lap Test ing C 240Len Wanger and Mike Fusco 9. Subd ivid ing Simplices C 244Doug Moore10. Und er st and ing Simploid s 250Doug Moore11. Conver t ing Bzier Tr iangles int o Rect angularPat ches C 256Dani Lischinski12. Cur ve Tesselat ion Cr it er ia t hrough Sampling 262Terence Lindgren, Juan Sanchez, and Jim HallVl Vl Vl Vl VlR RR RRAY TRACING AND RADIOSITY AY TRACING AND RADIOSITY AY TRACING AND RADIOSITY AY TRACING AND RADIOSITY AY TRACING AND RADIOSITYInt rod uct ion 269 1. Ray Tr acing wit h t he BSP Tree C 271Kelvin Sung and Pet er Shirley 2. Int er sect ing a Ray wit h a Quad r ic Sur face C 275Joseph M. Cychosz and Warren N. Waggenspack, Jr.xiiCONTENTS 3. Use of Resid ency Masks and Object Space Par t it ioningt o Eliminat e Ray-Object Int er sect ion Calculat ions 284Joseph M. Cychosz 4. A Panor amic Vir t ual Screen for Ray Tr acing C 288F. Kent on Musgrave 5. Rect angular Bound ing Volumes for PopularPr imit ives C 295Ben Trumbore 6. A Linear-Time Simple Bound ing Volume Algor it hm 301Xiaolin Wu 7. Physically Cor rect Direct Light ing for Dist r ibut ion RayTr acing C 307Changyaw Wang 8. Hemispher ical Project ion of a Tr iangleC314Buming Bian 9. Linear Rad iosit y Approximat ion Using Ver t ex-t o-Ver t exFor m Fact or s 318Nelson L. Max and Michael J. Allison10. Delt a For m-Fact or Calculat ion for t he CubicTet r ahed r al Algor it hm C 324Jeffrey C. Beran-Koehn and Mark J. Pavicic11. Accur at e For m-Fact or Comput at ionC329Filippo TampieriVII VII VII VII VIIR RR RRENDERING ENDERING ENDERING ENDERING ENDERINGInt rod uct ion 337 1. The Shad ow Dept h Map Revisit ed 338Andrew WooxiiiCONTENTS 2. Fast Linear Color Rend er ing C 343Russell C. H. Cheng 3. Ed ge and Bit -Mask Calculat ions for Ant i-Aliasing C 349Russell C. H. Cheng 4. Fast Span Conver sion: Unrolling Shor t Loops C 355Thom Grace 5. Progressive Image Renement Via Gr id d edSampling C 358St eve Hollasch 6. Accur at e Polygon Scan Conver sion Using Half-OpenInt er vals C 362Kurt Fleischer and David Salesin 7. Dar klight s 366Andrew S. Glassner 8. Ant i-Aliasing in Tr iangular Pixels 369Andrew S. Glassner 9. Mot ion Blur on Gr aphics Wor kst at ions C 374John Snyder, Ronen Barzel and St eve Gabriel10. The Shad er Cache: A Rend er ing Pipeline Acceler at or 383James Arvo and Cary ScofeldReferences 611Index 625PSEUDO-CODE.PSEUDO-CODE.xviiFOREWARDF FF FFOREWORD OREWORD OREWORD OREWORD OREWORDby Andrew GlassnerWelcome t o Graphics Gems III, an ent irely new collect ion of t ips, t echniqu es, andalgor it hms for t he pr act icing compu t er gr aphics progr ammer. Many id eas t hat were oncepassed on t hrou gh per sonal cont act s or chance conver sat ions can now be fou nd here,clear ly explained and d emonst r at ed . Many are illu st r at ed wit h accompanying sou rcecod e.It is par t icu lar ly pleasant for me t o see new volu mes of Gems, since each is somet hingof a surprise. The original volume was meant to be a self-contained collection. At the lastmoment we included a card wit h cont r ibut or s infor mat ion in case t here might be enoughinterest to someday prepare a second edition. When the rst volume was nished and att he pr int er s, I ret ur ned t o my research in rend er ing, mod eling and animat ion t echniques.As wit h t he r st volume, I was sur pr ised by t he quant it y and qualit y of t he cont r ibut ionst hat came owing in. We realized t here was a demand,a need for an ent irely new secondvolu me, and Graphics Gems II was bor n. The same cycle has now repeat ed it self again,and we have happily ar r ived at t he creat ion of a t hird collect ion of u sefu l gr aphics t ools.Since t he r st volu me of Graphics Gems was pu blished , I have spoken t o many read er sand d iscovered t hat t hese books have helped people lear n gr aphics by st ar t ing wit hwor king codes and just explor ing int uit ively. I didnt expect people t o play wit h t he codesso freely, but I t hink I now see why t his helps. It is oft en excit ing t o st ar t lear ning a newmedium by simply messing around in it, and understanding how it ows. My piano teacherencourages new students to begin by spending time playing freely at the keyboard: keep afew scales or chord progressions in mind , bu t ot her wise explore t he spaces of melod y,har mony, and rhyt hm. When I st ar t ed t o lear n new med iu ms in ar t classes, I oft en spenttime simply playing with the medium: squishing clay into odd shapes or brushing paint onpaper in free and u nplanned mot ions. Of cou r se one oft en moves on t o d evelop cont roland t echniqu e in ord er t o commu nicat e ones message bet t er, hu t mu ch creat ivit y spr ingsfrom su ch u ncont rolled and spir it ed play.It is d ifcu lt for t he novice t o play at progr amming. There is lit t le room for simpleexpression or er ror. A simple progr am d oes not commu nicat e wit h t he same r ange andst rengt h as a mast er fu lly simple line d r awing or hau nt ing melod y. A progr ammer cannothit a few wrong notes, or tolerate an undesired ripple in a line. If the syntax isnt right, theprogr am wont compile; if t he semant ics arent r ight , t he progr am wont d o anyt hingint erest ing. There are except ions t o t he lat t er st at ement , but t hey are not able because oftheir rarity. If youre going to write a program to accomplish a task, youve got to do somet hings complet ely r ight , and ever yt hing else almost per fect ly. That can be an int imid at ingrealization particularly for the beginner: if a newly constructed program doesnt work, theproblem cou ld be in a million places, anywhere from t he archit ect u re t o d at a st r u ct u res,xviiiFOREWARDalgor it hms, or cod ing er ror s. The chance t o st ar t wit h somet hing t hat alread y wor ksremoves the barrier to exploration: your program already works. If you want to change it,you can, and you will discover which new ideas work and which ones dont.I believe t hat t he su ccess of t he Graphics Gems ser ies d emonst r at es somet hing ver yposit ive about our research and pr act ice communit ies. The moder n view of science is anaggregat e of many fact or s, but one popular myt h d epict s t he researcher as a d ispassionat eobser ver who seeks evid ence for some u lt imat e t ru t h. The classical mod el is t hat t hisobject ive researcher piles one record ed fact u pon anot her, cont inu ou sly improving anu nd er lying t heoret ical basis. This mod el has been erod ed in recent year s, bu t it remainspotent in many engineering and scientic texts and curricula. The practical application ofcomput er gr aphics is somet imes compared t o a similar ly t heoret ical commercial ind ust r y:trade secrets abound, and anything an engineer learns remains proprietary to the rm foras long as possible, t o capit alize on t he ad vant age. I d o not believe t hat eit her of t heseat t it udes are accur at e or fruit ful in t he long run. Most researcher s are biased. They believesomet hing is t ru e, from eit her exper ience or int u it ion, and seek su ppor t and ver icat ionfor t hat t ru t h. Somet imes t here are su r pr ises along t he way, bu t one d oes not simplyjuggle symbols at r andom and hope t o nd a meaningful equat ion or progr am. It is ourexper ience and insight t hat guide t he search for new lear ning and limit ed t rut hs, or t heclear d emonst r at ion of er ror s of t he gu id ing pr inciple. I hail t hese preju d ices, becau set hey for m ou r core beliefs, and allow u s t o choose and ju d ge ou r wor k. There are aninnite number of interesting problems, and many ways to solve each one. Our biases helpus pick useful problems to solve, and to judge the quality and elegance of the solution. Byexplicit ly st at ing ou r beliefs, we are bet t er able t o u nd er st and t hem, emphasizing someand expu nging ot her s, and improve. Progr ammer s of gr aphics soft ware know t hat t hewhole is much more t han t he sum of t he par t s. A snippet of geomet r y can make a complexalgor it hm simple, or t he cor rect , st able analyt ical solu t ion can replace an expensivenu mer ical approximat ion. Like an orchest r al ar r anger, t he soft ware engineer weavest oget her t he st rengt hs and weaknesses of t he t ools available t o make a new progr am t hatis more power fu l t han any componentWhen we share ou r component s, we all benet . Two prod u ct s may share some basicalgor it hms, bu t t hat alone hard ly makes t hem compar able. The fact t hat so many peoplehave cont r ibu t ed t o Gems shows t hat we are not afr aid t o d emonst r at e ou r preferencesfor what is int erest ing and what is not , what is good and what is bad , and what isappropr iat e t o share wit h colleagu es.I believe t hat t he Graphics Gems ser ies d emonst r at es some of t he best qu alit ies in t het r adit ional models of t he researcher and engineer. Gems are wr it t en by progr ammer s whowor k in t he eld who are mot ivat ed by t he oppor t unit y t o share some int erest ing or usefultechnique with their colleagues. Thus we avoid reinventing the wheel, and by sharing thisinfor mat ion, we help each ot her move t oward s a common goal of amassing a bod y ofu sefu l t echniqu es t o be shared t hr ou ghou t t he commu nit y.I believe compu t er gr aphics has t he pot ent ial t o go beyond it s cu r rent preoccu pat ionwit h phot orealism and simple su r faces and expand int o a new creat ive med iu m. Thematerials from which we will shape this new medium are algorithms. As our mastery ofalgorithms grows, so will our ability to imagine new applications and make them real,enabling new for ms of creat ive expression. I hope t hat t he algor it hms in t his book willhelp each of u s move closer t o t hat goal.xixPREFACEPREFACE PREFACE PREFACE PREFACE PREFACEThis volume at t empt s t o cont inue along t he pat h blazed by t he r st t wovol u mes of t h i s ser i es, cap t u r i n g t h e sp i r i t of t h e cr eat i ve gr ap h i csprogr ammer. Each of t he Gems represent s a carefully cr aft ed t echniqueor id ea t hat has proven useful for t he respect ive aut hor. These cont r ibu-t or s have gr aciou sly allowed t hese id eas t o be shared wit h you . Ther esu lt ing collect ion of id eas, t r icks, t echniqu es, and t ools is a r ou ghsket ch of t he char act er of t he ent ir e gr ap hics eld . It rep r esent s t hed iver sit y of t he eld , cont aining a wid e var iet y of approaches t o solvingproblems, large and small. As such, it t akes t he pulse of t he gr aphicscommunit y, and present s you wit h id eas t hat a wid e var iet y of ind ivid ualsnd int erest ing, useful, and impor t ant . I hope t hat you will nd t hem so aswell.This book can be used in many ways. It can be used as a reference, t ond t he solu t ion t o a sp ecic p roblem t hat confront s you . If you aread d r essing t he same p r oblem as one d iscu ssed in a p ar t icu lar Gem,youre more t han halfway t o a solut ion, par t icular ly if t hat Gem provid esC or C + + cod e. Many of t he id eas in t his volume can also be used as ast ar t ing point for new wor k, provid ing a fresh point of view. However youchoose t o use t his volume, t here are many id eas cont ained herein.This volume ret ains t he over all st ruct ure and organizat ion, mat hemat i-cal not at ion, and st yle of pseud o-cod e as in t he r st and second volumes.Some of t he ind ivid u al chap t er names have been changed t o allow apar t it ioning t hat is more appropr iat e for t he cur rent crop of Gems. Ever yat t empt has been mad e t o group similar Gems in t he same chapt er. Manyof t he chapt er head ings appeared in t he r st t wo volumes, alt hough someare new. Ray t r acing and r ad iosit y have been combined int o one chapt er,since many of t he gems are applicable t o eit her t echnique. Also, a chapt ermore gener ally t it led Rend er ing has been ad d ed , which cont ains manyalgor it hms t hat ar e ap p licable t o a var iet y of t echniqu es for makingpict ures.As in t he second volume, we have t aken some of t he impor t ant sect ionsfr om t h e r st vol u me a n d i n cl u d ed t h em ver ba t i m. Th ese sect i on sar e ent it led Mat hemat ical Not at ion, Pseu d o-Cod e, and t he list ings,xxPREFACEGr aphics Gems C Head er File, and 2-D and 3-D Vect or Libr ar y, t helast of which was revised in volume t wo of Gr aphics Gems.At the end of most Gems, there are references to similar Gems whetherin this volume or the previous ones, identied by volume and pagenumber. This should be helpful in providing background for the Gems,although most of them stand quite well on their own. The only back-ground assumed in most cases is a general knowledge of computergraphics, plus a small amount of skill in mathematics.The C programming language has been used for most of the programlistings in the Appendix, although several of the Gems have C+ +implementations. Both languages are widely used, and the choice ofwhich language to use was left to the individual authors. As in the rsttwo volumes, all of the C and C + + code in this book is in the publicdomain, and is yours to study, modify, and use. As of this writing, all ofthe code listings are available via anonymous ftp transfer from themachines weedeater. math. yale. edu (internet address 128. 36. 23. 17), andprinceton. edu (internet address 128. 112. 128. 1). princeton. edu is thepreferred site. When you connect to either of these machines using ftp,log in as anonymous giving your full e-mail address as the password.Then use the cd command to move to the directory pub/Graphics-Gems on weedeater , or the directory pub/Graphics/GraphicsGemson princeton. Code for Graphics Gems I, II, and III is kept indirectories named Gems, Gemsll, and Gemslll, respectively. Down-load and read the le called README to learn about where the code iskept, and how to report bugs. In addition to the anonymous ftp site, thesource listings of the gems are available on the enclosed diskette in eitherIBM PC format or Apple Macintosh format.Finally, Id like to thank all of the people who have helped along theway to make this volume possible. First and foremost, Id like to thankAndrew Glassner for seeing the need for this type of book and starting theseries, and to Jim Arvo for providing the next link in the chain. Id alsolike to thank all of the contributors, who really comprise the heart of thebook. Certainly, without their cleverness and initiative, this book wouldnot exist. I owe Jenifer Swetland and her assistant Lynne Gagnon a greatdeal for their magical abilities applied toward making the whole produc-tion process go smoothly. Special thanks go to my diligent and thoughtfulreviewersTerry Lindgren, Jim Arvo, Andrew Glassner, Eric Haines,Douglas Voorhies, Devendra Kalra, Ronen Barzel and John Snyder. With-out their carefully rendered opinions, my job would have been a lotharder. Finally, thank you to Craig Kolb for providing a safe place to keepthe public domain C code.xxi GRAPHICS GEMS III Edit ed by DAVID KIRK xxiMATHEMATICAL NOTATIONM MM MMATHEMATICAL ATHEMATICAL ATHEMATICAL ATHEMATICAL ATHEMATICALN NN NNOTATION OTATION OTATION OTATION OTATIONGeomet 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 s0 t he number 0, t he zero vect or, t he point (0, 0), t hepoint (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 Ai)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 sAthe vector perpendicular to A (valid only in 2D, whereA = (Ay, Ax)M-1t he inver se of mat r ix MMTt he t r anspose of mat r ix MM*t he ad joint of mat r ix M M1Mdet M ( )

_,

| M| d et er minant of Md et (M) same as aboveMi,jelement from row i, column j of matrix M (top-left is(0, 0)Mi,all of row i of mat r ix Mxxii GRAPHICS GEMS III Edit ed by DAVID KIRK xxiiMATHEMATICAL NOTATIONM,jall of column j of Mat r ixABC 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 BBasi 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 st he d ot (or inner or scalar ) prod uctt he cross (or out er or vect or ) prod uctBasi 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 1ceiling of x (smallest int eger not smaller t han x)a| b mod ulo ar it hmet ic; remaind er of a ba mod b same as above Bint ( ) Ber nst ein polynomial = ni

_,

ti1 t ( )n i, i 0Ln ni

_, binomial coefficient n!n i ( )!i!xxiiiPSEUDO-CODEGRAPHICS GEMS III Edit ed by DAVID KIRK xxiiiP PP PPSEUDO-CODE SEUDO-CODE SEUDO-CODE SEUDO-CODE SEUDO-CODEDecl 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 Typesarray [lower Bound ..upper Bound ] of TYPE;bool eanchari ntegerrealdoubl epoi ntvectormatri 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 rixxxivPSEUDO-CODEGRAPHICS GEMS III Edit ed by DAVID KIRK xxivmatri x4equivalent 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.0m[0][3] 3.3; assigns 3.3 t o upper-right corner of mat rixRecor 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 itnewBox.left 10; t his same not at ion is appropriat e whet her newBox is a point er or st ruct ureAr r ays Ar r ays Ar r ays Ar r ays Ar r aysv: array [0..3] of integer [0, 1, 2, 3]; v is a four-element array of integersv[2] 5; assign t o t hird element of vComment s Comment s Comment s Comment s Comment sA comment may appear anywhereit is indicat ed by it alicsxxvPSEUDO-CODEGRAPHICS GEMS III Edit ed by DAVID KIRK xxvBl ocks Bl ocks Bl ocks Bl ocks Bl ocksbegi nSt at ement ;St at ement ; Lend;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 onsi f Testthen St at ement ;[el se St at ement ]; else clause is opt ionalresult = sel ect It em frominst 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 olfor Cont rolVar iable: Type Init ialExpr, Next Expr doSt at ement ;endl oop;unti l Test doSt at ement ;endl oop;whi l e Test doSt at ement ;endl oop;l oop; go direct ly t o t he next endloopexi t; go direct ly t o t he rst st at ement aft er t he next endloopreturn[value] ret urn value as t he result of t his funct ion callxxviPSEUDO-CODEGRAPHICS GEMS III Edit ed by DAVID KIRK xxviLogi cal Connect i ves Logi cal Connect i ves Logi cal Connect i ves Logi cal Connect i ves Logi cal Connect i vesor, and, not, xorBi 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 sbi t-or, bi t-and, bi t-xorRel at i ons Rel at i ons Rel at i ons Rel at i ons Rel at i ons=, , >, , h, else v: min(h,max(l,v))oor (x) or x ]round x t owards 0 t o rst int egerceiling(x) or x 1round x away from 0 t o rst int egerround(x) round x to nearest integer, if frac(x) = .5, round towards0fr ac(x) fract ional part of xxxviiiCONTRIBUTERSCONTRIBUTORS CONTRIBUTORS CONTRIBUTORS CONTRIBUTORS CONTRIBUTORSNumbers in parentheses indicate pages on which authors gems begin.Michael J. Allison (318), Lawrernce Livermore National Laboratory, P.0. Box 808,Livermore, California 94450Franklin Antonio (199), Qualcomm, Inc., 2765 Cordoba Cove, Del Mar, California92014James Arvo (117, 383), Program of Computer Graphics, Cornell University, Ithaca,New York 14853Didier Badouel (89), Computer Systems Research Institute, University of Toronto, .10Kings College Road, Toronto, Ontario M5S 1A4, Canada, [email protected]. H. Barr (137), Computer Graphics Laboratory, California Institute of Technology,Pasadena, California 91125Ronen Barzel (34, 374), Computer Graphics, California Institute of Technology, 350-74,Pasadena, California 91125, [email protected] C. Beran-Koehn (324), Department of Computer Science, North Dakota StateUniversity, 300 Minard Hall, SU Station, P.0. Box 5075, Fargo, North Dakota58105-5075, beran-ko@plains,nodak.eduBuming Bian (314), UT System Center for High Performance Computing, 10100Burnet Rd., Austin, Texas 78758-4497, [email protected] Bragg (20), Graphics Software, Inc., 23428 Deer Run, Bullard, Texas 75757Russell C. H. Cheng (343, 349), School of Mathematics, University of Wales, College ofCardiff, Senghynnydd Road, P.0. Box 915, Cardiff CF2 4AG, United Kingdom,[email protected] Chin (219), Department of Computer Science, Columbia University, NewYork, New York 10027, [email protected] M. Cychosz (275, 284), Purdue University CADLAB, Potter Engineering Cen-ter, 520 Evergreen, West Lafayette, Indiana 47907Paul Dana (121), Shadow Graphics, 112 Lily Court, Madison, Alabama 35758, com-puserve: 71351,372Gershon Elber (133), Computer Science Department, University of Utah, Salt LakeCity, Utah 84112, [email protected] Feldman (29), Island Graphics Corporation, 4000 Civic Center Drive, San Rafael,California 94903, [email protected] D. Feustel (188), Department of Mathmatics, Virginia Tech, Blacksburg,Virginia 24061, [email protected] Fleischer (362), California Institute of Technology, Box 35074, Pasadena, Cali-fornia 91125, [email protected] Furman (39), General Dynamics, Electronics Division, San Diego, California92115Mike Fusco (240), SimGraphic.s Engineering, 1137 Huntington Drive, A1, SouthPasadena, California 91030Steve Gabriel (374), 10495 W. 85th Place, Arvada, California 80005Pramos Georgiades (223, 233), CrystalGraphics, Inc.; 3110 Patrick Henry Drive,Santa Clara, California 95054Andrew Glassner (366, 369), Xerox PARC, 3333 Coyote Hill Rd., Palo Alto, California94304Ronald N. Goldman (84, 98, 108), Computer Science Department, Rice University, P.0.Box 1892, Houston, Texas 77251Thom Grace (355), Department of Computer Science, Illinois Institute of Technology,10 West 31st Street, Chicago, Illinois 60616, [email protected] Hall (262), Prime / Computervision, Crosby Dr., Bedford, Massachusetts 01730Andrew J. Hanson (51), Computer Science Department, Indiana University, Blooming-ton, Indiana 47405, [email protected] Hill (48, 49), Computing Laboratory, University of Kent, Canterbury, KentCT2 7NF, United Kingdom, [email protected] Hollasch (358), Kubota Pacic Computer, Inc., 2464 El Camino Real, Box #11,Santa Clara, California 95051, [email protected] Lindgren (262), Prime / Computervision, Crosby Drive, Bedford, Massachusetts 01730xxxCONTRIBUTERSDani Lischinski (256), Program of Computer Graphic.s, Cornell University, ETCBuilding, Ithaca, New York 14853, [email protected] J. Lpez-Lpez (215), Physics and Astronomy Deparment, SouthwesternCollege, Chula Vista, California 91810Nelson L. Max (318), Lawrence Livermore National Laboratory, P.O. Box 808, L-301,Livermore, CaIifornia 94550, [email protected] D. Miller (193), 1837 Burrwood Circle, E. Lansing, Michigan 48823Tomas Mller (4), Lund Institute of Technology, sommarstugevgan, 10, 263 71Hgans, Sweden, [email protected] Moore (28, 244, 250), Department of Computer Science, Rice University, P.0.Box 1892, Houston, Texas 77251, [email protected] Morrison (96), Digital Insight, P.0. Box 2095, Evergreen, Colorado 80439-2095F. Kenton Musgrave (288), Departments of Computer Science and Mathematics, YaleUniversity, Box 2155 Yale Station, New Haven, Connecticut 06520Alan W. Paeth (67, 77), NeuralWare Inc., 4-227 Penn Center W., Pittsburgh, Pennsyl-vania 15136, [email protected] J. Pavicic (324), Department of Computer Science, North Dakota State Univer-sity, 300 Minard Hall, SU Station, P.0. Box 5075, Fargo, Norlh Dakota 58105-5075,[email protected] Rokne (61), Department of Computer Science The University of Calgary, 2500University Drive N.W., Calgary, Alberta T2N 1N4, CanadaClaudio Rosati (173), IRIS s.r.l., Parco La Selva 151, 03018 PaIiano (FR), ItalyDavid Salesin (34, 225, 362), Program of Computer Graphics, 584 ETC BuildingCornell University, Ithaca, New York 14853-3801, [email protected] Sanchez (262), Prime / Computervision, Crosby Dr., Bedford, Massachusetts01730Dale Schumacher (8, 17), 399 Beacon Avenue, St. Paul, Minnesota 55014,[email protected] Scoeld (36, 383), Hewlett-Packard Company, 300 Appollo Drive, Chelmsford,Massachusetts 01824, [email protected] A. Sevici (203), GTS, 8 Crabapple Lane, Chelmsford, Massachusetts 01824Clifford A. Shaffer (188), Department of Computer Science, Virginia Tech, Blacksburg,Virginia 24061, [email protected] Shirley (80, 271), Department of Computer Science, Indiana University, 101Lindly Hall, Bloomington, Indiana 47405-4101, [email protected] Shoemake (124), 4417 BaItimore Avenue, Philadelphia, Pennsylvania 19104xxxiCONTRIBUTERSRay Simar (164), Texas Instruments, P.O. Box 443, Houston, Texas 77251John Snyder (374), California Institute of Technology, Box 350-74, Pasadena, Califor-nia 91125, [email protected] V. Srinivasan (182), SDRC, 2000 Eastman Drive, Milford, Ohio 45150Kelvin Sung (271), Department of Computer Science, University of Illinois atUrbana-Champaign, 1304 West Springfield Avenue, Urbana, Illinois 61801,[email protected] Tampieri (225, 231, 329), Program of Computer Graphics, Cornell University,580 ETCBuilding, Ithaca, New York 14853, [email protected] Trumbore (295), Program of Computer Graphics, Cornell University, 580 TheoryCenter Building, Ithaca, New York 14853, [email protected] R. Van Aken (164), Texas Instruments, Mail Stop 712, 12203 Southwest Freeway,Stafford, Texas 77477, [email protected] Voorhies (236), Silicon Graphics Inc., P.0. Box 7311, Mountain View, Califor-nia 94039-7311, [email protected] N. Waggenspack, Jr. (275), IMRLAB, Mechanical Engineering, Louisiana StateUniversity, Baton Rouge, Louisiana 70803Changyaw Wang (307), Department of Computer Science, Indiana University, 101Lindley Hall, Bloomington, Indiana 47405-4101, [email protected] Wanger (240), SemGraphics Engineering, 1137 Huntington Drive, Al, SouthPasadena, California 91030, [email protected] Warren (23), Departrnent of Computer Science, Rice University, P.0. Box 1892,Houston Texas 77251, [email protected] Woo (338), Alias Research, Style Division, 110 Richmond Street East, Toronto,Ontario M5C 1P1, CanadaXiaolin Wu (301), Department of Computer Science, Middlesex College, University ofWestern Ontario, London, Ontario, N6A 5B7 CanadaCharles A. Wthrich (89), Cornputer Systems Research Institute, University ofToronto, 6 Kings College Road, Toronto, Ontario M5S 1A1, Canada,[email protected] GRAPHIC GEMS III Edit ed by DAVID KIRK 3IMAGE PROCESSING IMAGE PROCESSING IMAGE PROCESSING IMAGE PROCESSING IMAGE PROCESSINGAll of t he Gems in t his sect ion involve oper at ions per for med on images,or t wo-d imensional ar r ays of pixels. Oft en, a gr aphics progr ammer maywant t o change t he size, t he color s, or ot her feat ures in an image. Thefir st t hree Gems d escr ibe t echniques for st ret ching or scaling images invar ious cont ext s. The fir st Gem emphasizes speed , while t he next t woemphasize qualit y. The four t h Gem d escr ibes a met hod for d isplaying afull color image using a red uced set of color s.In some cases, it is useful t o combine feat ures from sever al images. Thesevent h Gem applies t he now-familiar algebr a of image composit ion t oblack and whit e bit maps, or l-bit images. The eight h Gem d iscusses howt o blur t wo images select ively while combining t hem in ord er t o simulat ecamer a aper t ure d ept h-of-field effect s.Somet imes t he d esired result is not anot her image bu t , in fact , analt er nat ive represent at ion of some of t he feat ures in t he image. The fift h,sixt h, and nint h Gems d escr ibe t echniques for ext r act ing region bound ar yinfor mat ion from images.GRAPHICS GEMS III Edit ed by DAVID KIRK 4I.1 FAST BITMAP STRETCHINGI II II.1 .1 .1 .1 .1F FF FFAST BITMAP STRETCHING AST BITMAP STRETCHING AST BITMAP STRETCHING AST BITMAP STRETCHING AST BITMAP STRETCHINGTomas MllerLund Inst it ut e of TechnologyHoganas, SwedenInt r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i onPresent ed here is an int eger algor it hm for st ret ching ar bit r ar y hor izont alor ver t ical lines of a bit map ont o any ot her ar bit r ar y line. The algor it hmcan be used in d r awing and paint ing progr ams where near real-t ime orreal-t ime p er for mance is requ ir ed . Examp les of ap p licat ion areas areenlarging and d iminishing rect angular areas of bit maps and wr appingrect angular areas ont o, for example, circular areas.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 hmThe rout ine it self is ver y simple, and most comput er-gr aphics progr am-mer s are probably familiar wit h t he Bresenham line d r awing algor it hm(1965) t hat it is based upon. In fact , it could be based on any line-d r awingalgor it hm; however, Bresenham was chosen, as it is int eger-based andver y wid espread wit hin t he comput er gr aphics communit y. For t hose ofyou who are not familiar wit h t he Bresenham algor it hm, pseud o-cod efollows for line d r awing in t he r st oct ant .procedure Line(x1, y1, x2, y2);draw a line from (x1, y1) t o (x2, y2) in rst oct ant;all variables are int egerbegi nd x x2 x1d y y2 y1e 2*d y d xGRAPHICS GEMS III Edit ed by DAVID KIRK 5I.1 FAST BITMAP STRETCHINGfor i 1, i < = d x, i i + 1 doWr it ePixel(x1, y1) ;display pixel at (x1, y1)whi l e e > = 0 doy1 y1 + 1e e 2*d xendl oopx1 x1 + 1e e + 2*d yendl oopend Line;The pseud o-cod e above wor ks for t he second oct ant as well, but in t hatcase t he lines will not be cont inuous, since x1 always is increment ed by1. This suit s t he algor it hm ver y well.Let us go back t o t he explanat ion of t he st ret ching algor it hm. Inst eadof int er pret ing x1 and y1 as a pair of coord inat es on a 2-D line, t heymust be int er pret ed as 1-D coord inat es. dx must be int er pret ed as t helengt h of t he d est inat ion line, and dy as t he lengt h of t he source line.Using t hese int er pret at ions, x1 will be t he coord inat e on t he d est inat ionline and y1 t he coord inat e on t he sour ce line. For each pixel on t hed est inat ion line, a pixel is select ed from t he source line. These pixels areselect ed in a unifor m way. See Fig. 1.If dx is great er t han dy, t hen t he d est inat ion line is longer t han t hesource line. Therefore, t he source line will be enlarged when plot t ed ont he d est inat ion line. On t he ot her hand , if dy is great er t han dx, t hen t heFigure 1.GRAPHICS GEMS III Edit ed by DAVID KIRK 6I.1 FAST BITMAP STRETCHINGsource line will be d iminished . If dx is equal t o dy, t he algor it hm willyield t he same sor t of line as t he source. Here follows t he complet est ret cher-algor it hm in pseud o-cod e, rewr it t en t o be able t o hand le lineswhere x2 < x1 and y2 < y1.procedure St ret ch(x1, y1, x2, y2, yr, yw);st ret ches a source line(y1 t o y2) ont o t he dest inat ion line;(x1 t o x2). Bot h source & dest inat ion lines are horizont al;yr = horizont al line t o read pixels from;yw = horizont al line t o writ e pixels t o;ReadPixel(x, y) ret urns t he color of t he pixel at (x, y);Writ ePixel(x, y) writ es a pixel at (x, y) wit h current color;Set Color(Color) set s t he current writ ing color t o Colorbegi nd x abs(x2 x1)d y abs(y2 y1)sx sign(x2 x1)sy sign(y2 y1)e 2*d y d xd x2 2*d xd y 2*d yfor i 0, i < = d x, i i + 1 docolor Read Pixel(yl, yr )Set Color (color )Wr it ePixel(x1, yw);whi l e e > = 0 doy1 y1 + sye e d x2endl oopx1 x1 + sxe e + d yendl oopend St ret ch;functi on sign(n):i nteger;begi ni f x > 0 return 1else return 1end sign;GRAPHICS GEMS III Edit ed by DAVID KIRK 7I.1 FAST BITMAP STRETCHINGThe sign funct ion d oes not need t o ret ur n zero if x is equal t o zero,because t hen eit her dx or dy is equal t o zero, which means a line wit h alengt h equal t o 1. Since t his algor it hm only uses int eger ar it hmet ic andd oes not use mult iplicat ions or d ivisions, it is ver y efcient and fast .Anot her int erest ing t hing about t his lit t le progr am is t hat it can be usedt o gener at e sever al d ifferent shapes of bit maps. Her e follows a list ofsome t hings it can be used t o rend er.Some Pr oj ect s Usi ng t he Bi t map St r et cher Some Pr oj ect s Usi ng t he Bi t map St r et cher Some Pr oj ect s Usi ng t he Bi t map St r et cher Some Pr oj ect s Usi ng t he Bi t map St r et cher Some Pr oj ect s Usi ng t he Bi t map St r et cher Rect angu lar pict u res wr apped ont o cir cu lar or ellipt ical areas. Seesource cod e in append ix for wr apping ont o circles. Enlarging and d iminishing rect angular par t s of bit maps. See sourcecod e in append ix. Wr apping rect angular par t s of bit maps around par allel t r apeziums. Forexample, a rect angle t hat is rot at ed around t he x- or y-axis, and t henper spect ive-t r ansfor med , can be used as t he d est inat ion shape.Fur t her Wor k Fur t her Wor k Fur t her Wor k Fur t her Wor k Fur t her Wor kTo improve t he algor it hm, p er hap s an ant i-aliasing rou t ine cou ld bead d ed .See also G1, 147; G1, 166; G3, A.2.8I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 8I. 2 I. 2 I. 2 I. 2 I. 2GENERAL FILTERED IMAGE GENERAL FILTERED IMAGE GENERAL FILTERED IMAGE GENERAL FILTERED IMAGE GENERAL FILTERED IMAGE RESCALING RESCALING RESCALING RESCALING RESCALINGDale SchumacherSt . Paul, Minnesot aA r ast er image can be consid ered a rect angular gr id of samples of acont inuous 2-D funct ion f(x, y). These samples are assumed t o be t heexact value of t he cont inuous funct ion at t he given sample point . Theid eal proced ure for rescaling a r ast er image involves reconst ruct ing t heor iginal cont inu ou s fu nct ion and t hen resamp ling t hat fu nct ion at ad ifferent r at e (Pr at t , 1991; Foley et al., 1990). Sampling at a higher r at e(samp les closer t oget her ) gener at es more samp les, and t hu s a largerimage. Sampling at a lower r at e (samples far t her apar t ) gener at es fewersamples, and t hus a smaller image. For t unat ely, we d ont really havet o r econst r u ct t he ent ir e cont inu ou s fu nct ion, bu t mer ely d et er minet h e val u e of t h e r econ st r u ct ed fu n ct i on at t h e p oi n t s t h at cor r es-p ond t o t he new samp les, a mu ch easier t ask (Smit h, 1981). Wit hcareful choice of lt er s, t his resampling process can be car r ied out int wo passes, st ret ching or shr inking t he image r st hor izont ally and t henver t ically (or vice ver sa) wit h pot ent ially d ifferent scale fact or s. The t wo-pass approach has a signicant ly lower run-t ime cost , O(image_wid t h*i ma ge_h ei gh t *(l t er _wi d t h + l t er _h ei gh t )), t h a n st r a i gh t for wa r d2-D lt er ing, O(image_wid t h*image_height *lt er _wid t h*lt er _height ).The process of making an image larger is known by many names,includ ing magnicat ion, st ret ching, scaling up, int er polat ion, and upsam-pling. I will refer t o t his process as magnicat ion. The process of makingan image smaller is also known by many names, includ ing minicat ion,shr inking, scaling d own, d ecimat ion, and d ownsampling. I will refer t ot his p rocess as minicat ion. The p r ocesses will be exp lained in one9I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 9Figure 1.d imension r at her t han t wo, since t he scaling is car r ied out in each axisind epend ent ly.In magnicat ion, we d et er mine t he cont r ibu t ion each sou r ce p ixelmakes t o each d est inat ion p ixel by ap p licat ion of a lt er fu nct ion.Samp ling t heor y st at es t hat t he sinc fu nct ion, f(x) = sin(x)/ x, isid eal for reconst ruct ion; however, we have a nit e sample set and need alt er wit h a nit e suppor t (t hat is, t he area over which t he lt er isnonzero). The lt er I use in t his example is a cu bic fu nct ion, f(x) =2x3 3x 2 + 1, from 1 t o +1, which cover s a unit volume at eachsample when applied separ ably. Figure 1 compares t hese lt er funct ions.The d esign of resampling lt er s is a source of end less d ebat e and isbeyond t he scope of t his gem, but is d iscussed in many ot her wor ks(Pr at t , 1991; Tur kowski, 1990; Mit chell, 1988; Smit h, 1982; Oppenheimand Schafer, 1975; Rabiner and Gold , 1975). To apply t he lt er, we placea copy of our lt er funct ion cent ered around each source pixel, andscaled t o t he height of t hat pixel. For each d est inat ion pixel, we comput et he cor respond ing locat ion in t he source image. We sum t he values of t heweight ed lt er funct ions at t his point t o d et er mine t he value of ourd est inat ion pixel. Figure 2 illust r at es t his process.In minicat ion, t he process is similar, but not id ent ical, since we mustbe concer ned wit h frequency aliasing. Sampling t heor y d enes t he Nyquistfrequency as t he sampling r at e t hat will cor rect ly capt ure all frequencycomponent s in our cont inuous source signal. The Nyquist frequency ist wice t he frequency of t he highest -frequency component in our sourcesignal. Any frequency component t hat is higher t han half t he samplingr at e will be sampled incor rect ly and will be aliased t o a lower frequency.1 0I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 0Input SamplesOutput SamplesFigure 2.Therefore, a r econst ruct ed signal will cont ain only frequency component sof half t he sampling r at e or less. Dur ing magnicat ion, we are st ret chingour reconst ruct ed signal, lower ing it s component frequencies. However,d ur ing minicat ion, we are shr inking our reconst r uct ed signal, r aising it scomponent frequencies, and possibly exceed ing t he Nyquist frequency ofour new sampling r at e. To creat e proper samples, we must eliminat e allfrequency component s above t he resampling Nyquist frequency. This canbe accomplished by st ret ching t he lt er funct ion by t he image red uct ionfact or. Also, since t he lt er s at each source pixel are wid er, t he sums will1 1I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 1Input Sampl esOutput Sampl esFigure 3.be propor t ionally gr eat er and should be d ivid ed by t he same fact or t ocompensat e. Figure 3 illust r at es t his process.So far we have only consid ered t he one-d imensional case. We ext endt his t o t he t wo-d imensional case of a t ypical r ast er image by scaling r sthor izont ally and t hen ver t ically. The fur t her opt imizat ion of scaling t hesmallest d est inat ion axis r st will not be illust r at ed here. The lt er ingop er at ion can lead t o a signicant nu mber of comp u t at ions, so weprecalculat e as much as possible. The scaling process for each row (orcolumn) is id ent ical. The placement and area of t he lt er s is xed ; t hus,1 2I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 2we can precalculat e t he cont r ibut or s t o each d est inat ion pixel and t hecor respond ing lt er weight . The pseud o-cod e for calculat ing t he cont r ibu-t or s t o a d est inat ion pixel is as follows:calculat e_cont r ibut ions(d est inat ion);beginscale d st _size/ src_size;cent er d est inat ion/ scale;if (scale < 1.0) t hen beginwid t h lt er _wid t h/ scale;fscale 1.0/ scale;elsewid t h lt er _wid t h;fscale 1.0;end ;left oor (cent er wid t h);r ight ceiling(cent er + wid t h);for source left , sour ce = source + 1, source r ight d oweight lt er ((cent er source)/ fscale)/ fscale;ad d _cont r ibut or (d est inat ion, source, weight );end loop;end ;Aft er t he cont r ibut ions have been calculat ed , all t he rows (or columns) oft he d est inat ion image can be processed using t he same precalculat edlt er values. The following pseud o-cod e shows t he applicat ion of t hesevalues t o scale a single d est inat ion row.scale_row(d est inat ion_row, source_row)beginfor i 0, i i + 1, i < d st _size d ov 0;for j 0, j j + 1, j < cont r ibut or s[i] d os cont r ibut or [i][j];w weight _value[i][j];v v + (source_row[s]*w);end loop;d est inat ion_row[i] v;end ;1 3I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 3Figur e 4.Figur e 5.1 4I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 4Figur e 6.Figur e 7.1 5I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 5Figure 8.The same process is t hen applied t o t he columns of t he imager stp r ecalcu lat ing t he lt er cont r ibu t ions accord ing t o t he ver t ical scalefact or (which may be d ifferent t han t he hor izont al), and t hen processingcolumns from t he int er med iat e (hor izont ally scaled ) image t o t he nald est inat ion image.In t he sou rce cod e p r ovid ed in t he Ap p end ix, a nu mber of lt erfunct ions are given, and new funct ions may be easily ad d ed . The zoom()funct ion t akes t he name of t he d esired lt er and t he lt er suppor t aspar amet er s. Figures 4 t hrough 8 show t he effect of var ious lt er s on asample image, along wit h t he impulse response gr aphs for each lt erfunct ion.The sample images have been scaled up by a fact or of 12 in bot hd irect ions. Figure 4 shows a box lt er, which is equivalent t o d irectreplicat ion of pixel values, as it shows consid er able t iling or jaggies.Figure 5 shows t he t r iangle or Bar t let t lt er, a consid er able improvementover t he box, st ill comp u t at ionally simp le, bu t t here are st ill shar pt r ansit ion lines. Figure 6 shows a cubic B-spline, which creat es no shar pt r ansit ions, but it s wid t h causes excessive blur r ing. The t r iangle andB-spline funct ions are comput ed by convolving t he box lt er wit h it self1 6I.2 GENERAL FILTERED IMAGE RESCALINGGRAPHIC GEMS III Edit ed by DAVID KIRK 1 6one and t hree t imes, respect ively. Figure 7 shows t he Lanczos3 lt er, asinc funct ion d amped t o zero out sid e t he 3 t o +3 r ange, which showst he excessive r inging effect t hat occur s wit h t he full sinc funct ion.Figure 8 shows t he Mit chell lt er (B = 13, C = 13), a cubic funct ion wit hno shar p t r ansit ion, and a good comp romise bet ween r inging andblur r ing effect s.See also G1, 147; G1, 166; G3, A.1.GRAPHICS GEMS III Edit ed by DAVID KIRK 1 71.3 OPTIMIZATION OF BITMAP SCALING OPERATIONSI. 3 I. 3 I. 3 I. 3 I. 3OPTIMIZATION OF BITMAP OPTIMIZATION OF BITMAP OPTIMIZATION OF BITMAP OPTIMIZATION OF BITMAP OPTIMIZATION OF BITMAPSCALING OPERATIONS SCALING OPERATIONS SCALING OPERATIONS SCALING OPERATIONS SCALING OPERATIONSDale SchumacherSt . Paul Minnesot aThis gem d escr ibes a ser ies of opt imizat ions for bit map scaling oper a-t ions. Inst ead of giving gener al scaling algor it hms, we t ake ad vant age ofsever al applicat ion-specific const r aint s t hat allow significant red uct ions inexecut ion t ime: single-bit per pixel images, known source and d est inat ionbit map sizes, and bit -packed hor izont al r ast er st or age and d isplay for-mat s. The example applicat ion is t he d isplay of fax bit map images ont ypical vid eo monit or s.We fir st assu me t hat we have t he sou rce FAX in memor y, u ncom-p ressed , st or ed as 8-bit byt es, wit h t he high-ord er bit of each byt erepresent ing t he left most pixel in a group of eight along a hor izont al row.Fu r t her, we assu me, in choosing ou r examp le scale fact or s, t hat t heresolut ion of t he source FAX is 200 d ot s-per -inch, in bot h d irect ions. Ift he d at a is in t he oft en-used 200 100 d pi for mat , we can make it200 200 d pi by replicat ing each scanline, a t ask we can oft en hand le int he d ecompression phase. Init ially we will assume t hat t he d at a is st oredwit h t he bit values for whit e and black mat ching t hose used by t hed isplay. A good met hod of inver t ing t he meaning of 0 and 1 bit s will bed iscussed lat er. Finally, we assume t hat t he d est inat ion bit map will havet he same for mat as t he source.Since our example image resolut ion is higher t han your t ypical vid eomonit or, we will only be consid er ing t he case of red ucing t he image,r at her t han enlarging it . Also, for reasons which will soon be apparent , wewor k in eight s for scale fact or s, 78 = 87.5%, 68 = 75%, 58 = 62.5%, 48 = 50%, 38 = 37.5%, 28 = 25%. The gener al algor it hm wor ks as follows. Take asingle scanline from t he source image. For each byt e, use t he byt e valueas an ind ex int o a lookup t able t hat gives t he red uced bit s for a givenGRAPHICS GEMS III Edit ed by DAVID KIRK 1 81.3 OPTIMIZATION OF BITMAP SCALING OPERATIONSinput byt e. Shift t he d er ived out put bit s int o an accumulat or. The numberof bit s ad d ed t o t he accumulat or for each input byt e is based on t he scalefact or (e.g., if we are red ucing t o 58 scale, we gener at e five bit s out put foreach eight bit s input ). When t he accumulat or has at least eight bit s in it , weremove t he left most eight bit s from t he accumulat or and wr it e t hem as anout put byt e int o t he d est inat ion scanline. Any bit s remaining at t he end oft he scanline are shift ed int o p osit ion and flu shed ou t . Many sou rcescanlines can be skipped ent ir ely, again based on t he scale fact or (e.g., at 58scale we only process five out of ever y eight scanlines, skipping t hree).Now t hat t he basic algor it hm is und er st ood , we can d iscuss some usefulvar iat ions and improvement s on t he process. The hear t of t he algor it hm ist he red uct ion lookup t able. If we need t o rever se black and whit e in t hefinal image, one way t o d o it is t o inver t t he bit s st ored in t he lookupt able. Then, inst ead of 00000000b mapping t o 00000b it would map t o11111b. This essent ially gives us phot omet r ic inver sion for free d ur ingrescaling. Similar ly, we can solve anot her problem, again for free, bycareful creat ion of t he lookup t able. if we red uce t o 38 scale, we would beseeking t hree out of each eight bit s t o out put . The simplist ic way t o d ot his is shown in Fig. 1a. A bet t er way is t o simulat e a for m of filt er ing or (a) (b)Figure 1.GRAPHICS GEMS III Edit ed by DAVID KIRK 1 91.3 OPTIMIZATION OF BITMAP SCALING OPERATIONSweight ed aver aging over t he source bit s, as shown in Fig. 1b. Since t helookup t able can be creat ed at compile-t ime, t he comput at ional cost t ocreat e t he t able using a more complex algor it hm is ir relevant t o run-t imeper for mance. To d o proper filt ered scaling, we should really be applyingt he filt er across ad jacent scanlines, and across byt e bound ar ies as well.Since t hose oper at ions would car r y a high run-t ime cost , and applyingfilt er ing in t he limit ed way t hat we can show an improvement wit houtad d it ional cost , we d o what is cheap. It is bet t er t o use filt er ing, evenwit hin t hese rest r ict ions, t han t o d irect ly su bsamp le t he inp u t as inFig. 1a.Any kind of t r ansfer funct ion youd like can be applied in t he same way,wit hin t he limit at ions of an 8-bit span and only black and whit e as inputvalues. You can even d o t hings like rever se t he ord er of t he bit s, whichcan be used in conjunct ion wit h a d ifferent st or age ord er t o eit her flip t heimage left -t o-r ight , or rot at e it 180 d egrees (in case someone fed t heimage int o t he scanner upsid e-d own). Expand ing t he t able t o 16 bit s,which t akes 128Kb of memor y r at her t han t he 256b used by t he 8-bitt able, gives even more flexibilit y. Wit h 16 bit s you have a wid er span t owor k wit h, and can select scale fact or s in sixt eent hs r at her t han eight hs,which may allow a bet t er mat ch t o you r vid eo d isp lay size. Theset echniqu es, and t he samp le cod e given in t he ap p end ix, ar e simp lybuild ing blocks. Examine t he const r aint s of your own applicat ion t o findmore ways t o apply t hese pr inciples and improve t he per for mance of yourcod e.See also G1, 147; G1, 166; G2, 57; G2, 84.GRAPHICS GEMS III Edit ed by DAVID KIRK 2 0I.4 A SIMPLE COLOR REDUCTION FILTERI. 4 I. 4 I. 4 I. 4 I. 4A SIMPLE COLOR REDUCTION A SIMPLE COLOR REDUCTION A SIMPLE COLOR REDUCTION A SIMPLE COLOR REDUCTION A SIMPLE COLOR REDUCTIONFILTER FILTER FILTER FILTER FILTERDennis BraggGraphics Sof t ware Inc.Bullard, TexasInt r oduct i on Int r oduct i on Int r oduct i on Int r oduct i on Int r oduct i onA simple filt er is present ed t hat red uces a 24-bit color r ast er image t o 15significant bit s and eliminat es t he problem of visible color st epping. Theresult ing image can be d isplayed d ir ect ly on a 16-bit fr ame buffer or usedas t he input t o a color quant izat ion met hod for fur t her red uct ion in t henumber of color s in t he image.Rast er images are oft en st ored as an ar r ay of 24-bit pixels wit h 8 bit sallocat ed t o each r ed , gr een, or blu e (RGB) comp onent . Each RGBcomponent hold s one of 256 possible int ensit y levels. Plat e 1 (see colorinser t ) is a 24-bit image t hat uses 2215 d ifferent color s. Not e t he smoot hcont inuous shad ing of t he colored balls.Unfor t unat ely, fr ame buffer s t hat can d isplay 24-bit color images arenot always read ily available. Color d isp lays t hat u se 8-bit p ixels asind exes t o a 256-color color map are wid ely used . A color quant izat ionmet hod (Ger vaut z and Purgat hofer, 1990) is oft en employed t o red ucet he number of color s used in a 24-bit image so it can be accur at elyd isplayed on an 8-bit d evice.Fr ame buffer s t hat can d isplay 16 bit s of color per pixel (five bit s perRGB component plus an at t r ibut e bit ) are also becoming more afford able.The t ypical solut ion for d isplaying a 24-bit image on a 16-bit fr ame bufferis t o mask off t he t hree least significant bit s of each RGB component Thismet hod red uces t he 256 int ensit y levels available for each color t o only32 levels.A problem t hat occur s in color-red ucing smoot h shad ed images is colorst epping. A region whose int ensit y var ies cont inuously from d ar k t o lightin t he or iginal 24-bit image will oft en exhibit not iceable int ensit y levelst eps when d isplayed on a 16- or 8-bit fr ame buffer. In Plat e 2 (see colorGRAPHICS GEMS III Edit ed by DAVID KIRK 2 1I.4 A SIMPLE COLOR REDUCTION FILTERinser t ) t he image of Plat e 1 has been red uced t o 256 color s using t hecolor quant izat ion met hod of Ger vaut z and Purgat hofer. Not e t he colorst epping on t he balls d ue t o t he limit ed number of color s available.This gem solves t he color st epping problem by var ying t he int ensit ylevel of each pixels RGB component s by a weight ed r and om amount . Theamount of var iance is weight ed in such a way t hat t he aver age of anylocal region of pixels in t he result ing image is ver y close t o t he act ual24-bit color of t he source image.The result ing image cont ains 15 significant bit s of color per pixel, fivebit s for each RGB component . The image can be d isplayed d irect ly on a16-bit fr ame buffer or used as t he input for a color quant izat ion met hodt o fu r t her r ed u ce t he nu mber of color s. The r esu lt ing image has asomewhat gr ainy ap p ear ance, bu t is mu ch less object ionable t hanvisible color st epping.The Fi l t er The Fi l t er The Fi l t er The Fi l t er The Fi l t erThe filt er consid er s each pixels RGB component separ at ely. The 256int ensit y levels of a component are d ivid ed int o 32 equal regions. Eachregion cover s eight int ensit y levels. The fir st region has an int ensit y levelof zero, t he next region has an int ensit y of eight , and so on.The int ensit y of t he RGB component will be set t o one of t hese regions.If t he component is set t o t he nearest int ensit y level, t he result ing imagewould st ill exhibit color st epping. Inst ead , t he remaind er of t he int ensit yd ivid ed by 8 (or mod ulus) is d et er mined . This gives a number r angingfrom 0 t o 7. A r and om number in t he r ange of 0 t o 8 is gener at ed andcompared t o t he remaind er. If t he remaind er is less t han or equal t o t her and om number, t he component int ensit y is increased by 8. This has t heeffect of var ying t he component in a manner t hat is r and om, yet weight edt oward t he nearest int ensit y level.Next , some r and om noise is ad d ed t o t he component int ensit y based ona user-supplied noise level. The ad d it ion of t he noise eliminat es anyremnant s of color st epping t hat might ot her wise be not iceable. Finally,t he lower t hree bit s of t he component are masked off, red u cing t henumber of significant bit s per pixel t o 15.The process prod uces RGB component s t hat are significant ly d ifferentfrom t he or iginal 24-bit component s. However, t he aver age int ensit y oft he pixel component s in any local area of t he image is ver y close t o t heGRAPHICS GEMS III Edit ed by DAVID KIRK 2 2I.4 A SIMPLE COLOR REDUCTION FILTERaver age int ensit y of t he or iginal image. In Plat e 3 (see color inser t ), t heor iginal 24-bit image was fir st processed by t he filt er, t hen red uced t oeight bit s per pixel by t he same met hod used in Fig. 2.Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i on Impl ement at i onThe filt er is implement ed wit h t he funct ion rgbvar y(). The funct ion re-quires four argument s: a t hree-char act er ar r ay of RGB component s of t hepixel t o be processed (rgb), an int eger specifying t he d esired noise level(noise_level), and t he x and y locat ion of t he pixel (x and y).The funct ion ret ur ns t he mod ified RGB component s in t he source rgbar r ay. The noise level can var y from zero (no noise) t o 8 (loud !). A noiselevel of 2 has wor ked well in pr act ice.The x and y locat ion of t he pixel is used by t wo macros (jit t er x andjit t er y) which gener at e t he r and om number s. The jit t er macros are basedon t he jit t er funct ion found in GRAPHICS GEMS (Cychosz, 1990). Thead vant age of using jit t er is t hat it always var ies a pixel at a par t icular x, ylocat ion by t he same magnit ud e. This is impor t ant when one is color-red ucing sever al fr ames of an animat ion. Using a st and ar d r and om num-ber gener at or will cause a snowy effect as t he animat ion is played . Thejit t er funct ion eliminat es t his problem.The funct ion jit t er _init () must be called before any calls t o rgbvar y() t oinit ialize t he look-up t ables used by t he jit t er macros. This proced ure usest he st and ard C funct ion r and () t o fill out t he t ables.Summar y Summar y Summar y Summar y Summar yA filt er is present ed t o red uce a 24-bit image int o 15 significant bit s perpixel. The proced ure eliminat es t he problem of color st epping at t heexpense of a slight ly gr ainy appear ance. The result ing image can bed isplayed d irect ly on 16-bit fr ame buffer s or used as input t o a colorquant izat ion met hod for fur t her color red uct ion.See also G1, 233; G1, 287; G1, 448; G2, 126.1.4 Plate 1. Original 24-bit color image. 1.4 Plate 2. 256 color image after standardcolor quantization.1.4 Plate 3. 256 color image after process-ing with rgbvary() and standard color quan-tization.GRAPHICS GEMS III Edit ed by DAVID KIRK 2 3I.5 COMPACT ISOCONTOURS FROM SAMPLED DATAI. 5 I. 5 I. 5 I. 5 I. 5COMPACT ISOCONTOURS COMPACT ISOCONTOURS COMPACT ISOCONTOURS COMPACT ISOCONTOURS COMPACT ISOCONTOURSFROM SAMPLED DATA FROM SAMPLED DATA FROM SAMPLED DATA FROM SAMPLED DATA FROM SAMPLED DATADoug Moore and Joe Warren Rice Universit yHoust on, TexasPr obl em Pr obl em Pr obl em Pr obl em Pr obl emDat a in many field s, includ ing med ical imaging, seismology and met eorol-ogy, ar r ive as a set of measurement s t aken over t he ver t ices of a largecubic gr id . Techniques for prod ucing a visual represent at ion from a cubeof d at a are impor t ant in t hese field s. Many common visualizat ion t ech-niques t reat t he d at a values as sample funct ion values of a cont inuousfunct ion F, and gener at e, for some c, a piecewise planar approximat iont o F(x, y, z) = c, an isocont our of t he funct ion. One of t he or iginalGraphics Gems, Defining Sur faces from Sampled Dat a, sur veys sever alof t he best -known t echniques for gener at ing isocont our s from a d at a cube(Hall, 1990).In t his gem, we present an enhancement t o all t echniques of t hat t ype.The enhancement red uces t he nu mber of element s of any isocont ou rapproximat ion and improves t he shape of t he element s as well. The fir stimprovement t ypically red uces t he size of a represent at ion by about 50%,per mit t ing fast er red isplay and red ucing memor y requirement s. The sec-ond result s in bet t er-qualit y pict ures by avoid ing t he nar row element s t hatcause und esir able shad ing ar t ifact s in many light ing mod els.Cube- Based Cont our i ng Cube- Based Cont our i ng Cube- Based Cont our i ng Cube- Based Cont our i ng Cube- Based Cont our i ngSever al au t hor s have su ggest ed rou ghly similar met hod s t hat creat eisocont ou r s for visu alizat ion fr om a cu bic d at a gr id . These met hod sprocess t he d at a separ at ely on each cube, and use linear int er polat ionGRAPHICS GEMS III Edit ed by DAVID KIRK 2 4I.5 COMPACT ISOCONTOURS FROM SAMPLED DATAalong t he ed ges of a cube t o comput e a collect ion of point s lying on t heisocont ou r. In t he Marching Cu bes algor it hm of Lor enson and Cline(Lorenson and Cline, 1987), t hese int er sect ions are connect ed t o for med ges and t r iangles using a t able lookup based on t he signs of t he valuesF(x, y, z) c at t he ver t ices of t he d efining cube.Unfor t unat ely, t hat met hod d oes not guar ant ee a cont inuous cont our,since ad jacent cubes t hat share a face wit h mixed signs may be d ivid edd ifferent ly (Dur st , 1988). Ot her s have suggest ed an alt er nat ive met hodt hat d isambiguat es t hat case by sampling t he funct ion at t he cent er of t heambiguous face (Wyvil et al., 1986). We call met hod s like t hese, t hatcomput e t he ver t ices of t he result ing cont our using linear int er polat ionalong ed ges of t he cubic mesh, edge-based int erpolat ion met hod s.Anot her problem wit h ed ge-based int er polat ion met hod s is t hat t hesur face meshes t hey prod uce can be highly ir regular, even for simplet r ivar iat e d at a. These ir regular it ies consist of t iny t r iangles, prod ucedwhen t he cont our passes near a ver t ex of t he cubic mesh, and nar rowt r iangles, prod uced when t he cont our passes near an ed ge of t he mesh. Inour exper ience, such t r iangles can account for up t o 50% of t he t r ianglesin some sur face meshes. These bad ly shaped element s oft en d egr ad e t heper for mance of rend er ing algor it hms and finit e element analysis appliedt o t he mesh while cont r ibu t ing lit t le t o t he over all accu r acy of t heapproximat ion.Compact Cubes Compact Cubes Compact Cubes Compact Cubes Compact CubesThe cont r ibut ion of t his gem is a gener al t echnique for eliminat ing t heproblem of near ly d egener at e t r iangles from ed ge-based int er polat ion.The id ea behind t he t echnique is simple: When a ver t ex of t he mesh liesnear t he sur face, bend t he mesh a lit t le so t hat t he ver t ex lies on t hesur face. The small t r iangles collapse int o point s, t he nar row ones collapseint o ed ges, and only big, well-shaped t r iangles are left . The rest of t hegem out lines an implement at ion of t his id ea; a more d et ailed explanat ionis available (Moore and War ren, 1991).Apply any ed ge-based int er polat ion algor it hm t o t he d at a cube, and int he process, record for each ver t ex gener at ed along an ed ge of a cube t hepoint of t he cubic gr id nearer t hat ver t ex. We call t hat ver t ex a sat ellit eof it s nearest gr id point . If t he ver t ex lies at t he mid point of an ed ge,GRAPHICS GEMS III Edit ed by DAVID KIRK 2 5I.5 COMPACT ISOCONTOURS FROM SAMPLED DATAFigure 1. 2D case t able for Compact Cubes.Figure 2. A 2-D example of Compact Cubes.GRAPHICS GEMS III Edit ed by DAVID KIRK 2 6I.5 COMPACT ISOCONTOURS FROM SAMPLED DATAeit her end point of t he ed ge may be used , as long as all ot her cubesshar ing t he ed ge use t he same end point . When t his phase of t he algor it hmhas complet ed , you have a t r iangulat ion S of t he isocont our and a gr idpoint nearest each ver t ex of t he t r iangulat ion.To prod uce a new, smaller approximat ion t o t he isocont our, apply t hefollowing proced ure:f or each t r iangle T in S doi f t he ver t ices of T are sat ellit es of d ist inct gr id point sthen prod uce a t r iangle connect ing t he gr id point s;el se T collapses t o a ver t ex or ed ge so ignore it ;endl oop;f or each gr id point g of t he new t r iangulat ion dod isplace g t o t he aver age posit ion of it s sat ellit es;endl oop;The fir st st ep of t he met hod d efines t he t op ology of a new meshconnect ing point s of t he cubic gr id . All t he sat ellit es in S of a par t icularFigure 3. Two approximat ions t o a sphere.GRAPHICS GEMS III Edit ed by DAVID KIRK 2 7I.5 COMPACT ISOCONTOURS FROM SAMPLED DATAgr id point are coalesced int o a single ver t ex in t he result ing mesh. Thus,small t r iangles t hat result when a gr id point is chopped off ar e col-lapsed t o t he gr id point . Nar row t r iangles prod uced when t wo ver t ices arever y near t he same gr id point are collapsed t o make t he t r iangle an ed ge.Figure 1 illust r at es t his in t wo d imensions. This per spect ive shows t hat ift he or iginal sur face mesh is cont inuous, t hen t he mesh prod uced in t hefir st st ep of t he algor it hm must also be cont inuous.In t he second st ep, t he ver t ices of t he gr id d ed mesh are d isplaced t o lieon or near t he or iginal isocont our. Since each new ver t ex posit ion ischosen t o be at t he aver age posit ion of a small clust er of point s lying ont he or iginal cont our, t he new approximat ion usually d iver ges only slight lyfrom t he or iginal cont our.Figure 2 illust r at es t his met hod applied t o a t wo-d imensional mesh. Theupper por t ion illust r at es t he result of t he fir st st ep. The lower por t ionillust r at es t he out put of t he second st ep. The shor t ed ges in t he upperFigur e 4. Two approximat ions t o t he head of a femur.GRAPHICS GEMS III Edit ed by DAVID KIRK 2 8I.5 COMPACT ISOCONTOURS FROM SAMPLED DATApor t ion of t he figure have been collapsed t o for m ver t ices in t he lowerpor t ion.In p r act ice, t he met hod wor ks qu it e well, red u cing t he nu mber oft r iangles by 40% t o 60%. Figure 3 shows a sphere gener at ed by MarchingCubes (A) and t he same sphere aft er t he applicat ion of Compact Cubes(B). Figure 4 shows a human femur, or iginally present ed as CT d at a, ascont oured by Marching Cubes (A) and by Compact Cubes (B). In eachexample, t he number of t r iangles is red uced by using Compact Cubes,and t he shape of t he remaining t r iangles is measur ably improved .As d escr ibed here, t he cont our s prod uced by Compact Cubes may havesever al und esir able feat ures. Fir st , t he bound ar y of t he final cont our maynot lie on t he bound ar y of t he d efining cubic mesh. Second , t wo d isjointsheet s of t he cont our passing near a common gr id point may be fused att hat gr id point . Moore and War ren (1991) d escr ibe simple mod ificat ions t oCompact Cubes t hat solve each of t hese problems.See also G1, 552; G1, 558; G2, 202.2 9 GRAPHICS GEMS III Edit ed by DAVID KIRK 2 9I.6 GENERATING ISOVALUE CONTOURS FROM A PIXMAPI. 6 I. 6 I. 6 I. 6 I. 6GENERATING ISOVALUE GENERATING ISOVALUE GENERATING ISOVALUE GENERATING ISOVALUE GENERATING ISOVALUECONTOURS FROM A PIXMAP CONTOURS FROM A PIXMAP CONTOURS FROM A PIXMAP CONTOURS FROM A PIXMAP CONTOURS FROM A PIXMAPTim FeldmanIsland Graphics Corporat ionSan Raf ael, Calif orniaThis gem present s an algor it hm t hat follows t he ed ge of a cont our in anar r ay of sampled d at a. It uses Freeman chain encod ing t o prod uce a listof vect or s t hat d escr ibes t he out line of t he cont our.Say t hat you have a t er r ain map t hat has been sampled or d igit ized int o a rect angular ar r ay of gr ay-scale pixels. Different pixel values cor re-spond t o d ifferent t er r ain elevat ions. This algor it hm could be used inprod ucing a t opogr aphic map t hat showed t he t er r ain elevat ions ascont our lines. An example progr am (cont our.c) t hat follows one cont ouris given in t he Append ix.The algor it hm is cap able of hand ling cont ou r s cont aining a singlesamp le p oint , cont ou r s su r rou nd ing r egions of a d iffer ent elevat ion,cont our s t hat d o not for m closed cur ves, and cont our s t hat for m cur vest hat cross t hemselves, for ming loops. In all cases, it follows t he out er mosted ge of t he cont our. Given an init ial point in an elevat ion cont our in t hear r ay, t he algor it hm find s t he ed ge of t he cont our. Then it follows t heed ge in a clockwise d irect ion unt il it ret ur ns t o it s st ar t ing point . Alongt he way, it d escr ibes t he pat h t hat it follows, using d irect ion vect or s.Each d irect ion vect or d escr ibes t he d irect ion from a pixel on t he pat h t ot he next pixel on t he pat h. All of t he pixels on t he pat h are immed iat eneighbor s. Thus, t he vect or s may be t hought of as t he d irect ion par t of at r ad it ional t wo-d imensional vect or, wit h t he lengt h par t always equal t oone pixel. A list of such vect or s is known as a Freeman chain, aft erHer ber t Fr eeman, it s or iginat or (Freeman, 1961). Figu r e 1 shows t hevalues d efining t he eight possible d irect ions from a pixel on t he pat h t oit s neighbor s. The pixel ar r ay used in t his example is in Fig. 2a; Fig. 2bshows t he out put of t he example progr am. The algor it hm found and3 0 GRAPHICS GEMS III Edit ed by DAVID KIRK 3 0I.6 GENERATING ISOVALUE CONTOURS