graphics: introduction basic steps used in cgdjmoon/gaming/gaming-notes/graphics.pdf · graphics:...

43
Graphics: Introduction Basic steps used in CG: 1. Set properties Color Fill style Line widths Etc. 2. Model object Each object usually modeled in its own coordinate system Its orientation wrt the system is at the discretion of the programmer, usually such that it makes modeling easy 3. Transform Transform object from local space to world space The basic transforms are (a) Translation (b) Rotation (c) Scale (d) Reflection (e) Shear 4. Render Draw the scene Coordinate systems/spaces involved 1. Object/Local Origin placed wherever most convenient WRT object for modeling Units arbitrary, left to modeler 2. World/User Origin inherent in API Units arbitrary, left to modeler 3. Device Specific to type of display device For monitors * Origin at upper left * Units are pixels 1

Upload: others

Post on 24-May-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Introduction

• Basic steps used in CG:

1. Set properties

– Color

– Fill style

– Line widths

– Etc.

2. Model object

– Each object usually modeled in its own coordinate system

– Its orientation wrt the system is at the discretion of the programmer,usually such that it makes modeling easy

3. Transform

– Transform object from local space to world space

– The basic transforms are

(a) Translation

(b) Rotation

(c) Scale

(d) Reflection

(e) Shear

4. Render

– Draw the scene

• Coordinate systems/spaces involved

1. Object/Local

– Origin placed wherever most convenient WRT object for modeling

– Units arbitrary, left to modeler

2. World/User

– Origin inherent in API

– Units arbitrary, left to modeler

3. Device

– Specific to type of display device

– For monitors

∗ Origin at upper left

∗ Units are pixels

1

Page 2: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Introduction - Graphics and Graphics2D

• The Graphics class is the earlier of the two

• Graphics2D was added later, and extends Graphics

• Rendering is sent to an output device, which can be

1. The screen (all subsequent discussion assumes the screen)

2. A printer

3. An image

• To render, you need a canvas

– Usually a Component (awt) or JComponent (swing) object

– The programmer overrides the paint (Component) or paintComponent

(JComponent) method of the component with code to create the desiredscene

• The graphics context represents the set of attributes that affect the renderingprocess

– The context is passed into paint/paintComponent

– This context is then used to set the attributes

2

Page 3: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: AWT and Graphics

• Provided early Java 2D modeling capabilities

• World/User space origin in upper left corner

• Object origin in upper left corner

• Usually use a Panel/JPanel object as drawing canvas

• No separation of modeling and rendering

• Basic structure of a Graphics program

import java.awt.*;

import java.awt.event.*;

import java.swing.*;

import java.awt.geom.*;

public class BasicStructure extends JFrame {

public static void main()

{

JFrame = new JFrame();

frame.setTitle("Basic Structure");

frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

frame.getContentPane();

frame.pack();

frame.setVisible(true);

}

public void init()

{

JPanel gamePanel = new JPanel();

getContentPane().add(gamePanel);

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

g.setColor(...);

...

}

}

3

Page 4: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: AWT (2)

• Graphics class methods for modeling/rendering

1. draw methods draw a perimeter

(a) void drawLine(int x1, int y1, int x2, int y2)

(b) void drawRect(int x1, int y1, int w, int h)

(c) void drawOval(int x1, int y1, int w, int h)

– The oval is inscribed in the defining rectangle

(d) void drawArc(int x1, int y1, int w, int h, int startAngle, int arcAngle)

– Angles measured from center of defining rectangle, and specified indegrees

∗ Zero degrees is horizontal line from center toward right

∗ Forty five degrees is from center to upper right corner

(e) void drawRoundRect(int x1, int y1, int w, int h, int arcW, int arcH)

– arcW and arcH specify a rectangle which defines an oval

– The four quadrants of this oval represent the corners of the rectangle

4

Page 5: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: AWT (3)

(f) void drawPolygon(int xPoints[], int yPoints[], int nPoints)

– xpoints and ypoints hold the x and y coordinates of a set of pointsused to draw the polygon

– nPoints specifies how many of these points to use (always startingfrom the 0th index)

(g) void drawPolyLine(int xPoints[], int yPoints[], int nPoints)

