1. Trang chủ
  2. » Khoa Học Tự Nhiên

Wiley computer graphics for java programmers 2nd edition mar

549 71 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 549
Dung lượng 6,01 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Computer Graphics for Java Programmers, Second EditionbyLeen AmmeraalandKang Zhang John Wiley & Sons 2007 386 pages ISBN:9780470031605 Covering elementary concepts in creating andmanipul

Trang 1

Computer Graphics for Java Programmers, Second Edition

byLeen AmmeraalandKang Zhang John Wiley & Sons 2007 (386 pages)

ISBN:9780470031605

Covering elementary concepts in creating andmanipulating 2D and 3D graphical objects, this bookpresents topics from classic graphics algorithms toperspective drawings and hidden-line elimination

Table of Contents

Computer Graphics for Java Programmers, Second Edition

Trang 2

Index

List of Figures

List of Code Examples

Trang 3

Computer Graphics for Java Programmers, 2nd edition

covers elementary concepts in creating and

manipulating 2D and 3D graphical objects, covering topics from classic graphics algorithms to perspective drawings and hidden-line elimination.

mathematician at Akzo Research and Engineering,

Arnhem, The Netherlands, from 1961 to 1972 and did research work on compilers from 1972 to 1977 at

Mathematical Centre, Amsterdam He wrote many

Trang 4

Academic Service) Some of his Wiley books have been translated into other languages (Japanese, Russian, Italian, French, German, Greek, Danish, Portuguese, Bulgarian).

Kang Zhang is a Professor in Computer Science and Director of Visual Computing Lab at the University of Texas at Dallas He received his B.Eng in Computer Engineering from the University of Electronic Science and Technology, China, in 1982; and Ph.D from the University of Brighton, UK, in 1990 He held academic positions in the UK and Australia, prior to joining UTD Zhang's current research interests are in the areas of visual languages, graphical visualization, and Web

engineering; and has published over 130 papers in

these areas He has taught computer graphics and

related subjects at both graduate and undergraduate levels for many years Zhang was also an editor of two books on software visualization.

Trang 5

stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise,except under the terms of the Copyright, Designs and Patents Act 1988

or under the terms of a licence issued by the Copyright Licensing AgencyLtd, 90 Tottenham Court Road, London W1T 4LP, UK, without the

permission in writing of the Publisher Requests to the Publisher should

be addressed to the Permissions Department, John Wiley & Sons Ltd,The Atrium, Southern Gate, Chichester, West Sussex PO19 8SQ,

England, or emailed to permreq@wiley.co.uk, or faxed to (+44) 1243770620

Designations used by companies to distinguish their products are oftenclaimed as trademarks All brand names and product names used in thisbook are trade names, service marks, trademarks or registered

trademarks of their respective owners The Publisher is not associatedwith any product or vendor mentioned in this book

Trang 6

information in regard to the subject matter covered It is sold on the

understanding that the Publisher is not engaged in rendering professionalservices If professional advice or other expert assistance is required, theservices of a competent professional should be sought

Other Wiley Editorial Offices

John Wiley & Sons Inc., 111 River Street, Hoboken, NJ 07030, USA

Jossey-Bass, 989 Market Street, San Francisco, CA 94103-1741, USAWiley-VCH Verlag GmbH, Boschstr 12, D-69469 Weinheim, GermanyJohn Wiley & Sons Australia Ltd, 42 McDougall Street, Milton,

Queensland 4064, Australia

John Wiley & Sons (Asia) Pte Ltd, 2 Clementi Loop #02-01, Jin Xing

Distripark, Singapore 129809

John Wiley & Sons Canada Ltd, 6045 Freemont Blvd, Mississauga, ONT,L5R 4J3, Canada

006.6 63 – dc22

2006029327

Trang 7

A catalogue record for this book is available from the British Library13: 978-0-470-03160-5

(PB) ISBN-10: 0-470-03160-3 (PB)

Trang 8

During the eight years since the publication of the first edition of

Computer Graphics for Java Programmers, the programming language

