between the centre of the circle and the middle of pixels S and T . Whichever .... Data Structures and. Drawing. 5.1 Int
Computer Graphics via Java Ian Ferguson
Ab-libris the e-book people
British Library Cataloguing in Publication Data Ferguson, Robert Ian Computer Graphics via Java (Ab-libris computing classics series) 1. Computer Graphics I. Title II. Ferguson, Robert Ian, 1966ISBN: 1-903561-08-6 Typeset in Durham by Ab-Libris Ltd.
Copyright notice
Copyright 2002 by Ab-libris Ltd. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of Ab-Libris Ltd., PO Box 287, Durham, DH1 5YZ, UK
Dedication
To Jackie and Andrew
Our little systems have their day; They have their day and cease to be; They are but broken lights of Thee, And Thou, O Lord, art more than they. From: In Memoriam A.H.H. - OBIIT MDCCCXXXIII. By Alfred, Lord Tennyson
Foreword
This book is based upon an undergraduate class on Computer Graphics (52.359) taught at the University of Strathclyde. The author would like to thank past students for their comments on the material, without which, this book would never have taken shape. At first sight, a book on CG with Java is a bit of an odd beast; Java after all is not renowned for its speed of execution and if there is one application area which demands high speeds, it is CG and games. Given that the majority of Computer Science courses are now taught using Java, it does however make sense from a pedagogical point of view to continue using a familiar language when studying an unfamiliar application area. Much material, including demonstration animated applets, further examples and answers to (some) of the exercises in the book can be found on the website dedicated to the 52.359 class. The page can be found at: http://www.cs.strath.ac.uk/~if/classes/52.359 I hope you derive as much fun from the material contained in the book as I did when I first encountered CG.
Ian Ferguson Jan. 2002
Contents Chapter 1 Chapter 2
What is “Computer Graphics”?
12
1.1
12
Concepts, Terms and Definitions
24
2.1 2.2
Introduction Low level concepts 2.2.1 Memory Mapping 2.2.2 Resolution 2.2.3 Screen size 2.2.4 Coordinates 2.2.5 The origin 2.2.6 Colour 2.2.7 Image files 2D Drawing 2.3.1 Points 2.3.2 Lines 2.3.3 Shapes
24 25 26 28 28 29 30 30 32 33 33 35 35
A first graphics program
38
3.1 3.2 3.3 3.4
38 40 43 44
2.3
Chapter 3
Chapter 4
Introduction
Introduction The features of a simple graphics program Organising your work for Java Graphics Primitives
Graphics Primitives
53
4.1 4.2
53 53 54 58 60 62 63 63 65 67 69
4.3
Introduction Drawing straight lines 4.2.1 Brute force 4.2.2 Bresenham’s algorithm 4.2.3 An implementation of the line drawing algorithms Circles 4.3.1 Brute force 4.3.2 Cheating with 8 arcs 4.3.3 Digital Differential Analysis - An incremental algorithm 4.3.4 Bresenham’s algorithm for circles 4.3.5 An implementation of the circle drawing algorithms
Chapter 5
Data Structures and Drawing
75
5.1 5.2
75 75 76 77 81 82 85 85 86 87 88 89 91 92 92 92
5.3
5.4 5.5 5.6
Chapter 6
Chapter 7
Introduction The basic 2d data structure 5.2.1 Point2d class 5.2.2 Line2d Class 5.2.3 Shape2d class 5.2.4 Drawing2d class Adding methods 5.3.1 Point2d class 5.3.2 Line2d Class 5.3.3 Shape2d class 5.3.4 Drawing2d class 5.3.5 Adding these classes to the simple drawing application The completed system The Dry Run Further methods 5.6.1 Drawing vs erasing
2d Transformations
95
6.1 6.2
95 95 95 96 98 101 103 104 105 108
Introduction Transformations the simple way 6.2.1 What is a transformation? 6.2.2 Translation 6.2.3 Rotation - (about the origin) 6.2.4 Scaling 6.2.5 Identity transformations 6.2.6 Order of transformations 6.2.7 Rotation around local origin 6.2.8 Other transformations - general cases/ special cases.
Transformations as matrices
111
7.1 7.2
111 111 111 112 112 112 113 113 113 113 116 118 118
7.3 7.4
Introduction The Transformations 7.2.1 Rotation 7.2.2 Scaling 7.2.3 Translation 7.2.4 Homogenous coordinates 7.2.5 Homogenous rotation 7.2.6 Homogenous scaling 7.2.7 Homogenous translation Implementing Matrices Using the matrix class 7.4.1 Simple transformation using a matrix 7.4.2 Combination of transformations using matrices
Chapter 8
Simple Animation and Interaction
122
8.1 8.2
122 123 123 124 125 126 127 130
8.3 8.4
Chapter 9
Introduction Changing the drawing in response to user interaction 8.2.1 Drawing/erasing 8.2.2 Getting keystrokes/mouse-events 8.2.3 Double Buffering 8.2.4 The hopping frog example Continuous animation Animation changes in response to user interaction
Curves
134
9.1 9.2 9.3
134 136 137 138 141 143 143 144 146 150 150
9.4 9.5 9.6
Introduction Parametric Equations Splines 9.3.1 Representing Spline curves 9.3.2 Implementing Splines 9.3.3 Disadvantages of splines Bezier Curves 9.4.1 Representing Bezier curves 9.4.2 Implementing Bezier curves Other Curves The co-existence of multiple kinds of line
Chapter 10 3D graphics 10.1 Introduction 10.2 The 3D coordinate system 10.3 Implementing 3d - the basic 3d class structure 10.3.1 Points 10.3.2 3d Transformations 10.4 Projections - Viewing 3d on a flat screen 10.4.1 Projection - some definitions 10.4.2 Parallel projection. 10.4.3 Perspective projection 10.4.4 Oblique Parallel projections 10.4.5 Isometric Projection 10.5 Viewpoint Transformation 10.6 Implementing 3d - the data model 10.6.1 The Matrix Class 10.6.2 Point3d 10.6.3 Gitem3d 10.6.4 Line3d 10.6.5 Bezier3d 10.6.6 Transformation3d 10.7 Implementing 3d - Drawing, Projections and Viewpoints 10.7.1 Setting up the drawing transformation 10.7.2 Concatenating the transformations
154 154 154 155 155 156 161 162 163 164 165 169 170 173 175 175 176 176 176 177 179 180 180
10.7.3 Sharing the drawing transformation 10.7.4 Using the drawing transformation 10.7.5 Changing the drawing transformation
Chapter 11 Improving visual realism 11.1 Introduction 11.2 Hidden line removal 11.2.1 Determining visibility 11.2.2 Calculating the normal vector of a surface 11.2.3 An alternative approach 11.3 Implementing hidden line removal 11.4 More complex shapes 11.4.1 The Painter’s algorithm
Chapter 12 Rendering, Shading and Colour 12.1 Introduction 12.2 Illumination 12.2.1 Simplifying assumptions 12.2.2 Components of illumination 12.2.3 Diffuse illumination 12.2.4 Diffuse scattering from a point source 12.2.5 Specular reflection 12.2.6 Combining the illumination 12.2.7 Calculating E 12.2.8 Implementing illumination 12.2.9 Extending to colour 12.3 Approximating smooth surfaces with polygon nets. 12.4 Gouraud shading 12.5 Phong Shading 12.5.1 Comparison of Gouraud and Phong
Chapter 13 Fine detail - Texture Mapping and Bump Mapping 13.1 Introduction 13.2 Texture mapping 13.2.1 Modulating the colour of the surface 13.2.2 Mapping pictures onto surfaces 13.3 Tilling 13.4 Bump mapping 13.5 Some examples of texture and bump mapping
Chapter 14 Ray Tracing 14.1 Introduction 14.2 Follow a ray 14.2.1 The Ray Tree 14.3 Types of ray
181 181 184
189 189 190 193 195 198 198 203 203
210 210 211 212 213 214 215 216 218 219 221 225 226 227 231 231
235 235 237 237 238 240 240 242
245 245 246 247 247
14.3.1 Normal Rays 14.3.2 Illumination Rays 14.3.3 Diffuse Rays 14.3.4 Computing the brightness 14.3.5 Reducing Computation 14.4 Determining Intersections 14.4.1 Outline 14.4.2 Find the equation representing the light ray 14.4.3 Intersection of straight line with a plane 14.4.4 Determining where a straight line intersects a plane 14.4.5 Determining whether that point is with a given polygon 14.4.6 Applying to ray tracing
Chapter 15 Fractals 15.1 Introduction 15.2 Self similarity 15.2.1 The Koch Curve 15.2.2 The Sierpinski Gasket 15.3 The Mandelbrot Set 15.4 Utilising fractal geometry 15.4.1 Mountains 15.4.2 Trees etc. 15.5 Fractals and 3D
Chapter 16 Closing Remarks
247 248 248 248 248 248 249 250 251 251 251 253
256 256 256 257 259 262 266 266 268 271
274
12
What is “Computer Graphics”?
Chapter 1 What is “Computer Graphics”?
1.1
Introduction The field of study known simply as “Computer Graphics” is vast. It encompasses just about everything that is seen on a computer screen that isn’t a word or a number and on modern, window-based operating systems, even they will appear on screen using techniques from graphics. Table 1 - “Diversity in Computer Graphics” shows just some of thing things that could be studied under the heading of computer graphics. Software/ Hardware
Topic
Keywords
Pictures
digital drawings, digital photographs, gifs, bitmaps, jpegs, drawing tools, multimedia, digital cameras, image compression
Adobe Illustrator, Macromedia Freehand
Line drawings, Computer Aided Design (CAD), schematics, graphs, business/ presentation graphics
AutoCAD
Diagrams
Table 1. Diversity in Computer Graphics
Examples Figure 1 - “Digital photographs”
Adobe Photoshop, Paintshop Pro
MS Powerpoint
Figure 2 - “Line drawings and schematics”
13
What is “Computer Graphics”?
Software/ Hardware
Topic
Keywords
Video
.mov. avi, Quicktime, DV (digital video), video cameras
Adobe Premier
Figure 3 - “Digital Video”
Graphical User
Windows, icons, menu, pointers - (WIMPS)
Windows, Xwindows, Mac
Figure 4 - “Graphical User Interfaces”
3D Modelling
coordinate systems, transformations, clipping wireframe drawings, shading, hidden line removal, projections, rendering, ray tracing
Autocad AC3D, POV, Renderman, Alias Sketch, Lightwave
Figure 5 - “3D Modelling - Images courtesy of Autodesk(top) and BBC (bottom)”
Virtual Reality
Real-time 3D modelling, interaction, immersive/nonimmersive VR
Virtual Reality Markup Language (VRML).
Figure 6 - “Virtual Reality - (image courtesy of the Irish Tourist Board)”
Animation
Frames, tweening, frame rates
Macromedia Director
Figure 7 - “Animation - a frame from Highnoon - an animated 3D “cartoon” - Image courtesy of Michael G. Turner)”
Image Processing
filters, image enhancement, medical imaging, astronomy, maximum entropy techniques,
Khorus
Figure 8 - “Image Processing- a “raw” and processed brain scan”
Image Analysis
Edge detection, histogramming,
Khorus
Figure 9 - “Image Analysis - street scene and edgedetection”
Image Comprehension
image recognition, pattern recognition, face recognition, neural networks
(still experimental)
Graphics Hardware
display devices, VDUs, LCDs, plasma screens, TFT, goggles, VR headsets, Projection systems, interaction devices (mouse, bat, light pen, digitising pad, graphics tablets, pantograph)
Interfaces (GUIs)
Examples
Table 1. Diversity in Computer Graphics The following figures (1-9) show some examples of the various things that pass as “Computer Graphics.”
What is “Computer Graphics”?
Figure 1. Digital photographs
14
15
What is “Computer Graphics”?
library
book
author
Figure 2. Line drawings and schematics
What is “Computer Graphics”?
Figure 3. Digital Video
16
What is “Computer Graphics”?
Figure 4. Graphical User Interfaces
17
What is “Computer Graphics”?
Figure 5. 3D Modelling - Images courtesy of Autodesk1(top) and BBC2 (bottom)
1. www.autodesk.com 2. www.bbc.co.uk
18
What is “Computer Graphics”?
19
The same techniques that let architectural clients see a building that hasn’t even been built yet allow the creation of the “impossible” such as this extinct creature from the BBC series “Walking with Beasts”
Figure 6. Virtual Reality - (image courtesy of the Irish Tourist Board1)
1. www.ireland.travel.ie
What is “Computer Graphics”?
20
Figure 7. Animation - a frame from Highnoon - an animated 3D “cartoon” Image courtesy of Michael G. Turner)
Figure 8. Image Processing- a “raw” and processed brain scan
What is “Computer Graphics”?
21
Figure 9. Image Analysis - street scene and edge-detection This book concentrates on the terms and techniques that underlie the topics of diagrams, 3d-modelling, virtual reality and animation.
What is “Computer Graphics”?
22
Chapter review - 1 There’s not a great deal to summarise so far but you seen examples of the great variety of topics that make up the study of computer graphics
What is “Computer Graphics”?
23
Exercises - 1 1.1
Surf the WWW. Find examples of the different type of computer graphics applications mentioned in Chapter 1
1.2
Look at: •www.cs.strath.ac.uk/~if/classes/52359 •www.streetmap.co.uk •www.sat.dundee.ac.uk/ •www.wunderground.com/sky/ShowSky.asp?The-
Lat=52.200001&TheLon=0.180000&TimeZoneName=Europe/ London •javaboutique.webdeveloper.com/Mandelbrot/ •www.vrml.org •cgw.pennnet.com/home.cfm - the gallery section is particularly
well worth seeing. •www.computer.org/cga/
Concepts, Terms and Definitions
24
Chapter 2 Concepts, Terms and Definitions
2.1
Introduction Before examining to different specialisms that make up computer graphics, this chapter provides a quick review of the basic terms and definitions that are common to most areas of computer graphics.
Concepts, Terms and Definitions
2.2
25
Low level concepts All of computer graphics is based upon the properties of the screen or display device (more about this in Chapter ##). The fundamental thing that you need to know about displays is that they are divided into lots of small squares called pixels (“PICture ELements”).
Figure 10. Pixels
Concepts, Terms and Definitions
26
The simplest way to think of how this works is to stick to black and white. Each pixel can be set to black or white (i.e. turned on or off). This allows patterns of dots to be created on the screen.
Figure 11. Smiley pixels 2.2.1
Memory Mapping Drawing on the screen is therefore simply a matter of setting the right pixels either on or off. Each pixel on the screen corresponds to an address in the computers memory - this is known as memory mapping and the display is said to be a “memory mapped display.” Effectively, each pixel is numbered sequentially.
27
Concepts, Terms and Definitions
Memory 0
off
1
off
2
off
42
off
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
42
off
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
44
ON
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
45
ON
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
46
off
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
47
off
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
48
off
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
49
ON
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
50
ON
260 261 262 263 264 265 266 267 268 269 720 271 272 273 274 275 276 277 278 279
51
off
Screen 0
1
2
3
4
5
6
7
8
9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
280 281 282 283 284 285 286 297 288 289 290 291 292 293 294 295 296 297 298 299
296 off 297 off 298 off 299 off
Figure 12. Memory mapping By writing values to the correct locations in memory (this used to be called “poking the address”) the appearance of the screen can be controlled by a programmer. Conversely, by inspecting the contents of a memory location (“peeking”), a program can find out if a pixel is turned on or off. Aside
The portion of memory that is associated with the display is known as the “video memory”. In the PC architecture, this memory is usually physically located on the graphics card, which is why you can buy 8Mb graphics cards, 16Mb graphics cards etc.
Concepts, Terms and Definitions
2.2.2
28
Resolution The screen in this example is composed of 300 pixels arranged in 15 rows of 20. It is said to have a resolution of “20 by 15” (20 x 15). This is actually very small by today’s standards. Typically a display will have a resolution of 1024x768 maybe even more.
2.2.3
Screen size Resolution is NOT the same thing as screen size. Our 20x15 display could have been 5cm across (as a mobile phone display), 40cm across (as a monitor) or 20m (as a projection system) but the resolution would always be 20x15.
Figure 13. Screen size is different to resolution
29
Concepts, Terms and Definitions
2.2.4
Coordinates Whilst the computer “thinks” of its display as a simple list of addresses, it is much more convenient (for reasons which will become clear later) for us to think in terms of coordinates and leave it to the computer to convert the coordinates to memory location itself. X 0
1
2
3
4
5
6
7
8
9 10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 Y
5 6 7 8 9 10 11 12 13 14
Xsize = 20 (columns) Ysize = 15 (rows)
Figure 14. Coordinates Each pixel can be referred to by a pair of numbers known as its coordinates - an x coordinate (which gives the column’s number and a y coordinate which gives the row number. The coordinates are always written as a pair of numbers, separated by a comma and enclosed in brackets. This system of geometry is known as “Cartesian geometry” and the coordinates are spoken of as being “Cartesian Coordinates.”
Example 1. Simple coordinate example
In Figure 14 - “Coordinates” - pixel (7,12) is set ON. Aside
The computer converts coordinates to memory addresses by subtracting the y coordinate from the number of rows on the display minus 1 (i.e. Ysize -1, this effectively turns the y axis upside-down to make sure that the origin is at the bottom), multiplying that by the number of columns on the display
30
Concepts, Terms and Definitions
(Xsize), and adding the x coordinate. location = (((Ysize - y)* Xsize) + x).
(Equation 1)
(7,12) becomes (((14-12)*20) + 7) = 47 2.2.5
The origin In this example, the origin or (0,0) is in the bottom-left of the screen. It is also possible to have the origin in the top-left, in which case the rows (y coordinates) are numbered downwards
2.2.6
Colour In discussion so far, we have been restricted to black and white (monochrome) i.e. each pixel can only be on or off. Colour can be represented in most of today’s computers. Typically, instead of each pixel being represented by one bit (on or off) each pixel will be represented by 24 bits - 3 x 8 bit bytes. Each byte represents a number between 0 and 255 and each byte is associated with one primary colour - red, blue, green. red 0000 0000
green
blue
0000 0000
1111 1111
binary
0
0
255
decimal
00
00
FF
hex
1100 0000
1100 0000
0000 0000
binary
192
192
0
decimal
C0
C0
00
hex
Figure 15. 24 bit colour representation
31
Concepts, Terms and Definitions
Memory 0
FF FF FF
1
FF FF FF
2
FF FF FF
42
FF FF FF
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
42
FF FF FF
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
44
FF 00 00
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
45
FF 00 00
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
46
FF FF FF
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
47
FF FF FF
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
48
FF FF FF
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
49
FF 00 00
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
50
FF 00 00
260 261 262 263 264 265 266 267 268 269 720 271 272 273 274 275 276 277 278 279
51
FF FF FF
Screen 0
1
2
3
4
5
6
7
8
9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
280 281 282 283 284 285 286 297 288 289 290 291 292 293 294 295 296 297 298 299
296 FF FF FF 297 FF FF FF 298 FF FF FF 299 FF FF FF
Figure 16. Colour smiley
Concepts, Terms and Definitions
2.2.7
32
Image files From Figure 16 - “Colour smiley” it is hopefully only a small step to see how Figure 17 - “smiley.bmp” works. The pattern of bits in the computer’s memory forms what is know as a bitmap. 7 9
44 45 46 47 48 49 50
FF 00 00 FF 00 00 FF FF FF FF FF FF FF FF FF FF 00 00 FF 00 00
64 65 66 67 68 69 70
FF 00 00 FF 00 00 FF FF FF FF FF FF FF FF FF FF 00 00 FF 00 00
84 85 86 87 88 89 90
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
104 105 106 107 108 109 110
FF FF FF FF FF FF FF FF FF 00 FF 00 FF FF FF FF FF FF FF FF FF
124 125 126 127 128 129 130
FF FF FF FF FF FF FF FF FF 00 FF 00 FF FF FF FF FF FF FF FF FF
144 145 146 147 148 149 150
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
164 165 166 167 168 169 170
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
184 185 186 187 188 189 190
FF FF FF 00 00 FF FF FF FF FF FF FF FF FF FF 00 00 00 FF FF FF
204 205 206 207 208 209 210
FF FF FF FF FF FF 00 00 FF 00 00 FF 00 00 FF FF FF FF FF FF FF
Figure 17. smiley.bmp By simply writing those values out to a data file and prepending information about the height and depth of the image, a picture can be saved onto disk and this is indeed the approach taken by all the common graphical formats seen on the WWW such as.gifs,.jpegs, etc.
Concepts, Terms and Definitions
33
It is then an even smaller step (increase the number of pixels (i.e the resolution)) to see how Figure 18 - “Carol Smiley” works.
Figure 18. Carol Smiley 1
2.3
2D Drawing Leaving image processing behind for now, we can concentrate on the basic terminology associated with drawing on a computer screen. In two dimensions (2D), drawing are made up of points, lines and shapes.
2.3.1
Points Representing a point on a 2d drawing to a computer is simple. In fact you’ve already seen it, we just use coordinates.
1.
- Image courtesy of the BBC - www.bbc.co.uk
34
Concepts, Terms and Definitions
12
7 14
Y
13 12 11 10 9 8 7 6 5 4 3 2 1 0 0
1
2
3
4
5
6
7
8
9 10 11 12 13 14 15 16 17 18 19 X
Figure 19. Using coordinates to represent points Aside
It is worth noting at this stage two important points about the difference between coordinates that you will have come across in a maths course and those used by computers: 1. At the lowest level, a computer only understand integers as coordinates. If you want to plot a point at (5.673,48.32795) you will need some scheme for converting it sensibly into an integer value. 2. In maths, a point has no size, it is infinitesimally small. To a computer, a point is the size of a pixel.
35
Concepts, Terms and Definitions
2.3.2
Lines A (straight) line can be mathematically defined by its end points. To describe the line in figure X we need simply to state the coordinates of the two ends: (3,8),(12,2)
8
2
3
12
Figure 20. Defining a line using the start and end points (3,8),(12,2) Aside
Another difference between raw maths and computer graphics, a line has no thickness, in computer graphics, it does. 2.3.3
Shapes At this stage all you need to know is that shapes are made up of collections of lines.
Concepts, Terms and Definitions
36
Chapter review - 2 So far, you should have learned about: •screens being divided into pixels, resolution and size •memory mapping - whereby each pixel has a corresponding
address in video memory which can be set or read to set or interrogate the colour of the pixel •the 24 bit colour representation scheme •the concept of ‘bitmaps’ whereby patterns in memory can represent the appearance of the screen •a simple image file format •the representation of point and lines by means of cartesian coordi-
nates
Concepts, Terms and Definitions
37
Exercises - 2 2.1
Find out the size, resolution and colour depth of the display you are using.
2.2
Describe the difference between size and resolution
2.3
What steps must a computer take to plot a point (22.25,10.4)?
38
A first graphics program
Chapter 3 A first graphics program
3.1
Introduction It is traditional, when learning to program, that you start with a “Hello World” program. In this chapter, we will look at the graphics equivalent of that textual tradition. The code for this is below in example 2.
Example 2. Apollo 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//-----------------------------------------------// // // File : Gapp.java // // //-----------------------------------------------import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class Gapp extends JFrame
{
public Gapp(){ setBackground(Color.white); }// constructor
public void initComponents() throws Exception { setLocation(new java.awt.Point(0, 30));
A first graphics program
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
1 2 3 4 5 6 7 8 9 10 11 12 13 14
39
setSize(new java.awt.Dimension(350, 400)); setTitle("Graphics Application"); getContentPane().add(new Gcanvas()); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { thisWindowClosing(e); } }); }//end - initComponents
void thisWindowClosing(java.awt.event.WindowEvent e){ // Close the window when the close box is clicked setVisible(false); dispose(); System.exit(0); }//end - thisWindowClosing
static public void main(String[] args) { // Main entry point try { Gapp myGapp = new Gapp(); myGapp.initComponents(); myGapp.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }//end main }//end of class -- Gapp -------------------------------------------
import java.awt.*; import javax.swing.*; //--------------------------------------------------------------// // // File : Gcanvas.java // // //---------------------------------------------------------------class Gcanvas extends JPanel { public void paintComponent(Graphics g){ g.drawLine(50,50,50,150); g.drawLine(50,150,100,100);
40
A first graphics program
15 16 17 18 19 20 21 22 23 24 25
g.drawLine(100,100,100,150); g.drawLine(100,150,200,150); g.drawLine(200,150,200,50); g.drawLine(200,50,100,50); g.drawLine(100,50,100,100); g.drawLine(100,100,50,50); g.drawLine(200,50,250,100); g.drawLine(250,100,200,150); }//paintComponent }//end of -- Gcanvas --------------------------------------------
Running this program should result in the output found in Figure 21
Figure 21. Apollo 13 in flight
3.2
The features of a simple graphics program You can’t have it both ways with a programming language, it can either be simple or powerful. Java most definitely falls in the powerful (consequently complex) category. In order to draw things on screen (which is what this is all about) you have to have quite a bit of Java “machinery” in place before you can start. Let’s look at this machinery first via the simplest Java graphics
41
A first graphics program
program I could write. This program (let’s call it Apollo13) consists of two Java classes - Gapp (graphics application) and Gcanvas. Figure 22 shows a UML diagram of the program.
JDK - swing JFrame
JPanel
application
ours Gapp initComponents thisWindowclosing
Gcanvas paintComponent
Figure 22. Design diagram for a simple graphics application Gapp and Gcanvas are ours - we’re developing them. JFrame and JPanel from which they inherit, are part of the Java Foundation Classes - in particular they are part of the “swing” GUI components.
42
A first graphics program
The class Gapp inherits from JFrame, so when a Gapp object is created, a new GUI window appears on the screen. A Gcanvas/JPanel is simply something we can draw on, but it isn’t allowed to be on screen by itself, it must be part of a JFrame. So what we actually need is an instance of Gapp with an instance of Gcanvas “inside” it (Figure 23). application
Figure 23. Gapp with a Gcanvas in it The main entry point for the system is in class Gapp (line 46) - the main function, simply creates a Gapp object (line 49), and calls its initComponents() method(50). initComponents() sets the window’s on-screen position and size (lines 22,23), sets up some Java apparatus to allow the program to shut down cleanly (lines 27-31) and creates an instance of a Gcanvas (graphics canvas) - line 25. This GCanvas object is “added” to the Gapp object and hence becomes part of that window. The actual interesting bit of this program occurs in method paintCompoin file Gcanvas.java (lines 12-23). Here we finally see how to draw lines in Java. When paintComponent() is called, it is passed a Graphics object (“g”) - line 12. We use a method called drawLine() which is a member of the Graphics class. The Graphics class is part of the standard Java class library and its member functions are termed “graphics primitives”. There exist a whole range of methods for drawing and colouring in a variety of shapes (boxes, polygons, ovals etc.) Take a look at the Java API documentation for full details.
nent()
The drawLine() method takes 4 parameters, x1, y1, x2, y2 which represent the start and end points of the line you wish to draw. “But......?” you may be asking, this program doesn’t actually seem to call the paintComponent() method and where does it get “g” the Graphics object from? You are right, it doesn’t. paintComponent() is what is known as a “callback” method. It’s actually called by the system every time the JPanel object it belongs to needs to be displayed on screen and likewise the system passes us the mysterious “g” to provide all of those useful functions - we don’t have to worry about it.
43
A first graphics program
So how is Apollo 13 actually drawn? The drawing is simply broken down into a series of lines. Each line has a start point and an end point. These points are expressed in terms of there coordinates and by cross referencing between Figure 24 and lines 13-22 of Gcanvas.java you can see how the drawing is built up. 0
50
(50,50)
100
150
(100,50)
250
200
x
(200,50)
50
(100,100)
100
150
(50,150)
(100,150)
(250,100)
(200,150)
y
Figure 24. The Coordinates of Apollo 13
3.3
Organising your work for Java Here are some hints and tips more minimising hassle while trying to get the examples and exercises working. •Make a directory somewhere called “graphics” •Do each example/exercise in a separate sub-directory of graphics. •make sure you have “.” on your classpath •UNIX
- setenv JAVA_HOME /usr/local/jdk1.3/bin - setenv CLASSPATH "$JAVA_HOME":. •WIN - set JAVA_HOME=C:\jdk1.3\bin - set CLASSPATH=%JAVA_HOME%;.
44
A first graphics program
3.4
Graphics Primitives A graphics primitive can be loosely defined as a drawing function which the system makes available to the applications programmer. An obvious example is the Java “drawLine()” method. The subject of what to include within a system as a primitive can get quite complex because consideration needs to be given to the properties of the display device. Display devices include computer screens, printers, plotters and 'barco' type scanned optical displays. Even within a display device type there may be several alternative forms (e.g. a 'computer screen may be a CRT vector system, a CRT raster system or a LCD. A printer may be dot matrix, ink jet, laser etc.). At the lowest level each device needs its own set of primitives (hardware primitives). For a raster type display at the lowest level we only need to implement a pixel(x,y) on - off function. We normally expect to work at a higher level with a more comprehensive set of primitives which could, for example, include: Line, Circle (ellipse?), box, polyline, arc, fill etc. Java implements a comprehensive set of graphics primitives: abstract void clearRect(int x, int y, int width, int height)
Clears the specified rectangle by filling it with the background color of the current drawing surface.
abstract void clipRect(int x, int y, int width, int height)
Intersects the current clip with the specified rectangle.
abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
abstract
Creates a new Graphics object that is a copy of this Graphics object.
Graphics create()
Graphics create(int x, int y, int width, int height)
Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.
abstract
void dispose()
Disposes of this graphics context and releases any system resources that it is using.
void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle.
Table 2. The methods of the Graphics class - taken from the on-line Java JDK manuals
45
A first graphics program
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x, int y)
Draws the text given by the specified byte array, using this graphics context's current font and color.
void drawChars(char[] data, int offset, int length, int x, int y)
Draws the text given by the specified character array, using this graphics context's current font and color.
abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is currently available.
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
Draws as much of the specified image as is currently available.
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. Draws the outline of an
abstract void drawOval(int x, int y, int width, int height)
oval.
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates.
Table 2. The methods of the Graphics class - taken from the on-line Java JDK manuals
46
A first graphics program
void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
Draws a sequence of connected lines defined by arrays of x and y coordinates.
void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle.
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws an outlined roundcornered rectangle using this graphics context's current color.
abstract void drawString(AttributedCharacterIterator iterator, int x, int y)
Draws the text given by the specified iterator, using this graphics context's current color.
abstract void drawString(String str, int x, int y)
Draws the text given by the specified string, using this graphics context's current font and color.
void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color.
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Fills a closed polygon defined by arrays of x and y coordinates.
void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's current color. Fills the specified rectan-
abstract void fillRect(int x, int y, int width, int height)
gle.
abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills the specified rounded corner rectangle with the current color.
void finalize()
Disposes of this graphics context once it is no longer referenced.
Table 2. The methods of the Graphics class - taken from the on-line Java JDK manuals
47
A first graphics program
abstract
Gets the current clipping
Shape getClip() area.
abstract
Rectangle getClipBounds()
Returns the bounding rectangle of the current clipping area.
Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the current clipping area.
Rectangle getClipRect()
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
abstract
Color getColor()
abstract
Font getFont()
FontMetrics getFontMetrics()
Gets this graphics context's current color. Gets the current font. Gets the font metrics of the current font.
abstract FontMetrics getFontMetrics(Font f)
Gets the font metrics for the specified font.
boolean hitClip(int x, int y, int width, int height)
Returns true if the specified rectangular area intersects the bounding rectangle of the current clipping area.
abstract void setClip(int x, int y, int width, int height)
Sets the current clip to the rectangle specified by the given coordinates.
abstract
void setClip(Shape clip)
Sets the current clipping area to an arbitrary clip shape.
abstract
void setColor(Color c)
Sets this graphics context's current color to the specified color.
abstract
void setFont(Font font)
Sets this graphics context's font to the specified font.
abstract
void setPaintMode()
Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color.
abstract
void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color.
String toString()
Returns a String object representing this Graphics object's value.
Table 2. The methods of the Graphics class - taken from the on-line Java JDK manuals
48
A first graphics program
abstract
void translate(int x, int y)
Translates the origin of the graphics context to the point (x, y) in the current coordinate system.
Table 2. The methods of the Graphics class - taken from the on-line Java JDK manuals Use the on-line Java JDK manuals to find details of these functions. The full documentation of this class can be found at http://java.sun.com/j2se/1.3/ docs/index.html. To overcome the dependence of primitives on the display device a variety of standard 'device independent' software graphics primitives have been defined. The three most important standards you may meet are GKS (Graphics Kernel System), PHIGS (Programmers Hierarchical Interactive Graphics System) and X-Windows. A comparison of the relative merits of the competing systems is beyond the scope of this book. For our purposes, device independence is provided by the Java runtime system. In summary, the process of generating a graphics image on the display device can be represented by the following pipeline: Figure 25 - “Programmer’s model of a computer graphics system - version 2” .
application program
Graphics Primitives
Video memory
Display
Figure 25. Programmer’s model of a computer graphics system - version 2 Applications programs rarely (if ever) access the video memory directly indeed Java has no facilities to do this. All drawing is done via the graphics primitives. Further stages in this system will be added later. Workstations which are optimised for graphics applications (e.g. Silicon Graphics) will often implement a wide range of graphics primitives in hardware thus speeding up the applications.
49
A first graphics program
Chapter review - 3 So far, you should have learned about: •the structure of a basic Java graphics program •how to draw lines in Java •what a graphics primitive is •how an application program actually draw something on screen.
50
A first graphics program
Exercises - 3 3.1
Type in the Apollo13 program and make it work.
3.2
Make a copy of the Apollo 13 program in a new directory and modify it so that the output looks like this (Hint - you only need to change one function - paintComponent in Gcanvas):.
3.3
Alter the “hi” program to say “hello world”
3.4
Square swirl - Write a Java program to draw a square and then to draw a second square within the first reduced in size by the
51
A first graphics program
parameter u (see Figure 26 below, try u = 0.1 to start with) and so on until you have drawn approximately 40 diminishing squares.
(Px,Py)
P P1 (P1x,P1y)
Q (Qx,Qy) Q1 (Q1x,Q1y)
distance PP1 distance PQ
(S1x,S1y) S1
(R1x,R1y) R1
(Sx,Sy) S
=
distance SS1 distance SP
0 < u < 1 e.g. u= 0.1 R
(Rx,Ry)
P,Q,R,S - are the vertices of the first (outer) square P1,Q1,R1,S1 - are the vertices of the second (inner) squareu
HINT P1x = ((1 - u) * Px) + (u * Qx) P1y = ((1 - u) * Py) + (u * Qy) similarly for Q,R,S
Figure 26. The swirling square problem
=u
52
A first graphics program
Your answer should look something like Figure 27
Figure 27. Square swirl 3.5
Try the same thing with other shapes, triangle etc. (no answers for this one - your on your own!)
3.6
Generalise your solution so that it will draw any n-sided regular polygon.
53
Graphics Primitives
Chapter 4 Graphics Primitives
4.1
Introduction Having seen the anatomy of a simple Java graphics program, some questions arise: How does that program relate to the concepts of pixels and memory mapping that were introduced in Chapter 2? How were the lines drawn? What exactly did the line: g.drawLine(50,50,50,150);
do? In this chapter we will “lift the bonnet” and see how drawLine(), drawOval() etc. (the Java graphics primitives) operate. You will rarely need to program at this level (routines such as these are provided so you don’t have to), but an appreciation of how Java manages to efficiently perform such operations will influence our later program design.
4.2
Drawing straight lines Let’s start with drawLine(). We’re going to develop our own version of this method and as with so many things in computing there are two ways of doing it: the brute force approach and the elegant way. We’ll tackle the brute force way first to introduce some ideas and then looks at how it can be refined to produce an efficient (i.e. quick) solution known as Bresenham’s algorithm.
54
Graphics Primitives
4.2.1
Brute force The starting point (pun intended) is the equation of a straight line: y=mx+c
(Equation 2)
where m is the gradient of the line: y to – y from ∆y m = ------ = -----------------------x to – x from ∆x and c is its intercept of the y-axis c = y from – ( m × x from )
(Equation 3)
Assume that the endpoints of the line are known: (xto,yto) ∆y c
(xfrom,yfrom)
Figure 28. Specifying straight lines
∆x
55
Graphics Primitives
For any value of x we can compute y. Fortunately, in the quantized, integer valued world of computer graphics and bitmapped displays we know all the values of x. Figure 29 shows a rather course-grained bit mapped display superimposed upon the “mathematical” straight line of the previous diagram.
xfrom, xfrom+1, xfrom+2.....xto
Figure 29. Enumerating the values of x A for loop can be used to iterate through all the values of x between xfrom and xto and for each of these, the corresponding y value calculated. for(int x= xfrom; x1, the values for y increase by an amount greater than the increments of x that we are using (i.e. >1). Compare the lines xfrom = 10, yfrom = 10, xto = 40, yto = 30 (Figure 29) xfrom = 10, yfrom = 10, xto = 40, yto = 90 (Figure 30) Figure 29
Figure 30
x
y
x
y
10
10
10
10
11
11
11
13
12
11
12
15
13
12
13
18
14
13
14
21
Table 3. Comparison of x & y values for different gradients
The solution to the gaps problem is to always use the most rapidly changing variable (x or y) as the index to the loop (Figure 31). i.e.When the gradient (m) >1 - use y as the control variable in the loop and make x the subject of the equation: x = (y-c)/m
(Equation 4)
57
Graphics Primitives
m=1 use y use x
use x use y m = -1
Figure 31. Control variable usage depend on line gradient There is a second problem with the brute force approach: It requires floating point arithmetic which is slow when compared with using integer only arithmetic. An approach which used solely integers would result in a much quicker algorithm.
58
Graphics Primitives
4.2.2
Bresenham’s algorithm One such integer only algorithm is Bresenham’s. Start by considering the simple case where 0 < m