– Like drawPolygon(), except that it is not a closed object unless thefirst and last points are the same

(h) void drawString(String s, int x, int y)

– (x, y) denotes the baseline of the leftmost character in s

2. fill methods model and display filled figures

(a) void fillRect(int x1, int y1, int w, int h)

(b) void fillOval(int x1, int y1, int w, int h)

(c) void fillArc(int x1, int y1, int w, int h, int startAngle, int arcAngle)

(d) void fillRoundRect(int x1, int y1, int w, int h, int arcw, int arch)

(e) void fillPolygon(int xPoints[], int yPoints[], int nPoints)

3. public abstract void clearRect(int x, int y, int width, int height)

– Fills specified rectangle with background color

• Graphics class methods for setting and retrieving attributes

1. void setColor(Color c)

2. Color getColor()

3. void setFont(Font f)

4. Font getFont()

5. void setPaintMode()

– Overwrite pixels when draw

6. void setXORMode(Color c1)

– Pixels of the current color are set to c1; pixels of color c1 are set to thecurrent color

7. void translate(int x, int y)

– Translates origin of graphics context to (x, y)

5

Page 6: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: AWT (4)

• Graphics class methods for creating and manipulating the graphics context

1. Graphics create()

– Creates a new Graphics object that is a copy of this Graphics object

2. Graphics create(int x, int y, int w, int h)

– Creates a new Graphics object that is a copy of this Graphics object at(x, y) with dimensions w and h

3. void dispose()

– Disposes of this graphics context and releases any system resources thatit is using

4. boolean drawImage(Image i, int x, int y, java.awt.Image.ImageObserver o)

– Draws as much of the specified image as is currently available

5. boolean drawImage(Image i, int x, int y, int w, int h, java.awt.Image.ImageObservero)

– Draws as much of the specified image as is currently available, scaled tofit inside the specified rectangle

6. void copyArea(int x, int y, int width, int height, int dx, int dy)

– Copies an area of the component and relocates by dx and dy

6

Page 7: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Java2D - Introduction

• Unlike java.awt, java2D provides clear separation of rendering and modeling

– Class Graphics2D performs the rendering

– Other classes (see below) provide the remainder of the functionality

• Graphics2D extends java.awt.Graphics

1. Cast argument to paintComponent(Graphics g) to Graphics2D object

2. Call Graphics getGraphics()

– This approach does not produce persistent images

• 2D rendering in java:

1. Acquire a graphics object

2. Acquire a graphics context and set attributes

– The context is the collection of attributes that control the renderingprocess

3. Select an object to render

4. Invoke a rendering operation

• Java2D uses immediate mode for rendering -

– Rendering is executed as soon as a rendering operation is invoked

• Java2D provides output device-independence

– Output will appear the same regardless of the output device (screen, printer,image) or its resolution

7

Page 8: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Java2D - Introduction (2)

• Graphics2D context

– Context is implemented by the following classes:

1. Font

2. Composite

∗ Determines how a pixel may be combined with its neighbors

∗ Used for blur, edge detection, contrast, etc.

3. AffineTransform

∗ Used to orient shapes

4. Stroke

∗ Controls features of line segments, such as endcaps

5. Paint

∗ Provides sophisticated ways of shading objects, like gradients

6. RenderingHints

∗ Allows the programmer to request (but does not guarantee) certainfeatures, like antialiasing

7. Clip

∗ Provides for specifying clipping shapes

– These will be discussed below

8

Page 9: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Java2D - Introduction (3)

• Graphics2D rendering pipeline:

9

Page 10: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Java2D - Introduction (4)

• Basic structure of a java2D program:

import java.awt.*;

import java.awt.event.*;

import java.swing.*;

import java.awt.geom.*;

public class BasicStructure extends JFrame {

public static void main()

{

JFrame = new JFrame();

frame.setTitle("Basic Structure");

frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

frame.getContentPane();

frame.pack();

frame.setVisible(true);

}

public void init()

{

JPanel gamePanel = new JPanel();

getContentPane().add(gamePanel);

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

//create scene

}

}

• The parameter to paintComponent() is declared as Graphics, but is a Graph-ics2D object for any version of Java that supports Graphics2D

10

Page 11: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Graphics2D Shape Interface

• The Shape interface and inherited classes:

• Graphics2D provides two methods for drawing shapes:

1. public void draw(Shape s)

2. public void fill(Shape s)

– They reflect the java.awt.Graphic.drawX() and java.awt.Graphic.fillX() meth-ods

• Many subclasses have two inner subclasses:

1. X.Double

2. X.Float

– They obviously determine the data type to be used to define the shape

11

Page 12: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Graphics2D Shape interface (2)

• Subtypes:

1. Line2D

– Abstract, so cannot be instantiated directly (must use Double or Floatclass)

– Methods:

∗ Note that the other shapes have similar methods

(a) Object clone() - returns a new copy of the object

(b) boolean contains(double x, double y) - Tests if a specified coordinateis inside the boundary of this Line2D

(c) boolean contains(double x, double y, double w, double h) - Tests if theinterior of this Line2D entirely contains the specified set of rectangularcoordinates

(d) boolean contains(Point p) - Tests if a specified Point2D object is insidethe boundary of this Line2D

(e) boolean contains(Rectangle r) - Tests if the interior of this Line2Dentirely contains the specified Rectangle2D object

(f) Rectangle getBounds() - Returns the bounding box of this Line2D

(g) abstract Point2D getP1/P2() - Returns the starting/ending Point2Dobject of this Line2D object

(h) abstract double getX1/X2/Y1/Y2()

(i) boolean intersects(double x, double y, double w, double h) - Tests if thisLine2D object intersects the interior of a specified set of rectangularcoordinates

12

Page 13: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Graphics2D Shape interface (3)

2. Line2D.Double (similar for Line2D.Float)

– Methods:

(a) Line2D.Double() - Creates a line from (0, 0) → (0, 0)

(b) Line2D.Double(double x1, double y1, double x2, double y2) - Createsa line from (x1, y1) → (x2, y2)

(c) Line2D.Double(Point2D p1, Poin2D p2) - Creates a line from p1 →p2

(d) Rectangle2D getBounds2D()

(e) Point2D getP1/P2()

(f) double getX1/X2/Y1/Y2()

(g) Rectangle2D getBounds2D() - Returns the bounding box of this Line2Dobject

(h) void setLine(double X1, double Y1, double X2, double Y2)

3. Rectangle2D.Float/Double

– Methods:

(a) Rectangle2D.Double(double x, double y, double w, double h)

(b) Rectangle2D.Double() - Located at (0, 0) with w = h = 0

(c) type getX/Y/Height/Width()

(d) Rectangle2D getBounds2D() - Returns the bounding box of thisRectangle2Dobject

13

Page 14: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Graphics2D Shape interface (4)

4. RoundRectangle2D.Float/Double

– Like the awt round rectangle

– Methods:

(a) RoundRectangle2D.Double(double x, double y, double w, double h,double arcw, double arch)

(b) RoundRectangle2D.Double() - Located at (0, 0) with w = h = 0

(c) type getX/Y/Height/Width/ArcWidth/ArcHeight()

(d) Rectangle2D getBounds2D() - Returns the bounding box of thisRoundRectangle2Dobject

5. Arc2D.Double/Float

– Like the awt arc

– Methods:

(a) Arc2D.Double(double x, double y, double w, double h, double start,double extent, int type) - Constructs a new arc, initialized to thespecified location, size, angular extents, and closure type