Java has increasingly become the language of choice in many industrialand business domains Hence the skills for developing computer

graphics applications using Java have been highly in demand but aresurprisingly lacking in the computer science curricula Meanwhile, for thepast five years the second author has been teaching Computer Graphics

at his current university using the first edition of this textbook, and felt thatthere was a need to update the book We therefore decided to jointlywrite this second edition

This edition continues the main theme of the first edition, that is, graphicsprogramming in Java, with plenty of source code available to the reader.The new edition has, however, been updated as follows:

4 A beta version of a companion software package has been

added, which demonstrates the working of different algorithmsand concepts introduced in the book

5 More illustrative examples have been included in several

chapters and various minor errors in the first edition have beencorrected

Over the past few years, Java has evolved into more powerful

programming environments The most notable development related tocomputer graphics is its support for 3D graphics Many application

examples illustrated in this book could be readily implemented using Java

Trang 9

implementation, which we consider undesirable for computer sciencestudents We therefore believe that this textbook continues to serve as anindispensable introduction to the foundation of computer graphics, onwhich many application program interfaces (APIs) and graphics libraries

could be developed, and more importantly, how they are developed.

As in the first edition, the example programs can again be downloadedfrom the Internet at:

http://home.planet.nl/~ammeraal

or at:

http://www.utdallas.edu/~kzhang/BookCG/

In writing this second edition, several people need to be acknowledgedfor their direct or indirect contributions We would first like to thank theUT-Dallas graduate students Bill Fahle, Andy Restrepo, Janis Schubert,and Subramanya Suresh, who contributed to different parts of the

demonstration software In particular, we appreciate the great effort ofJanis Schubert in developing and integrating different parts of the

software while striving to maintain the same look and feel of the userinterfaces Finally, we thank Jonathan Shipley of John Wiley and Sons forhis enthusiastic support and assistance in publishing this edition

Leen Ammeraal, The Netherlands

l.ammeraal@hccnet.nl

Kang Zhang, USA

kzhang@utdallas.edu

Trang 10

Chapter 1: Elementary Concepts

This book is primarily about graphics programming and mathematics.Rather than discussing general graphics subjects for end users or how

to use graphics software, we will deal with more fundamental subjects,required for graphics programming In this chapter, we will first

understand and appreciate the nature of discreteness of displayed

graphics on computer screens We will then see that x- and y-coordinates need not necessarily be pixel numbers, also known asdevice coordinates In many applications logical coordinates are moreconvenient, provided we can convert them to device coordinates

Especially with input from a mouse, we also need the inverse

conversion, as we will see at the end of this chapter

Trang 11

The most convenient way of specifying a line segment on a computer

screen is by providing the coordinates of its two endpoints In

mathematics, coordinates are real numbers, but primitive line-drawingroutines may require these to be integers This is the case, for example,

drawLine are integers, ranging from zero to some maximum value The

above call to drawLine produces exactly the same line as this one:

g.drawLine(xB, yB, xA, yA);

We will now use statements such as the above one in a complete Javaprogram Fortunately, you need not type these programs yourself, sincethey are available from the Internet, as specified in the Preface It will

also be necessary to install the Java Development Kit (JDK), which youcan also download, using the following Web page:

http://java.sun.com/

If you are not yet familiar with Java, you should consult other books, such

as some mentioned in the Bibliography, besides this one

The following program draws the largest possible rectangle in a canvas.The color red is used to distinguish this rectangle from the frame border:// RedRect.java: The largest possible rectangle in red.import java.awt.*;

import java.awt.event.*;

public class RedRect extends Frame

Trang 14

frame; in other words, the x-coordinates increase from left to right and y-coordinates from top to bottom Although there is a method getInsets to

obtain the widths of all four borders of a frame so that we could computethe dimensions of the client rectangle ourselves, we prefer to use a

canvas

The tiny screen elements that we can assign a color are called pixels (short for picture elements), and the integer x-and y-values used for them are referred to as device coordinates Although there are 200 pixels on a