∗ Closure type (type is one of OPEN , CHORD, or PIE

(b) Arc2D.Double() - Constructs a new OPEN arc, initialized to location(0, 0), size (0, 0), angular extents (start = 0, extent = 0)

(c) Arc2D.Double(int type) - Constructs a new arc, initialized to location(0, 0), size (0, 0), angular extents (start = 0, extent = 0), and thespecified closure type.

(d) Arc2D.Double(Rectangle2D ellipseBounds, double start, double ex-tent, int type) -

(e) type getAngleExtent/AngleStart/Height/Width/X/Y

14

Page 15: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Graphics2D Shape interface (5)

6. Quad/CubicCurve2D.Double/Float

– Curves are defined by control points

∗ Two anchor the end points of the curve

∗ The others act like magnets and pull the curve toward them - thegreater the distance, the greater the pull

∗ Quad curves have three control points; cubic have four

– Methods:

(a) CubicCurve2D.Double(double x1, double y1, double ctrlx1, double ctrly1,double ctrlx2, double ctrly2, double x2, double y2) - (x1, y1) and (x2,y2) are the end points

(b) CubicCurve2D.Double() - Constructs and initializes a CubicCurvewith coordinates (0, 0, 0, 0, 0, 0)

(c) type getCtrlX1/CtrlX2/CtrlY1/CtrlY2/X1/X2/Y1/Y2

(d) Point2D getCtrlP1/CtrlP2/P1/P2

7. Polygon

– Same as awt version

– Methods:

(a) Polygon(int[] xpoints, int[] ypoints, int npoints) -

(b) Polygon() - Creates an empty polygon

(c) void addPoint(int x, int y) - Appends the specified coordinates tothis Polygon

15

Page 16: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Color - Introduction

• Color is represented in terms of a color space

• Some common color spaces are

1. RGB

2. CMYK

3. CIEXYZ

• Given primaries P1, P2, P3, a color is computed as

C = a ∗ P1 + b ∗ P2 + c ∗ P3

where (a, b, c) are the amounts of (P1, P2, P3) desired

• Note that colors have an additional channel - the alpha channel - for trans-parency

– This will be discussed under Transparency

16

Page 17: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Color - Color Class

• Color uses the sRGB color space

– This is an absolute RGB space

– It is device-independent - a specified color should appear the same no matterwhat display device is used

• Predefined colors:

1. static Color BLACK

2. static Color BLUE

3. static Color CYAN

4. static Color DARK GRAY

5. static Color GRAY

6. static Color GREEN

7. static Color LIGHT GRAY

8. static Color MAGENTA

9. static Color ORANGE

10. static Color PINK

11. static Color RED

12. static Color WHITE

13. static Color YELLOW

– Lowercase version of the above for backward-compatibility

17

Page 18: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Color - Color Class (2)

• Colors can be created with the Color constructors:

1. Color(float r, float g, float b)

– Creates an opaque sRGB color with the specified red, green, and bluevalues in the range (0.0 - 1.0)

2. Color(int r, int g, int b)

– Creates an opaque sRGB color with the specified red, green, and bluevalues in the range (0 - 255)

3. Color(float r, float g, float b, float a)

– Float version that includes an alpha value

4. Color(int r, int g, int b, int a)

– Integer version that includes an alpha value

5. Color(int rgb)

– Creates an opaque sRGB color with the specified combined RGB valueconsisting of the red component in bits 16-23, the green component inbits 8-15, and the blue component in bits 0-7

6. Color(int rgba, boolean hasAlpha)

– Alpha version of above

• Additional methods:

1. int get/Red/Green/Blue/Alpha()

2. float[] getRGBColorComponents(float[] compArray)

– Returns a float array containing only the color components of the Color,in the default sRGB color space

– If compArray is null, an array of length 3 is created for the return value

– Otherwise, compArray must have length 3 or greater, and it is filled inwith the components and returned

3. float[] getRGBComponents(float[] compArray)

– Alpha version of above

– compArray must have length 4

18

Page 19: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Color - Color Class (3)

• Methods also exist for converting among color spaces (e.g., HSB)

• Graphics.setColor(Color c)

– Sets this graphics context’s current color to the specified color

– All subsequent graphics operations using this graphics context use this spec-ified color

19

Page 20: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction

• A transform is an operation that changes the geometry of a shape in somemanner; e.g., location, size, orientation, etc.

• An affine transform is one that preserves parallelism

• The basic affine transforms:

1. Translation

– Relocation of point WRT frame

– Translation T (dx, dy) of vertex P = (x, y)

x′ = x+ dx, y′ = y + dy

20

Page 21: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction (2)

2. Rotation

– Defined about origin

– Positive rotation counterclockwize (righthand rule)

– Derivation of rotation R(θ) of vertex P = (x, y)

(a) x given by r ∗ cosφ, y by r ∗ sinφ(b) Using cos(θ + φ) = cosθ ∗ cosφ− sinφ ∗ sinθ,

sin(θ + φ) = cosθ ∗ sinφ+ sinθ ∗ cosφ,

x′ = r ∗ cosθ ∗ cosφ− r ∗ sinφ ∗ sinθ(c) Substituting x for r ∗ cosφ and y for r ∗ sinφ gives

x′ = x ∗ cosθ − y ∗ sinθ(d) Similarly, y′ = r ∗ cosθ ∗ sinφ+ r ∗ sinθ ∗ cosφ = x ∗ sinθ + y ∗ cosθ

21

Page 22: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction (3)

3. Scale

– Change of proportion

– Affects location

– Scale S(sx, sy) of vertex P = (x, y)

x′ = sx ∗ x, y′ = sy ∗ y

– Uniform scale: sx = sy

22

Page 23: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction (4)

4. Shear

– Lateral force applied to object

– Change of one coordinate in proportion to the other

– Shear Hy(hx) of vertex P = (x, y)

x′ = x+ hx ∗ y, y′ = y

– Alternative:

hz(θ, φ) · v(x, y) = v′(x+ ycotθ, y + xcotφ), whereθ is angle of deformation along x axis,φ is angle of deformation along y axis

5. **Reflection

– This is sometimes considered a separate operation

– Reflections about axes are simply scales with negative values

• Rigid body transformations

– Angles and lengths are preserved

– Translation and rotation

23

Page 24: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction (5)

• 2D Transforms are represented as 2 X 2 (or 3 X 3) matrices

– The use of 3 X 3 matrices allows all matrix transforms to be accomplishedby a uniform operation: matrix multiplication

– The matrices:

1. Translation:

T (dx, dy) =

1 0 dx0 1 dy0 0 1

2. Rotation:

R(θ) =

cosθ −sinθ 0sinθ cosθ 0

0 0 1

3. Scale:

S(sx, sy) =

sx 0 00 sy 00 0 1

4. Shear:

Hx(hx) =

1 hx 0hy 1 00 0 1

where hx = cotan(θ), hy = cotan(φ)

24

Page 25: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Introduction (6)

– 2D points are represented as 3 X 1 matrices, and thus

P ′(x′, y′) =

x′

y′

1

=

m00x+m01y +m02

m10x+m11y +m12

1

=

m00 m01 m02

m10 m11 m12

0 0 1

Xx

y

1

= P (x, y)

• Inverses

1. T−1(dx, dy) = T (−dx,−dy)

2. S−1(sx, sy) = S(1/sx, 1/sy)

3. R−1n (θ) = Rn(−θ)4. H−1n (α, β) = Hn(−α,−β)

25

Page 26: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - AffineTransform Class

• Constructors:

1. AffineTransform()

– Constructs a new AffineTransform representing the Identity transforma-tion

2. AffineTransform(AffineTransform Tx)

– Constructs a new AffineTransform that is a copy of the specified Affine-Transform object

3. AffineTransform(double[] flatmatrix)

– Constructs a new AffineTransform from an array of double precision val-ues representing either the 4 non-translation entries or the 6 specifiableentries of the 3x3 transformation matrix

4. AffineTransform(double m00, double m10, double m01, double m11, doublem02, double m12)

– Constructs a new AffineTransform from 6 double precision values repre-senting the 6 specifiable entries of the 3x3 transformation matrix

5. AffineTransform(float[] flatmatrix)

6. AffineTransform(float m00, float m10, float m01, float m11, float m02, floatm12)

• Note: The above allow the programmer to explicitly create transform matrices

• The set methods make it easy to set up a specific type of transform:

1. void setToTranslation(double tx, double ty)

2. void setToRotation(double theta)

3. void setToScale(double sx, double sy)

4. void setToShear(double shx, double shy)

• The following return AffineTransform objects of the specified type:

1. static AffineTransform getTranslateInstance(double tx, double ty)

2. static AffineTransform getRotateInstance(double theta)

3. static AffineTransform getScaleInstance(double sx, double sy)

4. static AffineTransform getShearInstance(double shx, double shy)

26

Page 27: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - AffineTransform Class (2)

• To transform objects, use Shape createTransformedShape(Shape pSrc)

Shape s1 = new Rectangle.Float(15, 75, 20, 40);

Shape s2;

AffineTransform tr = new AffineTransform();

tr.setToTranslation(20, -30);

s2 = tr.createTransformedShape(s1);

g2.draw(s2);

• To translate the entire context, use public abstract void translate(int x, int y)

Shape s1 = new Rectangle.Float(15, 75, 20, 40);

Shape s2;

AffineTransform tr = new AffineTransform();

tr.setToTranslation(20, -30);

s2 = tr.createTransformedShape(s1);

g2.translate(100, 100);

g2.draw(s2);

– The origin of the context has been translated to (100, 100)

– The rectangle has been translated wrt to context’s origin

– So the rectangle will actually appear at (120, 70)

• There are additional methods for transforming sets of points and vectors

1. Methods of general form void transform(args) are used to transform sets ofpoints

2. Methods of general form void deltaTransform(args) are used to transformsets of vectors

27

Page 28: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Composition

• Composition refers to a set of transforms applied in sequence

– Denoted op1() ◦ op2()

• Composition of transformations of the same type:

1. T (dx′, dy′, dz′) ◦ T (dx, dy, dz) = T (dx′ + dx, dy′ + dy, dz′ + dz)

2. S(sx′, sy′, sz′) ◦ S(sx, sy, sz) = S(sx′ ∗ sx, sy′ ∗ sy, sz′ ∗ sz)

3. Rn(θ) ◦Rn(φ) = Rn(θ + φ)

4. Hn(α′, β′) ◦Hn(α, β) = Hn(α

′ + α, β′ + β)

• Commutativity

1. T ′ ◦ T ≡ T ◦ T ′

2. S ◦ S ′ ≡ S · S ′

3. Rα ◦Rβ ≡ Rβ ◦Rα

4. Hα ◦Hβ ≡ Hβ ◦Hα

5. Rα ◦ Suniform ≡ Suniform ◦Rα

• To perform an arbitrary scale/rotation/shear in place

1. Translate to origin

2. Scale, rotate, shear

3. Translate to final position

• Composition using AffineTransformation

1. void translate(double tx, double ty)

– Concatenates this transform with a translation transformation

2. void rotate(double theta)

– Concatenates this transform with a rotation transformation

3. void rotate(double theta, double x, double y)

– Concatenates this transform with a transform that rotates coordinatesaround an anchor point

– Expands into T (x, y) ◦R(theta) ◦ T (−x,−y)

4. static AffineTransform getRotateInstance(double theta, double x, double y)

– Returns a transform that rotates coordinates around an anchor point

28

Page 29: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Geometric Transforms - Composition (2)

5. void scale(double sx, double sy)

– Concatenates this transform with a scaling transformation

6. void shear(double shx, double shy)

– Concatenates this transform with a shearing transformation

7. void concatenate(AffineTransform Tx)

– Concatenates an AffineTransform Tx to this AffineTransform Cx in themost commonly useful way to provide a new user space that is mappedto the former user space by Tx

8. void preConcatenate(AffineTransform Tx)

– Concatenates an AffineTransform Tx to this AffineTransform Cx in a lesscommonly used way such that Tx modifies the coordinate transformationrelative to the absolute pixel space rather than relative to the existinguser space

• The above compositions (except preConcatenate) are carried out as follows

– Let CT be the current transform– Consider

Shape s1 = new Rectangle.Float(20, 20, 50, 50);

AffineTransform t = new AffineTransform();

t.rotate(Math.PI/2);

t.scale(2, 4);

t.translate(100, 50);

Shape s2 = t.createTransformedShape(s1);

g2.fill(s2);

– This results in the sequence

CT ◦R(Math.PI/2) ◦ s(2, 4) ◦ T (100, 50) ◦ s2– Note that the net effect is that the translation is applied first, the scale

second, and finally the rotation!

• preConcatenate premultiplies the current transform by its argument Tx

Tx · CT

29

Page 30: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: GeneralPath Class

• This class allows the programmer to make a shape from scratch

• It utilizes vector-like methods for drawing:

1. void moveTo(float x, float y)

– Adds a point to the path by moving to the specified coordinate (addsno segment)

2. void lineTo(float x, float y)

– Adds a point to the path by drawing a straight line from the currentcoordinates to the new specified coordinates

3. void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)

– Adds a curved segment, defined by three new points, to the path bydrawing a Bezier (cubic) curve that intersects both the current coordi-nates and the coordinate (x3, y3), using the control points (x1, y1) and(x2, y2)

4. void quadTo(float x1, float y1, float x2, float y2)

– Adds a curved segment, defined by two new points, to the path bydrawing a quadratic curve that intersects both the current coordinatesand the coordinates (x2, y2), using the control point (x1, y1)

5. void closePath()

– Closes the current subpath by drawing a straight line back to the coor-dinates of the last moveTo

6. void reset()

– Resets the path to empty

30

Page 31: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: GeneralPath Class (2)

• Constructors:

1. GeneralPath()

2. GeneralPath(int rule)

– Constructs a new GeneralPath object with the specified winding rule tocontrol operations that require the interior of the path to be defined

3. GeneralPath(int rule, int initialCapacity)

– Constructs a new GeneralPath object with the specified winding ruleand the specified initial capacity to store path coordinates

∗ initialCapacity specifies how many coords the initial GeneralPath ar-ray should hold

∗ The default size is 10

4. GeneralPath(Shape s)

– Constructs a new GeneralPath object from an arbitrary Shape object

31

Page 32: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: GeneralPath Class (3)

• Winding rules

– A non-simple shape is one that has intersecting lines, or multiple disjointboundaries