horizontal line in the entire frame, only 192 of these lie on the canvas, theremaining 8 being used for the left and right borders On a vertical line,there are 100 pixels for the whole frame, but only 73 for the canvas

Apparently, the remaining 27 pixels are used for the title bar and for thetop and bottom borders Since these numbers may differ in different Javaimplementations and the user can change the window size, it is desirablethat our program can determine the canvas dimensions We do this by

using the getSize method of the class Component, which is a superclass

of Canvas The following program lines in the paint method show how we

obtain the canvas dimensions and how we interpret them:

Trang 15

connecting the points (0, 0) and (7, 3) is approximated by a set of eightpixels.

Trang 16

Note that the call

g.drawLine(xA, y, xB, y);

draws a horizontal line consisting of | xB − xA |+1 pixels.

Trang 17

In mathematics, lines are continuous and have no thickness, but they arediscrete and at least one pixel thick in our graphics output This

difference in the interpretation of the notion of lines may not cause anyproblems if the pixels are very small in comparison with what we are

drawing However, we should be aware that there may be such problems

in special cases, as Figure 1.3(a) illustrates Suppose that we have todraw a filled square ABCD of, say, 4×4 pixels, consisting of the bottom-right triangle ABC and the upper-left triangle ACD, which we want to paint

in dark gray and light gray, respectively, without drawing any lines

Strangely enough, it is not clear how this can be done: if we make thediagonal AC light gray, triangle ABC contains fewer pixels than triangleACD; if we make it dark gray, it is the other way round

Figure 1.3: Small filled regions

A much easier but still non-trivial problem, illustrated by Figure 1.3(b), isfilling the squares of a checker-board with, say, dark and light gray

squares instead of black and white ones Unlike squares in mathematics,those on the computer screen deserve special attention with regard tothe edges belonging or not belonging to the filled regions We have seenthat the call

Trang 18

void checker(Graphics g, int x, int y, int n, int w){ for (int i=0; i<n; i++)

Trang 19

positive y direction to be reversed by performing this simple

transformation:

1.3.2 Continuous vs Discrete Coordinates

Instead of the discrete (integer) coordinates we are using at the lower,device-oriented level, we want to use continuous (floating-point)

coordinates at the higher, problem-oriented level Other usual terms are

device and logical coordinates, respectively Writing conversion routines

to compute device coordinates from the corresponding logical ones andvice versa is a bit tricky We must be aware that there are two solutions tothis problem, even in the simple case in which increasing a logical

fx(x),

fy(y):

the logical coordinates of the point with device coordinates x and y.

With regard to x-coordinates, the first solution is based on rounding:

int iX(float x){return Math.round(x);}

Trang 20

For example, with this solution we have

The second solution is based on truncating:

int iX(float x){return (int)x;} // Not used infloat fx(int x){return (float)x + 0.5F;} // this book.With these conversion functions, we would have

Trang 22

we compute the new points A′ , B′ and C′ near A, B and C and lying onthe sides AB, BC and CA, respectively, writing

Figure 1.5: Triangles drawn inside each other

If we change the dimensions of the window, new equilateral trianglesappear, again in the center of the canvas and with dimensions

proportional to the size of this canvas Without floating-point logical

Trang 23

have been less easy to write:

// Triangles.java: This program draws 50 triangles inside each other.import java.awt.*;

Trang 24

It is important to notice that, on each triangle edge, the computed

floating-point coordinates, not the integer device coordinates derivedfrom them, are used for further computations This principle, which

applies to many graphics applications, can be depicted as follows:

which is in contrast to the following scheme, which we should avoid Here

Trang 25

graphics output but also for further computations, so that such errors willaccumulate:

In summary, we compare and contrast the logical and device coordinatesystems in the following table, in terms of (1) the convention used in thetext, but not in Java programs, of this book; (2) the data types of the

Value domain

Trang 26

1.4 ANISOTROPIC AND ISOTROPIC MAPPING MODES

1.4.1 Mapping a Continuous Interval to a Sequence of

Integers

Suppose we want to map an interval of real logical coordinates, such as

to the set of integer device coordinates {0, 1, 2, … ,9} Unfortunately, themethod

Trang 27

Figure 1.6: Pixels lying 10/9 logical units apart

In general, if a horizontal line of our window consists of n pixels,

numbered 0, 1, …, maxX (where maxX = n − 1), and the corresponding(continuous) interval of logical coordinates is 0 ≤ x ≤ rWidth, we can usethe following method:

Trang 28

We will use this in a demonstration program Regardless of the window

dimensions, the largest possible rectangle in this window has the logical

dimensions 10.0 × 7.5 After clicking on a point of the canvas, the logicalcoordinates are shown, as Figure 1.7 illustrates

Figure 1.7: Logical coordinates with anisotropic mapping

mode

Trang 29

setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); show();