– To specify what constitutes the interior and exterior of such shapes, a wind-ing rule is used

– The PathIterator class defines two rules:

1. WIND EVEN ODD

∗ An area is interior if the number of edge crossings to reach that areais odd, exterior if even

2. WIND NON ZERO

∗ This rule considers not only edge crossings, but edge direction

(a) A counter is initialized to zero

(b) When crossing an edge, increment the counter if the edge crossesthe path from left to right

(c) Decrement the counter if the edge crosses the path from right to left

∗ Interior regions are those for which the counter != 0

– Examples (moving from bottom to top along each line segment):

32

Page 33: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: GeneralPath Class (4)

• Typical usage:

GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);

path.moveTo(10, 110);

path.lineTo(110, 110);

path.lineTo(110, 10);

path.lineTo(10, 10);

path.close();

path.moveTo(35, 85);

path.lineTo(85, 85);

path.lineTo(85, 35);

path.lineTo(35, 35);

path.close();

g2.fill(path);

path.reset();

path.setWindingRule(WIND_NON_ZERO);

path.moveTo(210, 110);

path.lineTo(310, 110);

path.lineTo(310, 10);

path.lineTo(210, 10);

path.close();

path.moveTo(235, 85);

path.lineTo(285, 85);

path.lineTo(285, 35);