Trang 30

int iY(float y){return maxY - Math.round(y/pixelHeight);}float fx(int x){return x * pixelWidth;}

Trang 31

1.4.3 Isotropic Mapping Mode

We can arrange for horizontal and vertical units to be equal in terms of

their real size by using the same scale factor for x and y Let us use the term drawing rectangle for the rectangle with dimensions rWidth and

Since it is normally desirable for a drawing to appear in the center of thecanvas, it is often convenient with the isotropic mapping mode to placethe origin of the logical coordinate system at that center This implies that

we will use the following logical-coordinate intervals:

Our methods iX and iY will map each logical coordinate pair (x, y) to a pair (X, Y) of device coordinates, where

To obtain the same scale factor for x and y, we compute rWidth/maxX and rHeight/maxY and take the larger of these two values; this maximum value, pixelSize, is then used in the methods iX and iY, as this fragment

shows:

Dimension d = getSize();

int maxX = d.width - 1, maxY = d.height - 1;

pixelSize = Math.max(rWidth/maxX, rHeight/maxY);

Trang 32

int iX(float x){return Math.round(centerX + x/pixelSize);}int iY(float y){return Math.round(centerY - y/pixelSize);}float fx(int x){return (x - centerX) * pixelSize;}

Trang 33

Figure 1.8, right logical coordinate x device coordinate iX(x)

add("Center", new CvIsotrop());

setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); show();

Trang 35

MOUSE

We will use the conversion methods of the previous program in a moreinteresting application, which enables the user to define a polygon byclicking on points to indicate the positions of the vertices Figure 1.9

shows such a polygon, just after the user has defined successive

vertices, ending at the first one on the left, which is marked with a tinyrectangle

Figure 1.9: Polygon defined by a user

The large rectangle surrounding the polygon is the drawing rectangle:only vertices inside this rectangle are guaranteed to appear again if theuser changes the dimensions of the window The very wide window ofFigure 1.9 was obtained by dragging one of its corners After the polygonwas drawn, the dimensions of the window were again changed, to obtainFigure 1.10 It is also possible to change these dimensions during theprocess of drawing the polygon We now summarize the requirements forthis application program:

The first vertex is drawn as a tiny rectangle

If a later vertex is inside the tiny rectangle, the drawing of onepolygon is complete

Only vertices in the drawing rectangle are drawn

The drawing rectangle (see Figures 1.9 and 1.10) is either ashigh or as wide as the window, yet maintaining its height/widthratio regardless of the window shape

Trang 36

1 Activate the mouse;

2 When the left mouse button is pressed

2.1 Get x- and y-coordinates at where the mouse is clicked;

Trang 38

addWindowListener(new WindowAdapter()

{public void windowClosing(WindowEvent e){System.exit(0);}}); setSize (500, 300);

add("Center", new CvDefPoly());

setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); show();

Trang 39

if (v.size()>0&&

dx * dx + dy * dy <4 * pixelSize * pixelSize) ready = true;

Trang 40

However, since class names are unique throughout this book, it is

possible to place all program files in the same directory In this way, eachrequired class will be available

EXERCISES

1.1 How many pixels are put on the screen by each of the following

calls?

Ngày đăng: 25/03/2019, 16:43

TỪ KHÓA LIÊN QUAN

w