path.lineTo(235, 35);

path.close();

g2.fill(path);

33

Page 34: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Constuctive Geometry - Class java.awt.geom.Area

• This class facilitates the creation of complex shapes by the ”logical” combina-tion of other shapes

• The constructive area geometry operations

– There are four:

1. void add(Area rhs)

∗ Adds the shape of the specified Area to the shape of this Area

∗ (See diagram below)

2. void exclusiveOr(Area rhs)

∗ Sets the shape of this Area to be the combined area of its currentshape and the shape of the specified Area, minus their intersection

3. void intersect(Area rhs)

∗ Sets the shape of this Area to the intersection of its current shapeand the shape of the specified Area

4. void subtract(Area rhs)

∗ Subtracts the shape of the specified Area from the shape of this Area

– The Area object is altered; the argument is left unchanged

34

Page 35: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Constuctive Geometry - Class java.awt.geom.Area (2)

– Constructors:

1. Area()

2. Area(Shape)

– Typical usage:

Shape s1 = new Oval2D.Float(0, 0, 100, 100);

Shape s2 - new Rectangle.Float(50, 50, 100, 60);

Area a1 = new Area(s1);

Area a2 = new Area(s2);

a1.add(a2);

g2.translate(20, 200);

g2.draw(s1);

g2.draw(s2);

a1.add(a2);

g2.translate(250, 0);

g2.fill(a1);

a1 = new Area(s1);

a1.subtract(a2);

g2.translate(250, 0);

g2.fill(a1);

a1 = new Area(s1);

a1.intersect(a2);

g2.translate(250, 0);

g2.fill(a1);

a1 = new Area(s1);

a1.exclusiveOr(a2);

g2.translate(250, 0);

g2.fill(a1);

35

Page 36: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint Interface

• This class provides more general capabilities than Color

• It allows filling shapes with something other than a solid color

• It is implemented by Color, GradientPaint, and TexturePaint

• It applies to Graphics2D operations

• Paint effects are applied by calls to abstract void setPaint(Paint p)

– This is comparable to Graphics.setColor()

36

Page 37: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint - Color Class

• This class provides solid colors

• See earlier discussion of Color class

• Typical usage:

g2.setPaint(Color.red);

37

Page 38: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint - GradientPaint Class

• This class allows blending of colors across a shape

– Blending is based on the gradient line, specified by 2 points

– These points do not have to correspond to vertices of the shape being filled

• Constructors:

1. GradientPaint(float x1, float y1, Color color1, float x2, float y2, Colorcolor2)

– Constructs a simple acyclic GradientPaint object

– (x1, y1) and (x2, y2) define the gradient line

– Pixels beyond the endpoints are the color associated with that endpointwith no variation

– If y1 == y2 (e.g., top corners)

– If x1! = x2, y1! = y2 (e.g., opposite corners)

38

Page 39: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint - GradientPaint Class (2)

2. GradientPaint(float x1, float y1, Color color1, float x2, float y2, Colorcolor2, boolean cyclic)

– If cyclic == true, the gradient line is tiled across the shape (mirroredon each iteration)

– If cyclic == false, as described for the previous constructors

3. GradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2)

4. GradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2, booleancyclic)

39

Page 40: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint - GradientPaint Class (2)

• Sample usage:

GradientPaint gp = new GradientPaint(100, 100, Color.RED, 300, 100, Color.BLUE);

g2.setPaint(gp);

Shape e = newEllipse2D.Float(100, 100, 200, 50);

g2.fill(e);

40

Page 41: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Paint - TexturePaint Class

• Allows use of textures

• Constructor:

1. TexturePaint(BufferedImage txtr, Rectangle2D anchor)

– txtr represents the image to be textured

– anchor indicates where the texture is to be applied

• Sample usage:

Shape r = new Reactangle2D.Float(100, 100, image.getWidth(), image.getHeight());

TexturePaint tp = new TexturePaint(image, r);

g2.setPaint(tp);

Shape e = newEllipse2D.Float(100, 100, 200, 50);

g2.fill(e);

41

Page 42: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Transparency

• Transparency is controlled by the alpha channel - the fourth component ofColor

• Given a pixel and an incoming fragment about to be written to that pixel, theresulting color and alpha values are determined by the equations

α ∗ C = Fs ∗ αs ∗ Cs + Fd ∗ αd ∗ Cdα = Fs ∗ αs + Fd ∗ αdwhere

– C is the resulting color of the pixel

– α is the resulting alpha value of the pixel

– The s subscript represents a property of the source (incoming values)

– The d subscript represents a property of the destination (existing values ofthe pixel)

– The F coefficients represent various ways of combining the values, as definedby the Porter-Duff rules

• The Porter-Duff rules:

Rule Fs FdClear 0 0SrcOver 1 1− αsDstOver 1− αd 1SrcIn αd 0DstIn 0 αsSrcOut 1− αd 0DstOut 0 1− αsSrc 1 0Dst 0 1SrcAtop αd 1− αsDstAtop 1− αd αsXor 1− αd 1− αs

• For example:

1. For opaque objects, the applicable rule is Src with alpha values of 1

2. For equal blending of two values, use SrcAtop or DstAtop with alpha valuesof 0.5

42

Page 43: Graphics: Introduction Basic steps used in CGdjmoon/gaming/gaming-notes/graphics.pdf · Graphics: AWT (4) Graphics class methods for creating and manipulating the graphics context

Graphics: Transparency (2)

• To specify a blending rule

1. Use the Graphics2D methodvoid setComposite(Composite comp)

2. The Composite values (as listed in the above table) are defined in classAlphaComposite

3. Sample code:g2.setComposite(AlphaComposite.SrcIn);

• You can also create a composite using the method static AlphaCompositegetInstance(int rule)

– The rules are AlphaComposite.CLEAR, AlphaComposite.SRC OVER, etc.– For example,

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_IN);

g2.setComposite(ac);

43