Upload
sathis-kumar-kathiresan
View
22
Download
0
Embed Size (px)
DESCRIPTION
useful
Citation preview
7/13/2019 It Sem7 Cs2401nol
1/325
UNIT- I
2D PRIMITIVES
7/13/2019 It Sem7 Cs2401nol
2/325
Line and Curve Drawing
Algorithms
7/13/2019 It Sem7 Cs2401nol
3/325
Line Drawing
y = m . x + b
m = (yendy0) / (xen dx0)
b = y0m . x0x0
y0
xend
yend
7/13/2019 It Sem7 Cs2401nol
4/325
DDA Algorithm
if |m|1
yk+1= yk+ 1
xk+1= xk+ 1/m
x0
y0
xend
yend
x0
y0
xend
yend
7/13/2019 It Sem7 Cs2401nol
5/325
DDA Algorithm
#include
#include
inline int round (const float a) { return int (a + 0.5); }
void lineDDA (int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0, dy = yEnd - y0, steps, k;
float xIncrement, yIncrement, x = x0, y = y0;
if (fabs (dx) > fabs (dy))
steps = fabs (dx); /* |m|=1 */
xIncrement = float (dx) / float (steps);
yIncrement = float (dy) / float (steps);
setPixel (round (x), round (y));
for (k = 0; k < steps; k++) {
x += xIncrement;
y += yIncrement;
setPixel (round (x), round (y));
}
}
7/13/2019 It Sem7 Cs2401nol
6/325
Bresenhams Line Algorithm
xk
yk
xk+1
yk+1
y
du
dl
xk xk+1
yk
yk+1
7/13/2019 It Sem7 Cs2401nol
7/325
Bresenhams Line Algorithm
#include
#include
/* Bresenham line-drawing procedure for |m| xEnd) {
x = xEnd;
y = yEnd;
xEnd = x0;
}
else {
x = x0;
y = y0;
}
setPixel (x, y);
while (x < xEnd) {
x++;
if (p < 0)
p += twoDy;
else {
y++;
p += twoDyMinusDx;
}
setPixel (x, y);
}
}
7/13/2019 It Sem7 Cs2401nol
8/325
Circle Drawing
Pythagorean Theorem:
x2+ y2= r2
(x-xc)2
+ (y-yc)2
= r2
(xc-r) x (xc+r)
y = ycr2- (x-x
c)2
xc
yc
r(x, y)
7/13/2019 It Sem7 Cs2401nol
9/325
Circle Drawing
change x
change y
7/13/2019 It Sem7 Cs2401nol
10/325
Circle Drawing
using polar coordinates
x = xc+ r . cos
y = yc+ r . sin
change w i th steps ize 1/r
r (x, y)
(xc, yc)
7/13/2019 It Sem7 Cs2401nol
11/325
Circle Drawing
using polar coordinates
x = xc+ r . cos
y = yc+ r . sin
change w i th steps ize 1/r
use symmetry i f >450
r (x, y)
(xc, yc)
(x, y)
(xc, yc)
450
(y, x)(y, -x)
(-x, y)
7/13/2019 It Sem7 Cs2401nol
12/325
Midpoint Circle Algorithm
f(x,y) = x2+ y2- r2
7/13/2019 It Sem7 Cs2401nol
13/325
Midpoint Circle Algorithm#include
class scrPt {public:
GLint x, y;};
void setPixel (GLint x, GLint y){
glBegin (GL_POINTS);glVertex2i (x, y);
glEnd ( );}
void circleMidpoint (scrPt circCtr, GLint radius){
scrPt circPt;
GLint p = 1 - radius;
circPt.x = 0;circPt.y = radius;void circlePlotPoints (scrPt, scrPt);
/* Plot the initial point in each circle quadrant. */circlePlotPoints (circCtr, circPt);
/* Calculate next points and plot in each octant. */while (circPt.x < circPt.y) {
circPt.x++;if (p < 0)p += 2 * circPt.x + 1;
else {circPt.y--;
p += 2 * (circPt.x - circPt.y) + 1;}circlePlotPoints (circCtr, circPt);}
}
void circlePlotPoints (scrPt circCtr, scrPt circPt);{
setPixel (circCtr.x + circPt.x, circCtr.y + circPt.y);setPixel (circCtr.x - circPt.x, circCtr.y + circPt.y);setPixel (circCtr.x + circPt.x, circCtr.y - circPt.y);setPixel (circCtr.x - circPt.x, circCtr.y - circPt.y);
setPixel (circCtr.x + circPt.y, circCtr.y + circPt.x);setPixel (circCtr.x - circPt.y, circCtr.y + circPt.x);setPixel (circCtr.x + circPt.y, circCtr.y - circPt.x);setPixel (circCtr.x - circPt.y, circCtr.y - circPt.x);
}
7/13/2019 It Sem7 Cs2401nol
14/325
OpenGL#include // (or others, depending on the system in use)
void init (void){
glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glMatrixMode (GL_PROJECTION); // Set projection parameters.gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}
void lineSegment (void)
{ glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (0.0, 0.0, 1.0); // Set line segment color to red.glBegin (GL_LINES);
glVertex2i (180, 15); // Specify line-segment geometry.glVertex2i (10, 145);
glEnd ( );
glFlush ( ); // Process all OpenGL routines as quickly as possible.}
void main (int argc, char** argv){
glutInit (&argc, argv); // Initialize GLUT.glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Set display mode.glutInitWindowPosition (50, 100); // Set top-left display-window position.glutInitWindowSize (400, 300); // Set display-window width and height.glutCreateWindow ("An Example OpenGL Program"); // Create display window.
init ( ); // Execute initialization procedure.glutDisplayFunc (lineSegment); // Send graphics to display window.glutMainLoop ( ); // Display everything and wait.
}
7/13/2019 It Sem7 Cs2401nol
15/325
OpenGL
Point Functions glVertex*( );
* : 2, 3, 4i (integer)
s (short)f (float)d (double)
Ex:glBegin(GL_POINTS);
glVertex2i(50, 100);glEnd();
int p1[ ]={50, 100};glBegin(GL_POINTS);
glVertex2iv(p1);glEnd();
7/13/2019 It Sem7 Cs2401nol
16/325
OpenGL
Line Functions GL_LINES GL_LINE_STRIP
GL_LINE_LOOP
Ex:
glBegin(GL_LINES);glVertex2iv(p1);glVertex2iv(p2);
glEnd();
7/13/2019 It Sem7 Cs2401nol
17/325
OpenGL
glBegin(GL_LINES); GL_LINES GL_LINE_STRIP
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);glVertex2iv(p4);
glVertex2iv(p5);
glEnd();
GL_LINE_LOOP
p1
p1
p1
p2
p3
p2
p2
p4
p3
p3
p5
p4
p4
p5
7/13/2019 It Sem7 Cs2401nol
18/325
Antialiasing
Supersampl ingCount the
number of
subpixels
that overlap
the line path.
Set the intensity
proportional
to this count.
7/13/2019 It Sem7 Cs2401nol
19/325
Antialiasing
Area Sampl ingLine is treated as a rectangle.
Calculate the overlap areasfor pixels.
Set intensity proportional to
the overlap areas.
80% 25%
7/13/2019 It Sem7 Cs2401nol
20/325
Antialiasing
Pixel Sampling
Micropos i t ion ing
Electron beam is shifted 1/2,
1/4, 3/4 of a pixel diameter.
7/13/2019 It Sem7 Cs2401nol
21/325
Line Intensity differences
Change the line drawingalgorithm:
For horizontal andvertical lines use thelowest intensity
For 45olines use thehighest intensity
7/13/2019 It Sem7 Cs2401nol
22/325
2D Transformations
with Matrices
7/13/2019 It Sem7 Cs2401nol
23/325
Matrices
3,32,31,3
3,22,21,2
3,12,11,1
aaa
aaa
aaa
A
A matrix is a rectangular array of numbers.
A general matrix will be represented by an upper-case italicisedletter.
The element on the ith row andjth column is denoted by ai,j. Notethat we start indexing at 1, whereas Cindexes arrays from 0.
7/13/2019 It Sem7 Cs2401nol
24/325
Given two matricesAand Bif we want to add BtoA(that isformA+B) then ifAis (nm), Bmust be (nm), Otherwise,A+Bis not defined.
The addition produces a result, C=A+B, with elements:
Matrices Addition
jijiji BAC ,,,
121086
84736251
8765
4321
7/13/2019 It Sem7 Cs2401nol
25/325
Given two matricesAand Bif we want to multiply BbyA(thatis formAB) then ifAis (nm), Bmust be (mp), i.e., thenumber of columns inAmust be equal to the number of rowsin B. Otherwise,ABis not defined.
The multiplication produces a result, C=AB, with elements:
(Basically we multiply the first row ofAwith the first column ofBand put this in the c1,1element of C.And so on).
Matrices Multiplication
m
k
kjikji baC1
,
7/13/2019 It Sem7 Cs2401nol
26/325
96669555
7644
6233
86
329854
762
Matrices Multiplication (Examples)
26+ 63+ 72=44
6233
86
54
62Undefined!2x2 x 3x2 2!=3
2x2 x 2x4 x 4x4 is allowed. Result is 2x4 matrix
7/13/2019 It Sem7 Cs2401nol
27/325
Unlike scalar multiplication,AB BA
Matrix multiplication distributes over addition:
A(B+C) =AB+AC
Identity matrix for multiplication is defined as I.
The transpose of a matrix,A, is either denotedATorA isobtained by swapping the rows and columns ofA:
Matrices -- Basics
3,23,1
2,22,1
1,21,1
3,22,21,2
3,12,11,1'
aa
aa
aa
Aaaa
aaaA
7/13/2019 It Sem7 Cs2401nol
28/325
2D Geometrical Transformations
Translate
Rotate Scale
Shear
7/13/2019 It Sem7 Cs2401nol
29/325
Translate Points
Recall.. We can translate points in the (x, y) plane to new positionsby adding translation amounts to the coordinates of the points. Foreach point P(x, y) to be moved by dxunits parallel to thexaxis and by dyunits parallel to the yaxis, to the new point P(x, y ). The translation has
the following form:y
x
dyydxx
''
P(x,y)
P(x,y)
dx
dy
In matrix format:
y
x
dd
yx
yx''
If we define the translation matrix , then we have P =P + T.
y
x
d
dT
7/13/2019 It Sem7 Cs2401nol
30/325
Scale Points
Points can be scaled (stretched) by sxalong thexaxis and by syalong the yaxis into the new points by the multiplications:
We can specify how much bigger or smaller by means of a scale factor
To double the size of an object we use a scale factor of 2, to half the size ofan obejct we use a scale factor of 0.5
ysy
xsx
y
x
'
'
P(x,y)
P(x,y)
xsxx
syy
y
y
x
s
s
y
x
y
x
0
0
'
'
If we define , then we have P =SP
y
x
s
sS
0
0
7/13/2019 It Sem7 Cs2401nol
31/325
Rotate Points (cont )
Points can be rotated through an angle about the origin:
cossin
cossinsincos)sin()sin(|'|'
sincos
sinsincoscos
)cos()cos(|'|'
|||'|
yx
lllOPy
yx
ll
lOPx
lOPOP
P(x,y)
P(x,y)
xx
y
y
l
O
y
x
y
x
cossin
sincos
'
'
P =RP
7/13/2019 It Sem7 Cs2401nol
32/325
Review
Translate: P = P+T Scale: P = SP Rotate: P = RP
Spot the odd one out Multiplying versus adding matrix
Ideally, all transformations would be the same.. easier to code
Solution: Homogeneous Coordinates
7/13/2019 It Sem7 Cs2401nol
33/325
Homogeneous Coordinates
For a given 2D coordinates (x, y), we introduce a third dimension:
[x, y, 1]
In general, a homogeneous coordinates for a 2D point has the form:
[x, y, W]
Two homogeneous coordinates [x, y, W] and [x, y, W] are said to be of thesame (or equivalent) if
x= kx eg: [2, 3, 6] = [4, 6, 12]y= ky for some k 0 where k=2W= kW
Therefore any [x, y, W] can be normalised by dividing each element by W:[x/W, y/W, 1]
7/13/2019 It Sem7 Cs2401nol
34/325
Homogeneous Transformations
Now, redefine the translation by using homogeneous coordinates:
Similarly, we have:
y
x
d
d
y
x
y
x
'
'
1100
10
01
1
'
'
y
x
d
d
y
x
y
x
PTP '
1100
00
00
1
'
'
y
x
s
s
y
x
y
x
1100
0cossin
0sincos
1
'
'
y
x
y
x
Scaling Rotation
P = S P P = R P
7/13/2019 It Sem7 Cs2401nol
35/325
Composition of 2D Transformations
1. Additivity of successive translations
We want to translate a point Pto Pby T(dx1, dy1)and then to Pbyanother T(dx2, dy2)
On the other hand, we can define T21= T(dx1, dy1) T(dx2, dy2)first, thenapply T21to P:
where
]),()[,('),('' 112222 PddTddTPddTP yxyxyx
PTP 21''
100
10
01
100
10
01
100
10
01
),(),(
21
21
1
1
2
2
112221
yy
xx
y
x
y
x
yxyx
dd
dd
d
d
d
d
ddTddTT
7/13/2019 It Sem7 Cs2401nol
36/325
T(-1,2) T(1,-1)
(2,1)
(1,3)
(2,2)
100
110001
100
210
101
100
110
101
21T
Examples of Composite 2D Transformations
7/13/2019 It Sem7 Cs2401nol
37/325
Composition of 2D Transformations (cont )
2. Multiplicativity of successive scalings
where
PS
PssSssS
PssSssSP
yxyx
yxyx
21
1122
1122
)],(),([
]),()[,(''
100
0*0
00*
100
00
00
100
00
00
),(),(
12
12
1
1
2
2
112221
yy
xx
y
x
y
x
yxyx
ss
ss
s
s
s
s
ssSssSS
7/13/2019 It Sem7 Cs2401nol
38/325
Composition of 2D Transformations (cont )
3. Additivity of successive rotations
where
PR
PRR
PRRP
21
12
12
)]()([
])()[(''
100
0)cos()sin(
0)sin()cos(100
0cossin
0sincos
100
0cossin
0sincos
)()(
1212
1212
11
11
22
22
1221
RRR
7/13/2019 It Sem7 Cs2401nol
39/325
Composition of 2D Transformations (cont )
4. Different types of elementary transformations discussed abovecan be concatenated as well.
where
MP
PddTR
PddTRP
yx
yx
)],()([
]),()[('
),()( yx ddTRM
7/13/2019 It Sem7 Cs2401nol
40/325
Consider the following two questions:
1) translate a line segment P1 P2, say, by -1 units in thexdirection
and -2 units in the ydirection.
2). Rotate a line segment P1 P2, say by degrees counter clockwise,about P1.
P1(1,2)
P2(3,3)
P2
P1
P1(1,2)
P2(3,3)P2
P1
7/13/2019 It Sem7 Cs2401nol
41/325
ther Than Point Transformations
Translate Lines: translate both endpoints, then join them.
Scale or Rotate Lines: More complex. For example, consider torotate an arbitrary line about a point P1,
three steps are needed:1). Translate such that P1is at the origin;2). Rotate;3). Translate such that the point at the origin
returns to P1.
T(-1,-2) R()
P1(1,2)
P2(3,3)
P2(2,1)T(1,2)P2
P2
P1
P1P1
7/13/2019 It Sem7 Cs2401nol
42/325
Another Example.
Scale
Translate
Rotate
Translate
7/13/2019 It Sem7 Cs2401nol
43/325
Order Matters
As we said, the order for composition of 2D geometrical transformations matters,because, in general, matrix multiplication is not commutative. However, it is easy to
show that, in the following four cases, commutativity holds:
1). Translation + Translation
2). Scaling + Scaling
3). Rotation + Rotation
4). Scaling (with sx= sy) + Rotation
just to verify case 4:
if sx= sy, M1= M2.
100
0cos*sin*
0sin*cos*
100
0cossin
0sincos
100
00
00
)(),(1
yy
xx
y
x
yx
ss
ss
s
s
RssSM
100
0cos*sin*
0sin*cos*
100
00
00
100
0cossin
0sincos
),()(2
yx
yx
y
x
yx
ss
ss
s
s
ssSRM
7/13/2019 It Sem7 Cs2401nol
44/325
Rigid-Body vs. Affine Transformations
A transformation matrix of the form
where the upper 22 sub-matrix is orthogonal, preserves angles andlengths. Such transforms are called rigid-body transformations,because the body or object being transformed is not distorted in anyway. An arbitrary sequence of rotation and translation matrices
creates a matrix of this form.
The product of an arbitrary sequence of rotation, translations, andscalematrices will cause an affine transformation, which have theproperty of preserving parallelism of lines, but not of lengths and
angles.
100
2221
1211
y
x
trr
trr
7/13/2019 It Sem7 Cs2401nol
45/325
Rigid-Body vs. Affine Transformations (cont )
Shear transformation is also affine.
Unit cube 45 Scale in x , not in y
Rigid- bodyTransformation
AffineTransformation
Shear in the xdirection Shear in the ydirection
100
010
01 a
SHx
100
01
001
bSHy
7/13/2019 It Sem7 Cs2401nol
46/325
2D Output Primitives
Points Lines Circles Ellipses Other curves Filling areas
Text Patterns Polymarkers
7/13/2019 It Sem7 Cs2401nol
47/325
Filling area
Polygons are considered!
1) Scan-Line Filling (between edges)2) Interactive Filling (using an interior
starting point)
7/13/2019 It Sem7 Cs2401nol
48/325
1) Scan-Line Filling (scan
conversion)
Problem: Given the vertices or edges of a
polygon, which are the pixels to beincluded in the area filling?
7/13/2019 It Sem7 Cs2401nol
49/325
Scan-Line filling, contd
Main idea: locate the intersections between the
scan-lines and the edges of the polygon sort the intersection points on each
scan-line on increasing x-coordinates generate frame-buffer positions along
the current scan-line between pairwiseintersection points
7/13/2019 It Sem7 Cs2401nol
50/325
Main idea
7/13/2019 It Sem7 Cs2401nol
51/325
Scan-Line filling, contd
Problemswith intersection points that arevertices:
Basic rule: count them as if each vertex isbeing two points (one to each of the two joiningedges in the vertex)
Exception: if the two edges joining in the
vertex are on opposite sides of the scan-line,then count the vertex only once (require someadditional processing)
7/13/2019 It Sem7 Cs2401nol
52/325
Vertex problem
7/13/2019 It Sem7 Cs2401nol
53/325
Scan-Line filling, contd
Time-consuming to locate the intersection points!
If an edge is crossed by a scan-line, mostprobably also the next scan-line will cross it(the use of coherence properties)
7/13/2019 It Sem7 Cs2401nol
54/325
Scan-Line filling, contd
Each edge is well described by an edge-record:
ymax
x0(initially the x related to ymin) x/y (inverse of the slope) (possibly also x and y)x/y is used for incremental calculations
of the intersection points
7/13/2019 It Sem7 Cs2401nol
55/325
Edge Records
7/13/2019 It Sem7 Cs2401nol
56/325
Scan-Line filling, contd
The intersection point (xn,yn) between an edgeand scan-line ynfollows from the line equationof the edge:
yn= y/x . xn+ b (cp. y = m.x + b)The intersection between the same edge and the
next scan-line yn+1is then given from thefollowing:
yn+1= y/x . xn+1+ band also
yn+1= yn+ 1 = y/x. xn+ b +1
7/13/2019 It Sem7 Cs2401nol
57/325
Scan-Line filling, contd
This gives us:
xn+1= xn+ x/y , n = 0, 1, 2, ..
i.e. the new value of x on the next scan-
line is given by adding the inverse of theslope to the current value of x
7/13/2019 It Sem7 Cs2401nol
58/325
Scan-Line filling, contd
An active list of edge records intersectingwith the current scan-line is sorted on
increasing x-coordinatesThe polygon pixels that are written in theframe buffer are those which arecalculated to be on the current scan-linebetween pairwise x-coordinatesaccording to the active list
7/13/2019 It Sem7 Cs2401nol
59/325
Scan-Line filling, contd
When changing from one scan-line to the next,the active edge list is updated:
a record with ymax< the next scan-line isremoved
in the remaining records, x0is incremented androunded to the nearest integer
an edge with ymin= the next scan-line isincluded in the list
7/13/2019 It Sem7 Cs2401nol
60/325
Scan-Line Filling Example
7/13/2019 It Sem7 Cs2401nol
61/325
2) Interactive Filling
Given the boundaries of a closed surface.By choosing an arbitrary interior point,
the complete interior of the surface willbe filled with the color of the userschoice.
7/13/2019 It Sem7 Cs2401nol
62/325
Interactive Filling, contd
Definition: An area or a boundary is said to be 4-connectedif from an arbitrary point all otherpixels within the area or on the boundary can
be reached by only moving in horizontal orvertical steps.
Furthermore, if it is also allowed to takediagonal steps, the surface or the boundary issaid to be 8-connected.
7/13/2019 It Sem7 Cs2401nol
63/325
4/8-connected
7/13/2019 It Sem7 Cs2401nol
64/325
Interactive Filling, contd
A recursive procedure for filling a 4-connected (8-connected) surface caneasily be defined.
Assume that the surface shall have thesame color as the boundary (can easilybe modified!).
The first interior position (pixel) is choosenby the user.
7/13/2019 It Sem7 Cs2401nol
65/325
Interactive Filling, algorithm
void fill(int x, int y, int fillColor) {int interiorColor;interiorColor = getPixel(x,y);
if (interiorColor != fillColor) {setPixel(x, y, fillColor);fill(x + 1, y, fillColor);
fill(x, y + 1, fillColor);fill(x - 1, y, fillColor);fill(x, y - 1, fillColor); } }
7/13/2019 It Sem7 Cs2401nol
66/325
Inside-Outside test
When is a point an interior point?Odd-Even RuleDraw conceptually a line from a specified point to
a distant point outside the coordinate space;count the number of polygon edges that arecrossed
if odd => interior
if even => exteriorNote! The vertices!
7/13/2019 It Sem7 Cs2401nol
67/325
Text
Representation:* bitmapped (raster)
+ fast- more storage- less good forstyles/sizes
* outlined (lines andcurves)
+ less storage+ good for styles/sizes- slower
7/13/2019 It Sem7 Cs2401nol
68/325
Other output primitives
* pattern (to fill an area)
normally, an n x m rectangularcolor pixel array with a specifiedreference point
* polymarker (marker symbol)
a character representing a point
* (polyline)a connected sequence of line segments
7/13/2019 It Sem7 Cs2401nol
69/325
Attributes
Influence the way a primitive is displayed
Two main ways of introducing attributes:
1) added to primitives parameter liste.g. setPixel(x, y, color)
2) a list of current attributes (to be
updated when changed)e.g setColor(color); setPixel(x, y);
7/13/2019 It Sem7 Cs2401nol
70/325
Attributes for lines
Lines (and curves) are normally infinitely thin type
dashed, dotted, solid, dot-dashed,
pixel mask, e.g. 11100110011 width
problem with the joins; line caps are used to adjustshape
pen/brush shape color (intensity)
7/13/2019 It Sem7 Cs2401nol
71/325
Lines with width
Line caps
Joins
7/13/2019 It Sem7 Cs2401nol
72/325
Attributes for area fill
fill style hollow, solid, pattern, hatch fill,
color pattern
tiling
7/13/2019 It Sem7 Cs2401nol
73/325
Tiling
Tiling = filling surfaces (polygons) with arectangular pattern
7/13/2019 It Sem7 Cs2401nol
74/325
Attributes for characters/strings
style font (typeface) color size (width/height) orientation path
spacing alignment
7/13/2019 It Sem7 Cs2401nol
75/325
Text attributes
7/13/2019 It Sem7 Cs2401nol
76/325
Text attributes, contd
7/13/2019 It Sem7 Cs2401nol
77/325
Text attributes, contd
7/13/2019 It Sem7 Cs2401nol
78/325
Text attributes, contd
7/13/2019 It Sem7 Cs2401nol
79/325
Color as attribute
Each color has a numerical value, or intensity,based on some color model.
A color model typically consists of three primary
colors, in the case of displays Red, Green andBlue (RGB)For each primary color an intensity can be given,
either 0-255 (integer) or 0-1 (float) yielding the
final color256 different levels of each primary color means3x8=24 bits of information to store
7/13/2019 It Sem7 Cs2401nol
80/325
Color representations
Two different ways of storing a color value:
1) a direct color value storage/pixel
2) indirectly via a color look-up tableindex/pixel (typically 256 or 512different colors in the table)
7/13/2019 It Sem7 Cs2401nol
81/325
Color Look-up Table
7/13/2019 It Sem7 Cs2401nol
82/325
Antialiasing
Aliasing the fact that exact points are
approximated by fixed pixel positions
Antialiasing= a technique thatcompensates for this (more than oneintensity level/pixel is required)
7/13/2019 It Sem7 Cs2401nol
83/325
Antialiasing, a method
A polygon will be studied (as an example).
Area sampling(prefiltering): a pixel that is onlypartly included in the exact polygon, will begiven an intensity that is proportional to theextent of the pixel area that is covered by the
true polygon
7/13/2019 It Sem7 Cs2401nol
84/325
Area sampling
P = polygon intensity
B = background intensity
f = the extent of the pixel
area covered by the truepolygon
pixel intensity =
P*f + B*(1 - f)
Note!Time consuming tocalculate f
7/13/2019 It Sem7 Cs2401nol
85/325
Topics
Clipping
Cohen-Sutherland Line Clipping Algorithm
7/13/2019 It Sem7 Cs2401nol
86/325
Clipping
Why clipping? Not everything defined in the world
coordinates is inside the world window
Where does clipping take place?
OpenGL does it for you BUT, as a CS major, you should know how itis done.
Model ViewportTransformation
Clipping
7/13/2019 It Sem7 Cs2401nol
87/325
Line Clipping
int clipSegment(p1, p2, window)
Input parameters: p1, p2, windowp1, p2: 2D endpoints that define a line
window: aligned rectangle Returned value:
1, if part of the line is inside the window
0, otherwise
Output parameters: p1, p2p1 and/or p2s value might be changed so
that both p1 and p2 are inside the window
7/13/2019 It Sem7 Cs2401nol
88/325
Line Clipping
Example Line RetVal Output
AB
BC
CD
DE
EA
o P1
o P2
o P3
o P4
o P1
o P2o P3
o P4
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
89/325
Cohen-Sutherland Line Clipping
Algorithm
Trivial accept and trivial reject If both endpoints within window trivial accept
If both endpoints outside of same boundary ofwindow trivial reject Otherwise
Clip against each edge in turnThrow away clipped off part of line each time
How can we do it efficiently (elegantly)?
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
90/325
Cohen-Sutherland Line Clipping
Algorithm
Examples: trivial accept?
trivial reject?
window
L1
L2
L3
L4
L5
L6
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
91/325
Cohen-Sutherland Line Clipping
Algorithm
Use region outcode
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
92/325
Cohen-Sutherland Line Clipping
Algorithm
outcode[1] (x< Window.left)
outcode[2] (y> Window.top)
outcode[3] (x> Window.right)
outcode[4] (y< Window.bottom)
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
93/325
Cohen-Sutherland Line Clipping
Algorithm
Both outcodes are FFFF Trivial accept
Logical AND of two outcodes
FFFF Trivial reject Logical AND of two outcodes = FFFF
Cant tell
Clip against each edge in turnThrow away clipped off part of line each time
C h S th l d Li Cli i
7/13/2019 It Sem7 Cs2401nol
94/325
Cohen-Sutherland Line Clipping
Algorithm
Examples: outcodes?
trivial accept?
trivial reject?
window
L1
L2
L3
L4
L5
L6
Cohen S therland Line Clipping
7/13/2019 It Sem7 Cs2401nol
95/325
Cohen-Sutherland Line Clipping
Algorithm
int clipSegment(Point2& p1, Point2& p2, RealRect W)do
if(trivial accept) return 1;
else if(trivial reject) return 0;else
if(p1 is inside) swap(p1,p2)if(p1 is to the left) chop against the leftelse if(p1 is to the right) chop against the rightelse if(p1 is below) chop against the bottomelse if(p1 is above) chop against the top
while(1);
Cohen Sutherland Line Clipping
7/13/2019 It Sem7 Cs2401nol
96/325
Cohen-Sutherland Line Clipping
Algorithm
A segment that requires 4 clips
Cohen Sutherland Line Clipping
7/13/2019 It Sem7 Cs2401nol
97/325
Cohen-Sutherland Line Clipping
Algorithm How do we chop against each boundary?Given P1 (outside) and P2, (A.x,A.y)=?
Cohen Sutherland Line Clipping
7/13/2019 It Sem7 Cs2401nol
98/325
Cohen-Sutherland Line Clipping
Algorithm
Let dx = p1.x - p2.x dy = p1.y - p2.y
A.x = w.r d = p1.y - A.y e = p1.x - w.r
d/dy = e/dxp1.y - A.y = (dy/dx)(p1.x - w.r)
A.y = p1.y - (dy/dx)(p1.x - w.r)
= p1.y + (dy/dx)(w.r - p1.x)As A is the new P1
p1.y += (dy/dx)(w.r - p1.x)p1.x = w.r
Q: Will we havedivided-by-zeroproblem?
7/13/2019 It Sem7 Cs2401nol
99/325
UNIT-IITHREE-
DIMENSIONALCONCEPTS
7/13/2019 It Sem7 Cs2401nol
100/325
3D VIEWING
7/13/2019 It Sem7 Cs2401nol
101/325
3D Viewing-contents
Viewing pipelineViewing coordinatesProjections
View volumes and general projectiontransformations
clipping
7/13/2019 It Sem7 Cs2401nol
102/325
3D Viewing
World coordinate system(where theobjects are modeled and defined)
Viewing coordinate system(viewing objects
with respect to another user defined coordinatesystem) Scene coordinate system(a viewing
coordinate system chosen to be at the centre
of a scene) Object coordinate system(a coordinate
system specific to an object.)
7/13/2019 It Sem7 Cs2401nol
103/325
3D viewing
Simple camera analogy is adopted
7/13/2019 It Sem7 Cs2401nol
104/325
3D viewing-pipeline
7/13/2019 It Sem7 Cs2401nol
105/325
3D viewing
Defining the viewing coordinate system andspecifying the view plane
7/13/2019 It Sem7 Cs2401nol
106/325
3D viewing
First pick up a world coordinate positioncalled the view reference point. This is the origin
of the VC systemPick up the +ve direction for the Zv axis
and the orientation of the view plane byspecifying the view plane normal vector N.
Choose a world coordinate position andthis point establishes the direction for N relativeto either the world or VC origin. The view planenormal vector is the directed line segment.
steps to establish a Viewing coordinate systemor view referencecoordinate system and the view plane
7/13/2019 It Sem7 Cs2401nol
107/325
3D viewing
steps to establish a Viewing coordinate systemor view reference coordinatesystem and the view plane
Some packages allow us to choose a look at
point relative to the view reference point.Or set up a Left handed viewing system and
take the N and the +ve Zv axis from the viewingorigin to the look- at point.
7/13/2019 It Sem7 Cs2401nol
108/325
3D viewing
steps to establish a Viewing coordinate systemor view referencecoordinate system and the view plane
We now choose the view up vector V. It can
be specified as a twist angle about Zv axis.Using N,V U can be specified.
Generally graphics packages allow users tochoose a position of the view plane along the Zv axisby specifying the view plane distance from theviewing origin.
The view plane is always parallel to the XvYvplane.
7/13/2019 It Sem7 Cs2401nol
109/325
3D viewing
To obtain a series of views of a scene we
can keep the view reference point fixed and changethe direction of N or we can fix N direction and movethe view reference point around the scene.
Transformation from world to viewing coordinate system
7/13/2019 It Sem7 Cs2401nol
110/325
3D viewing
(a)
Invert Viewing
z Axis
(b)
Translate Viewing
Origin to World Origin
(c)
Rotate About World x Axis
to Bring Viewing z Axis into
the xz Plane of the World System
(d)
Rotate About the World
y Axis to Align
the Two z Axes
(e)
Rotate About the World
z Axis to Align the Two
Viewing Systems
wx
w
y
wz
wx
wy
wz
wx
wy
wz
wx
wy
wz
wx
wy
wz
vx vy
vz
vz
vyvx
vx
vy
vz v
z
vx
vy
vz
vy
vx
Transformation from world to viewing coordinate system
Mwc,vc=RzRyRx.T
7/13/2019 It Sem7 Cs2401nol
111/325
What Are Projections?
Picture Plane
Objects in
World Space
Our 3-D scenes are all specified in 3-D world coordinatesTo display these we need to generate a 2-D image -projectobjectsonto apicture plane
7/13/2019 It Sem7 Cs2401nol
112/325
Converting From 3-D To 2-D
Projection is just one part of the process of converting from 3-Dworld coordinates to a 2-D image
Clip againstview volume
Project ontoprojection
plane
Transform to2-D devicecoordinates
3-D worldcoordinateoutput
primitives
2-D devicecoordinates
7/13/2019 It Sem7 Cs2401nol
113/325
Types Of Projections
There are two broad classes ofprojection:Parallel: Typically used for architectural and engineering
drawingsPerspective: Realistic looking and used in computer graphics
Perspective ProjectionParallel Projection
7/13/2019 It Sem7 Cs2401nol
114/325
Taxonomy Of Projections
7/13/2019 It Sem7 Cs2401nol
115/325
Types Of Projections
There are two broad classes of projection: Parallel:
preserves relative proportions of objects
accurate views of various sides of an object can be obtaineddoes not give realistic representations of the appearance of a3D objective.
Perspective:produce realistic views but does not preserve relative
proportionsprojections of distant objects are smaller than the projectionsof objects of the same size that are closer to the projectionplane.
7/13/2019 It Sem7 Cs2401nol
116/325
Parallel Projections
Some examples of parallel projections
Orthographic Projection(axonometric)
Orthographic oblique
7/13/2019 It Sem7 Cs2401nol
117/325
Parallel Projections
Some examples of parallel projections
Isometric projection for a cube
The projectionplane is aligned so that itintersects each coordinateaxes in which the object isdefined (principal axes) atthe same distance from theorigin.
All the principalaxes are foreshortenedequally.
7/13/2019 It Sem7 Cs2401nol
118/325
Parallel Projections
Transformation equations for an orthographic parallel projections is simple
Any point (x,y,z) in viewing coordinates is transformed to projectioncoordinates as
Xp=X Yp=Y
7/13/2019 It Sem7 Cs2401nol
119/325
Parallel Projections
Transformation equations for oblique projections is as below.
Oblique projections
11000
0000
0sin10
0cos01
1
1
z
y
x
L
L
w
z
y
x
p
p
p
p
7/13/2019 It Sem7 Cs2401nol
120/325
Parallel Projections
Transformation equations for oblique projections is as below.
Oblique projections
11000
0000
0sin10
0cos01
1
1
z
y
x
L
L
w
z
y
x
p
p
p
p
An orthographic projection isobtained when L1=0.
In fact the effect of the projectionmatrix is to shear planes ofconstant Z and project them on tothe view plane.
Two common oblique parallel projections:
Cavalierand Cabinet
7/13/2019 It Sem7 Cs2401nol
121/325
Parallel Projections Oblique projections
2 common oblique parallel projections:Cavalier projection
45
1tan
Cabinet projection
4.63
2tan
All lines perpendicular to the projectionplane are projected with no change inlength.
They are more realistic than cavaliarLines perpendicular to the viewingsurface are projected at one-half theirlength.
7/13/2019 It Sem7 Cs2401nol
122/325
Perspective Projections
visual effect is similar to human visual system...has 'perspective foreshortening
size of object varies inversely with distance from the center of projection.
angles only remain intact for faces parallel to projection plane.
7/13/2019 It Sem7 Cs2401nol
123/325
Perspective Projections
Where u varies from o to 1
7/13/2019 It Sem7 Cs2401nol
124/325
Perspective Projections
7/13/2019 It Sem7 Cs2401nol
125/325
Perspective Projections
If the view plane is the UV plane itself then Zvp=0.
The projection coordinates become
Xp=X(Zprp/(Zprp-Z))=X(1/(1-Z/Zprp))
Yp=Y(Zprp/(Zprp-Z))=Y(1/(1-Z/Zprp))
If the PRP is selected atthe viewing cooridinateorigin then Zprp=0
The projection coordinates
become
Xp=X(Zvp/Z)
Yp=Y(Zvp/Z)
7/13/2019 It Sem7 Cs2401nol
126/325
Perspective Projections
There are a number of different kinds of perspective views
The most common are one-point and two point perspectives
One-point perspectiveprojection
Two-point perspectiveprojection
Coordinate description
7/13/2019 It Sem7 Cs2401nol
127/325
Perspective Projections
Parallel lines that are parallel to the view plane areprojected as parallel lines. The point at which a set of projectedparallel lines appear to converge is called a vanishing point.
If a set of lines are parallel to one of the three principle
axes, the vanishing point is called anprincipal vanishing point.There are at most 3 such points, corresponding to the number of
axes cut by the projection plane.
7/13/2019 It Sem7 Cs2401nol
128/325
View volume
7/13/2019 It Sem7 Cs2401nol
129/325
View volume
Perspective projectionParallelprojection
The size of the view volume depends on the size of the window but theshape depends on the type of projection to be used.
Both near and far planes must be on the same side of the referencepoint.
7/13/2019 It Sem7 Cs2401nol
130/325
View volume
Often the view plane is positioned at the view reference point or on the
front clipping plane while generating parallel projection.Perspective effects depend on the positioning of the projectionreference point relative to the view plane
View volume - PHIGS
7/13/2019 It Sem7 Cs2401nol
131/325
VPN
B
F
Front
Clipping
Plane
View
Plane
Back
Clipping
Plane
Direction of
Propagation
VPN
Front
Clipping
Plane
View
Plane
Back
Clipping
Plane
BF
VRP
VRP
Direction of
Propagation
VPNFront
Clipping
Plane
View
Plane
BackClipping
Plane
BF
VRP
7/13/2019 It Sem7 Cs2401nol
132/325
View volume
In an animation sequence, we canplace the projection reference point at theviewing coordinate origin and put the viewplane in front of the scene.
We set the field of view byadjusting the size of the window relative tothe distance of the view plane from thePRP.
We move through the scene by
moving the viewing reference frame andthe PRP will move with the view referencepoint.
General parallel projection
7/13/2019 It Sem7 Cs2401nol
133/325
N
Direction of
Projection
N
Near
Plane
FarPlane
Window
(a)
Original Orientation
(b)
After Shearing
Direction ofProjection
Window
Near
Plane
Far
Plane
View
Volume
ViewVolume
Paralleltransformation
General parallel projection
7/13/2019 It Sem7 Cs2401nol
134/325
transformation
),0,0(:),,(: ccba
c
bbbcb
caaaca
cc
b
a
b
a
11
11
1
1
0
0
0
0
0
01000
0100
010
001
ShearingLet Vp=(a,b,c) be the projectionvector in viewing coordinates.
The shear transformation can
be expressed asVp=Mparallel.Vp
Where Mparallelis
For an orthographic parallel
projection Mparallel becomes theidentity matrix since a1=b1=0
Parallel
Regularization of Clipping
General perspective projectiontransformation
7/13/2019 It Sem7 Cs2401nol
135/325
Perspective
N N
View
VolumeView
Volume
Far
Near
Window
Far
Near
Window
Center of
Projection
Center of
Projection
(a)
Original Orientation
(b)
After TransformationShearing
g pp g
(View) Volume (Cont)
General perspective projection
7/13/2019 It Sem7 Cs2401nol
136/325
transformation Perspective
Steps
1. Shear the view volume so that thecenterline of the frustum isperpendicular to the view plane
2. Scale the view volume with ascaling factor that depends on 1/z.
A shear operation is to align a generalperspective view volume with theprojection window.
The transformation involves acombination of z-axis shear and atranslation.
Mperspective=Mscale.Mshear
7/13/2019 It Sem7 Cs2401nol
137/325
Clipping
View volume clipping boundaries are planes whoseorientations depend on the type of projection, the projectionwindow and the position of the projection reference point
The process of finding the intersection of a line with oneof the view volume boundaries is simplified if we convert the view
volume before clipping to a rectangular parallelepiped.i.e we first perform the projection transformation which
converts coordinate values in the view volume to orthographicparallel coordinates.
Oblique projection view volumes are converted to arectangular parallelepiped by the shearing operation andperspective view volumes are converted with a combination ofshear and scale transformations.
Clipping-normalized view
7/13/2019 It Sem7 Cs2401nol
138/325
volumes
The normalized view volume is a region defined by the planes
X=0, x=1, y=0, y=1, z=0, z=1
Clipping-normalized view
7/13/2019 It Sem7 Cs2401nol
139/325
volumes
There are several advantages to clipping against theunit cube
1. The normalized view volume provides a standardshape for representing any sized view volume.
2. Clipping procedures are simplified and standardizedwith unit clipping planes or the viewport planes.
3. Depth cueing and visible-surface determination aresimplified, since Z-axis always points towards theviewer.
Unit cube
3D viewport
Mapping positions within a rectangularview volume to a three-dimensionalrectangular viewport is accomplishedwith a combination of scaling andtranslation.
Clipping-normalized view
7/13/2019 It Sem7 Cs2401nol
140/325
volumes
Unit cube
3D viewport
Mapping positions within arectangular view volume to athree-dimensional rectangularviewport is accomplished with a
combination of scaling andtranslation.
Dx 0 0 Kx
0 Dy 0 Ky
0 0 Dz Kz0 0 0 1
Where
Dx=(xvmax-xvmin)/(xwmax-xwmin) and Kx= xvmin- xwmin Dx
Dy= (yvmax-yvmin)/(ywmax-ywmin) and Ky= yvmin - ywmin Dy
Dz= (zv
max-zv
min)/(zw
max-zw
min) and K
z= zv
min- zw
minD
z
7/13/2019 It Sem7 Cs2401nol
141/325
Viewport clipping
For a line endpoint at position(x,y,z) we assign the bit positionsin the region code from right to leftas
Bit 1 = 1 if x< xvmin (left)Bit 1 = 1 if x< xvmax (right)
Bit 1 = 1 if y< yvmin (below)
Bit 1 = 1 if y< yvmax (above)
Bit 1 = 1 if z< zvmin (front)
Bit 1 = 1 if z< zvmax (back)
7/13/2019 It Sem7 Cs2401nol
142/325
Viewport clipping
For a line segment with endpointsP1(x1,y1,z1) and P2(x2,y2,z2) theparametric equations can be
X=x1+(x2-x1)u
Y=y1+(y2-y1)u
Z=z1+(z2-z1)u
7/13/2019 It Sem7 Cs2401nol
143/325
Hardware implementations
WORLD-COORDINATE
Object descriptions
Transformation Operations
Clipping Operations
Conversion to Device Coordinates
3D Transformations
7/13/2019 It Sem7 Cs2401nol
144/325
2D coordinates 3D coordinates
x
y
x
y
z
xz
y
Right-handed coordinate system:
3D Transformations (cont )
7/13/2019 It Sem7 Cs2401nol
145/325
1. Translation in 3D is a simple extension from that in 2D:
2. Scaling is similarly extended:
1000
100
010
001
),,(z
y
x
zyxd
d
d
dddT
1000
000000
000
),,(z
y
x
zyxs
s
s
sssS
3D Transformations (cont )
7/13/2019 It Sem7 Cs2401nol
146/325
3. The 2D rotation introduced previously is just a 3D rotation aboutthe zaxis.
similarly we have:X
Y
Z
1000
0100
00cossin
00sincos
)(
zR
1000
0cossin00sincos0
0001
)(xR
1000
0cos0sin0010
0sin0cos
)(
yR
Composition of 3D Rotations
7/13/2019 It Sem7 Cs2401nol
147/325
In 3D transformations, the order of a sequence of rotations matters!
1000
0cos0sin
0sinsincoscossin
0sincossincoscos
1000
0cos0sin
0010
0sin0cos
1000
0100
00cossin
00sincos
)()(
yz RR
1000
0cossinsincossin
00cossin
0sincossincoscos
1000
0100
00cossin
00sincos
1000
0cos0sin
0010
0sin0cos
)()(
zy RR
)()()()( yzzy RRRR
More Rotations
7/13/2019 It Sem7 Cs2401nol
148/325
We have shown how to rotate about one of the principle axes, i.e. the
axes constituting the coordinate system. There are more we can do,
for example, to perform a rotation about an arbitrary axis:
X
Y
Z
P2(x2, y2 , z2)
P1(x1, y1 , z1)
We want to rotate an object about anaxis in space passing through (x1, y1, z1)
and (x2, y2, z2).
Rotating About An Arbitrary Axis
7/13/2019 It Sem7 Cs2401nol
149/325
Y
Z
P2
P1
1). Translate the object by (-x1, -y1, -z1): T(-x1, -y1, -z1)
X
Y
Z P2
P1
2). Rotate the axis aboutx sothat it lies on thexzplane: Rx()
X
X
Y
Z P2
P1
3). Rotate the axis about y so
that it lies on z: Ry ()
X
Y
ZP2
P1
4). Rotate object about z by : Rz()
Rotating About An Arbitrary Axis (cont )
7/13/2019 It Sem7 Cs2401nol
150/325
After all the efforts, dont forget to undo the rotations and the translation!
Therefore, the mixed matrix that will perform the required task of rotating an
object about an arbitrary axis is given by:
M= T(x1,y1,z1) Rx(-)Ry(-) Rz() Ry() Rx()T(-x1,-y1,-z1)
Finding is trivial, but what about ?
The angle between the zaxis and the
projection of P1 P2on yzplane is .
X
Y
Z
P2
P1
7/13/2019 It Sem7 Cs2401nol
151/325
Composite 3DTransformations
Example of Composite 3D Transformations
7/13/2019 It Sem7 Cs2401nol
152/325
Try to transform the line segments P1P2and P1P3from their start position in (a)
to their ending position in (b).
The first solution is to compose the primitive transformations T, Rx
, Ry
, and Rz
.This approach is easier to illustrate and does offer help on building anunderstanding. The 2nd, more abstract approach is to use the properties ofspecial orthogonal matrices.
y
x
z
y
x
z
P1 P2
P3
P1
P2
P3
(a) (b)
Composition of 3D Transformations
7/13/2019 It Sem7 Cs2401nol
153/325
Breaking a difficult problem into simpler sub-problems:
1.Translate P1to the origin.2. Rotate about the yaxis such that P1P2lies in the (y, z) plane.3. Rotate about thexaxis such that P1P2lies on the zaxis.4. Rotate about the zaxis such that P1P3lies in the (y, z) plane.
y
xz
y
xz
y
xz
P1 P2
P3
P1
P2
P3
y
xz
P1 P2
P3
y
xz
P1P2
P3P3
P2 P1
1
2
34
Composition of 3D Transformations
7/13/2019 It Sem7 Cs2401nol
154/325
1.
2.
1000
100
010
001
),,(
1
1
1
111
z
y
x
zyxT
1000
0sin0cos
0010
0cos0sin
))90((
yR
T
T
T
zzyyxxPzyxTP
zzyyxxPzyxTP
PzyxTP
]1[),,(
]1[),,(
]1000[),,(
1313133111
'
3
1212122111
'
2
1111
'
1
y
xz
P1 P2P3
D1
Composition of 3D Transformations
7/13/2019 It Sem7 Cs2401nol
155/325
3
4.
1000
0cossin0
0sincos0
0001
)(
xRy
xz
P1P2 D2
y
xz
P 1P 2
D3
P 3
)(zR
TRzyxTRRR yxz ),,()90()()( 111Finally, we have the composite matrix:
Vector Rotation
7/13/2019 It Sem7 Cs2401nol
156/325
x
y
x
y
Rotate the vecto r
0
1
u
sincos
01
cossinsincosu
The unit vector along thexaxis is [1, 0]T. After rotating about the origin by, the resulting vector is
Vector Rotation (cont )
7/13/2019 It Sem7 Cs2401nol
157/325
x
y
Rotate the vecto r
1
0
cos
sin
1
0
cossin
sincosv
x
y
v
The above results states that if we try to rotate a vector, originally pointing thedirection of thex (or y)axis, toward a new direction, u (or v), the rotation matrix,R, could be simply written as [u | v] without the need of any explicit knowledgeof , the actual rotation angle.
Similarly, the unit vector along the yaxis is [0, 1]T
. After rotating about theorigin by , the resulting vector is
Vector Rotation (cont )
7/13/2019 It Sem7 Cs2401nol
158/325
The reversed operation of the above rotation is to rotate a vector that is not
originally pointing thex(or y) direction into the direction of the positivexor yaxis. The rotation matrix in this case is R(-), expressed by R-1()
where Tdenotes the transpose.
)(cossin
sincos
)cos()sin(
)sin()cos()(1
T
T
T
Rv
uR
x x
yy
Rotate the vecto ruu
Example
7/13/2019 It Sem7 Cs2401nol
159/325
what is the rotation matrix if one wants the vector Tin the left figure to be
rotated to the direction of u.
T
(2, 3)
TT
u
u
13
3
13
2
32
32
|| 22
13
2
13
313
3
13
2
| vuR
If, on the other hand, one wants the vector uto be rotated to the direction ofthe positivexaxis, the rotation matrix should be
13
2
13
313
3
13
2
T
T
v
uR
Rotation Matrices
7/13/2019 It Sem7 Cs2401nol
160/325
Rotation matrix is or thonormal:
Each row is a unit vector
Each row is perpendicular to the other, i.e. their dot product is zero.
Each vector will be rotated by R() to lie on the positivex and yaxes,respectively. The two column vectors are those into which vectorsalong the positivexand yaxes are rotated.
For orthonormal matrices, we have
1sincos
1)sin(cos
cossin
sincos22
22
R
0)sin(cossincos
)()(1 TRR
Cross Product
7/13/2019 It Sem7 Cs2401nol
161/325
The cross produc torvector product of two vectors, v1and v2, is
another vector:
The cross product of two vectors is orthogonal to both Right-hand rule dictates direction of cross product.
1221
1221
1221
21 )(
yxyx
zxzx
zyzy
vv
v1
v2v1v2
Extension to 3D Cases
7/13/2019 It Sem7 Cs2401nol
162/325
u2
The above examples can be extended to 3D cases.
In 2D, we need to know u, which will be
rotated to the direction of the positivexaxis.uv
x
y
z u1
v=u1u2
In 3D, however, we need to know more than
one vector. See in the left figure, for example,
two vectors, u1and u2are given. If after
rotation, u1is aligned to the positive zaxis, this
will only give us the third column in the rotation
matrix. What about the other two columns?
3D Rotation
7/13/2019 It Sem7 Cs2401nol
163/325
In many cases in 3D, only one vector will be aligned to one of the
coordinate axes, and the others are often not explicitly given. Lets see theexample:y
x
z
y
x
z
P1 P2
P3
P1
P2
P3
Note, in this example, vector P1P2 will be
rotated to the positive zdirection. Hence the
fist columnvector in the rotation matrix is the
normalised P1P2. But what about the other
two columns? After all, P1P3is not perpendi-
cular to P1P2. Well, we can find it by taking
the cross product of P1P2and P1P3. Since
P1P2 P1P3is perpendicular to both P1P2
and P1P3, it will be aligned into the direction
of the positivexaxis.
3D Rotation (cont )y
7/13/2019 It Sem7 Cs2401nol
164/325
And the third direction is decide by the cross
product of the other two directions, which is
P1P2(P1P2P1P2 ).
Therefore, the rotation matrix should be
u
y
xz
P1
P2
P3v
w
21
21
312121
312121
3121
3121
)(
)(
PPPP
PPPPPP
PPPPPP
PPPPPPPP
R
y
x
z
P1P2
P3
u
v
Yaw, Pitch, and Roll
7/13/2019 It Sem7 Cs2401nol
165/325
Imagine three lines running through an airplane and intersecting atright angles at the airplanes centre of gravity.
Roll: rotation around the
front-to-back axis.
Roll: rotation around the
side-to-side axis.
Roll: rotation around the
vertical axis.
An Example of the Airplane
7/13/2019 It Sem7 Cs2401nol
166/325
Consider the following example. An airplane is oriented such that its nose is
pointing in the positive zdirection, its right wing is pointing in the positivexdirection, its cockpit is pointing in the positive ydirection. We want totransform the airplane so that it heads in the direction given by the vectorDOF(direction of flight), is centre at P,and is not banked.
Solution to the Airplane Example
7/13/2019 It Sem7 Cs2401nol
167/325
First we are to rotate the positive zpdirection into the direction of DOF,
which gives us the third column of the rotation matrix: DOF / |DOF|. Thexpaxis must be transformed into a horizontal vector perpendicular to DOFthat is in the direction of yDOF. The ypdirection is then given byxpzp=DOF (y DOF).
DOF
DOF
DOFyDOF
DOFyDOF
DOFy
DOFyR
)(
)(
Inverses of (2D and) 3D Transformations
7/13/2019 It Sem7 Cs2401nol
168/325
1. Translation:
2. Scaling:
3. Rotation:
4. Shear:
),,(),,(1 zyxzyx dddTdddT
)1
,1
,1
(),,(1
zyx
zyxsss
SsssS
)()()(1 TRRR
),(),(1 yxyx shshSHshshSH
7/13/2019 It Sem7 Cs2401nol
169/325
UNIT-III
GRAPHICS
PROGRAMMING
7/13/2019 It Sem7 Cs2401nol
170/325
Color Models
Color models,contd
7/13/2019 It Sem7 Cs2401nol
171/325
Different meanings of color:
painting
wavelength of visible light
human eye perception
Physical properties of light
7/13/2019 It Sem7 Cs2401nol
172/325
Visible light is part of the electromagnetic radiation (380-750 nm)
1 nm (nanometer) = 10-10m (=10-7cm)
1 (angstrom) = 10 nm
Radiation can be expressed in wavelength () orfrequency (f), c=f, where c=3.1010cm/sec
Physical properties of light
7/13/2019 It Sem7 Cs2401nol
173/325
White light consists ofa spectrum of allvisible colors
Physical properties of light
7/13/2019 It Sem7 Cs2401nol
174/325
All kinds of light can bedescribed by theenergy of eachwavelength
The distributionshowing the relationbetween energy andwavelength (or
frequency) is calledenergy spectrum
Physical properties of light
7/13/2019 It Sem7 Cs2401nol
175/325
This distribution may indicate:
1) a dominant wavelength (or frequency)which is the color of the light (hue), cp.ED
2) brightness (luminance), intensity of thelight (value), cp. the area A
3) purity (saturation), cp. ED- EW
Physical properties of light
7/13/2019 It Sem7 Cs2401nol
176/325
Energy spectrum for a light source with adominant frequency near the red color
Material properties
7/13/2019 It Sem7 Cs2401nol
177/325
The color of an object depends on the socalled spectral curvesfor transparencyand reflection of the material
The spectral curves describe how light ofdifferent wavelengths are refracted andreflected (cp. the material coefficients
introduced in the illumination models)
Properties of reflected light
7/13/2019 It Sem7 Cs2401nol
178/325
Incident white light upon an object is forsome wavelengths absorbed, for othersreflected
E.g. if all light is absorbed => blackIf all wavelengths but one are absorbed =>
the one color is observed as the color ofthe object by the reflection
Color definitions
7/13/2019 It Sem7 Cs2401nol
179/325
Complementary colors- two colorscombine to produce white light
Primary colors- (two or) three colors used
for describing other colorsTwo main principles for mixing colors:
additive mixing
subtractive mixing
Additive mixing
7/13/2019 It Sem7 Cs2401nol
180/325
pure colors are put close to each other => a mix on theretina of the human eye (cp. RGB)
overlapping gives yellow, cyan, magenta and white
the typical technique on color displays
Subtractive mixing
7/13/2019 It Sem7 Cs2401nol
181/325
color pigments are mixed directly in someliquid, e.g. ink
each color in the mixture absorbs its specific
part of the incident light the color of the mixture is determined by
subtraction of colored light, e.g. yellow absorbsblue => only red and green, i.e. yellow, will
reach the eye (yellow because of addition)
Subtractive mixing,contd
7/13/2019 It Sem7 Cs2401nol
182/325
primary colors: cyan, magenta andyellow, i.e. CMY
the typical technique in printers/plotters
connection between additive andsubtractive primary colors (cp. the colormodels RGB and CMY)
Additive/subtractive mixing
7/13/2019 It Sem7 Cs2401nol
183/325
Human color seeing
7/13/2019 It Sem7 Cs2401nol
184/325
The retina of the human eye consists of cones(7-8M),tappar, and rods(100-120M), stavar,which are connected with nerve fibres to the
brain
Human color seeing,contd
7/13/2019 It Sem7 Cs2401nol
185/325
Theory: the cones consist of various lightabsorbing material
The light sensitivity of the cones and rods varieswith the wavelength, and between persons
The sum of the energy spectrum of the light the reflection spectrum of the object
the response spectrum of the eyedecides the color perception for a person
Overview of color models
7/13/2019 It Sem7 Cs2401nol
186/325
The human eye can perceive about 382000(!)different colors
Necessary with some kind of classification sys-tem; all using three coordinates as a basis:
1) CIE standard2) RGB color model3) CMY color model (also, CMYK)
4) HSV color model5) HLS color model
CIE standard
7/13/2019 It Sem7 Cs2401nol
187/325
CommissionInternationale deLEclairage (1931)
not a computermodel
each color = aweighted sum of
three imaginaryprimary colors
RGB model
7/13/2019 It Sem7 Cs2401nol
188/325
all colors aregenerated from thethree primaries
various colors areobtained bychanging the amountof each primary
additive mixing(r,g,b), 0r,g,b1
RGB model,contd
7/13/2019 It Sem7 Cs2401nol
189/325
the RGB cube 1 bit/primary => 8 colors, 8 bits/primary => 16M colors
CMY model
7/13/2019 It Sem7 Cs2401nol
190/325
cyan, magenta andyellow are comple-mentary colors ofred,green and blue,
respectively subtractive mixing the typical printer
technique
CMY model,contd
7/13/2019 It Sem7 Cs2401nol
191/325
almost the samecube as with RGB;only black white
the various colorsare obtained byreducing light, e.g. ifred is absorbed =>
green and blue areadded, i.e cyan
RGB vs CMY
7/13/2019 It Sem7 Cs2401nol
192/325
If the intensities are represented as 0r,g,b1
and 0c,m,y1 (also coordinates 0-255 can beused), then the relation between RGB andCMY can be described as:
c
my
1
11
r
gb
CMYK model
7/13/2019 It Sem7 Cs2401nol
193/325
For printing and graphics art industry, CMYis not enough; a fourth primary, K whichstands for black, is added.
Conversions between RGB and CMYK arepossible, although they require someextra processing.
HSV model
7/13/2019 It Sem7 Cs2401nol
194/325
HSV stands for Hue-Saturation-Value
described by a hexcone derived from the RGBcube
HSV model,contd
7/13/2019 It Sem7 Cs2401nol
195/325
Hue (0-360); thecolor, cp. thedominant wave-length (128)
Saturation (0-1); theamount of white(130)
Value (0-1); theamount of black (23)
HSV model,contd
7/13/2019 It Sem7 Cs2401nol
196/325
The numbers given after each primary are
estimates of how many levels a human beingis capable to distinguish between, which (intheory) gives the total number of colornuances:
128*130*23 = 382720
In Computer Graphics, usually enough with:
128*8*15 = 16384
HLS model
7/13/2019 It Sem7 Cs2401nol
197/325
Another model similarto HSV
L stands for Lightness
Color models
7/13/2019 It Sem7 Cs2401nol
198/325
Some more facts about colors:
The distance between two colors in thecolor cube is not a measure of how far
apart the colors are perceptionally!Humans are more sensitive to shifts in
blue (and green?) than, for instance, in
yellow
7/13/2019 It Sem7 Cs2401nol
199/325
COMPUTER
ANIMATIONS
Computer Animations
7/13/2019 It Sem7 Cs2401nol
200/325
Any time sequence of visual changes in a scene. Size, color, transparency, shape, surface texture, rotation,
translation, scaling, lighting effects, morphing, changing cameraparameters(position, orientation, and focal length), particle animation.
Design of animation sequences: Storyboard layout Object definitions Key-frame specifications generation of in-between frames
Computer Animations
7/13/2019 It Sem7 Cs2401nol
201/325
Frame by frame animation Each frame is separately generated.
Object defintion
Objects are defined interms of basic shapes, such as
polygons or splines. In addition the associated movements foreach object are specified along with the shape.
Storyboard
It is an outline of the action
Keyframe Detailed drawing of the scene at a particular instance
Computer Animations
7/13/2019 It Sem7 Cs2401nol
202/325
Inbetweens Intermediate frames (3 to 5 inbetweens for each two key
frames) Motions can be generated using 2D or 3D transformation
Object parameters are stored in database Rendering algorithms are used finally Raster animations: Uses raster operations. Ex: we can animate objects along 2D motion paths using
the color table transformations. Here we predefine the object atsuccessive positions along the motion path, and set thesuccessive blocks of pixel values to color table entries
Computer Animations
7/13/2019 It Sem7 Cs2401nol
203/325
Computer animation languages:A typical task in animation specification is
Scene descriptionincludes position of objects and lightsources, defining the photometric parameters and setting the
camera parameters. Action specificationthis involves layout of motion paths for the
objects and camera. We need viewing and perspectivetransformations, geometric transformations, visible surfacedetection, surface rendering, kinematics etc.,
Keyframe systemsdesigned simply to generate the in-betweens from the user specified key frames.
Computer Animations
7/13/2019 It Sem7 Cs2401nol
204/325
Computer animation languages:A typical task in animation specification is Parameterized systemsallow object motion characteristics to be
specified as part of the object definitions. The adjustableparameters control such object charateristics as degrees offreedom, motion limitations and allowable shape changes.
Scripting systems allow object specifications and animation sequences to be defined with a user-input script. From the script a library of various objects and motions can be constructed.
Computer Animations
7/13/2019 It Sem7 Cs2401nol
205/325
Interpolation techniques Linear
Computer Animations
7/13/2019 It Sem7 Cs2401nol
206/325
Interpolation techniques Non-linear
Computer Animations
7/13/2019 It Sem7 Cs2401nol
207/325
Key frame systems MorphingTransformation of object shapes from one form to another is
called morphing.
Given two keyframes for an object transformation, we first adjust theobject specification in one of the frames so that number of polygon edges
or vertices is the same for the two frames. Let Lk,Lk+1denote the number of line segments in two different frames
K,K+1
Let us define
Lmax
=max(Lk,L
k+1)
Lmin=min(Lk,Lk+1)
Ne= Lmax mod LminNs= int(Lmax / Lmin)
1
2
3
2
1
Key frame K Key frame K+1
Computer Animations
7/13/2019 It Sem7 Cs2401nol
208/325
Steps
1. Dividing Needges of keyframemin into Ns+1 sections
2. Dividing the remaining lines of keyframemin into Nssections
1
2
3
2
1
Key frame K Key frame K+1
Computer Animations
7/13/2019 It Sem7 Cs2401nol
209/325
Key frame systems MorphingTransformation of object shapes from one form to another is
called morphing. If we equalize the vertex count, then the similar analysis follows Let Vk,Vk+1denote the number of vertices in two different frames K,K+1 Let us define Vmax=max(Lk,Lk+1) Vmin=min(Lk,Lk+1) Nls= (Vmax1)mod (Vmin1)
Np= int((Vmax1)/ (Vmin1) Steps
1. adding Nppoints to Nlsline sections of keyframemin sections 2. Adding Np-1 points to the remaining edges of keyframemin
Computer Animations
7/13/2019 It Sem7 Cs2401nol
210/325
Simulating accelerations Curve fitting techniques are often used to specify the animation paths
between keyframes. To simulate accelerations we can adjust the time spacing for the in-
betweens. For constant speed we use equal interval time spacing for the
inbetweens. suppose we want n in-betweens for keyframes at times t1 and t2.
The time intervals between key frames is then divided into n+1 subintervals, yielding an in-between spacing of
t = t2-t1/(n+1) We can calculate the time for in-betweens as tBj=t1+j t for j=1,2,.,n
t
Computer Animations
7/13/2019 It Sem7 Cs2401nol
211/325
Simulating accelerations To model increase or decrease in speeds we use trignometric functions. To model increasing speed, we want the time spacing between frames to
increase so that greater changes in position occur as the object moves faster. We can obtain increase in interval size with the function 1-cos, 0<
7/13/2019 It Sem7 Cs2401nol
212/325
Simulating deccelerations To model increase or decrease in speeds we use trignometric functions. To model decreasing speed, we want the time spacing between
frames to decrease. We can obtain increase in interval size with thefunction
sin, 0<
7/13/2019 It Sem7 Cs2401nol
213/325
Simulating both accelerations and deccelerations To model increase or decrease in speeds we use trignometric functions.
A combination of increasing and decreasing
speeds can be modeled using
(1-cos) 0<
7/13/2019 It Sem7 Cs2401nol
214/325
Motion specifications Direct motion specifications
Here we explicitly give the rotation angles and translation vectors.Then the geometric transformation matrices are applied to transformcoordinate positions.
A bouncing ball can be approximated by a sine curve y(x)=AI(sin(x+0)Ie
-kx
A is the initial amplitude
is the angular frequency
0 is the phase angle K is the damping constant
Computer Animations
7/13/2019 It Sem7 Cs2401nol
215/325
Motion specifications Goal directed systems
We can specify the motions that are to take place in general termsthat abstractly describe the actions, because they determine specificmotion paramters given the goals of the animation.
Computer Animations
7/13/2019 It Sem7 Cs2401nol
216/325
Motion specifications Kinematics Kinematic specification
of of a motion can also begiven by simply describingthe motion path which isoften done using splines.
In inverse kinematicswe specify the intital andfinal positions of objects atspecified times and the
motion parameters arecomputed by the system.
Computer Animations
7/13/2019 It Sem7 Cs2401nol
217/325
Motion specifications dynamics
specification of the forces that produce the velocities andaccelerations. Descriptions of object behavior under the influence offorces are generally referred to as a Physically based modeling (.rigidbody systems and non rigid systems such as cloth or plastic)
Ex: magnetic, gravitational, frictional etc
We can also use inverse dynamics to obtain the forces, given the initialand final position of objects and the type of motion.
Computer Animations
7/13/2019 It Sem7 Cs2401nol
218/325
Ideally suited for:Large volumes of objectswind effects, liquid
Cloth animation/draping
Underlying mechanisms are usually:
Particle systems
Mass-spring systems
Physics based animations
Computer Animations
7/13/2019 It Sem7 Cs2401nol
219/325
Physics based animations
Computer Animations
7/13/2019 It Sem7 Cs2401nol
220/325
Physics based animations
Computer Animations
7/13/2019 It Sem7 Cs2401nol
221/325
Some more animationtechniques.
Anticipation and Staging
Computer Animations
7/13/2019 It Sem7 Cs2401nol
222/325
Some more animationtechniques.
Secondary Motion
Computer Animations
7/13/2019 It Sem7 Cs2401nol
223/325
Some more animationtechniques.
Motion Capture
7/13/2019 It Sem7 Cs2401nol
224/325
Computer Graphicsusing OpenGL
Initial Steps in Drawing Figures
Using Open-GL
7/13/2019 It Sem7 Cs2401nol
225/325
Files: .h, .lib, .dll The entire folder gl is placed in the Include
directory of Visual C++
The individual lib files are placed in the libdirectory of Visual C++ The individual dll files are placed in
C:\Windows\System32
Using Open-GL (2)
7/13/2019 It Sem7 Cs2401nol
226/325
Includes:
(if used)
Include in order given. If you use capital
letters for any file or directory, use themin your include statement also.
Using Open-GL (3)
7/13/2019 It Sem7 Cs2401nol
227/325
Changing project settings: Visual C++6.0 Project menu, Settings entry
In Object/library modules move to the end ofthe line and add glui32.lib glut32.lib glu32.libopengl32.lib (separated by spaces from lastentry and each other)
In Project Options, scroll down to end of boxand add same set of .lib files
Close Project menu and save workspace
Using Open-GL (3)
7/13/2019 It Sem7 Cs2401nol
228/325
Changing Project Settings: Visual C++.NET 2003 Project, Properties, Linker, Command Line
In the white space at the bottom, addglui32.lib glut32.lib glu32.lib opengl32.lib Close Project menu and save your solution
Getting Started Making Pictures
7/13/2019 It Sem7 Cs2401nol
229/325
Graphics display: Entire screen (a);windows system (b); [both have usualscreen coordinates, with y-axis down];
windows system [inverted coordinates](c)
Basic System Drawing Commands
7/13/2019 It Sem7 Cs2401nol
230/325
setPixel(x, y, color) Pixel at location (x, y) gets color specified by
color
Other names: putPixel(), SetPixel(),ordrawPoint() line(x1, y1, x2, y2)
Draws a line between (x1, y1) and (x2, y2) Other names: drawLine()or Line().
Alternative Basic Drawing
7/13/2019 It Sem7 Cs2401nol
231/325
current position (cp), specifies wherethe system is drawing now.
moveTo(x,y)moves the pen invisibly to
the location (x, y) and then updates thecurrent position to this position.
lineTo(x,y)draws a straight line from the
current position to (x, y) and thenupdates the cpto (x, y).
Example: A Square
7/13/2019 It Sem7 Cs2401nol
232/325
moveTo(4, 4); //move to startingcorner
lineTo(-2, 4);
lineTo(-2, -2);
lineTo(4, -2);
lineTo(4, 4);
//close thesquare
Device Independent Graphics and
OpenGL
7/13/2019 It Sem7 Cs2401nol
233/325
Allows same graphics program to be runon many different machine types withnearly identical output.
.dll files must be with program
OpenGL is an API: it controls whateverhardware you are using, and you use itsfunctions instead of controlling the
hardware directly. OpenGL is open source (free).
Event-driven Programs
7/13/2019 It Sem7 Cs2401nol
234/325
Respond to events, such as mouse clickor move, key press, or window reshapeor resize. System manages event queue.
Programmer provides call-backfunctions to handle each event. Call-back functions must be registered
with OpenGL to let it know which
function handles which event. Registering function does *not* call it!
Skeleton Event-driven Program
7/13/2019 It Sem7 Cs2401nol
235/325
// include OpenGL librariesvoid main(){
glutDisplayFunc(myDisplay); // register the redraw functionglutReshapeFunc(myReshape); // register the reshapefunctionglutMouseFunc(myMouse); // register the mouse actionfunctionglutMotionFunc(myMotionFunc); // register the mouse motionfunction
glutKeyboardFunc(myKeyboard); // register the keyboardaction functionperhaps initialize other thingsglutMainLoop(); // enter the unending main loop
}
Callback Functions
7/13/2019 It Sem7 Cs2401nol
236/325
glutDisplayFunc(myDisplay); (Re)draws screen when window opened or another
window moved off it.
glutReshapeFunc(myReshape);
Reports new window width and height for reshapedwindow. (Moving a window does not produce areshape event.)
glutIdleFunc(myIdle);
when nothing else is going on, simply redraws displayusing void myIdle() {glutPostRedisplay();}
Callback Functions (2)
7/13/2019 It Sem7 Cs2401nol
237/325
glutMouseFunc(myMouse); Handles mouse button presses. Knows
mouse location and nature of button (up or
down and which button). glutMotionFunc(myMotionFunc);
Handles case when the mouse is moved withone or more mouse buttons pressed.
Callback Functions (3)
7/13/2019 It Sem7 Cs2401nol
238/325
glutPassiveMotionFunc(myPassiveMotionFunc) Handles case where mouse enters the window with
nobuttons pressed.
glutKeyboardFunc(myKeyboardFunc); Handles key presses and releases. Knows which
key was pressed and mouse location.
glutMainLoop() Runs forever waiting for an event. When one occurs,it is handled by the appropriate callback function.
Libraries to Include
7/13/2019 It Sem7 Cs2401nol
239/325
GL, for which the commands begin with GL; GLUT, the GL Utility Toolkit, opens windows,
develops menus, and manages events. GLU, the GL Utility Library, which provides
high level routines to handle complexmathematical and drawing operations. GLUI, the User Interface Library, which is
completely integrated with the GLUT library. The GLUT functions must be available for GLUI to
operate properly. GLUI provides sophisticated controls and menus toOpenGL applications.
A GL Program to Open a Window
7/13/2019 It Sem7 Cs2401nol
240/325
// appropriate #includes go heresee Appendix 1void main(int argc, char** argv){
glutInit(&argc, argv); // initialize the toolkitglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);// set the display modeglutInitWindowSize(640,480); // set window sizeglutInitWindowPosition(100, 150);
// set window upper left corner position on screenglutCreateWindow("my first attempt");
// open the screen window (Title: my first attempt)// continued next slide
Part 2 of Window Program
7/13/2019 It Sem7 Cs2401nol
241/325
// register the callback functionsglutDisplayFunc(myDisplay);glutReshapeFunc(myReshape);glutMouseFunc(myMouse);
glutKeyboardFunc(myKeyboard);myInit(); // additional initializations as
necessaryglutMainLoop(); // go into a perpetual
loop} Terminate program by closing window(s) it is using.
What the Code Does
7/13/2019 It Sem7 Cs2401nol
242/325
glutInit (&argc, argv) initializes Open-GLToolkit
glutInitDisplayMode (GLUT_SINGLE |
GLUT_RGB) allocates a single displaybuffer and uses colors to draw
glutInitWindowSize (640, 480) makes the
window 640 pixels wide by 480 pixelshigh
What the Code Does (2)
7/13/2019 It Sem7 Cs2401nol
243/325
glutInitWindowPosition (100, 150) putsupper left window corner at position 100pixels from left edge and 150 pixels
down from top edge glutCreateWindow (my first attempt)
opens and displays the window with the
title my first attempt Remaining functions register callbacks
What the Code Does (3)
7/13/2019 It Sem7 Cs2401nol
244/325
The call-back functions you write areregistered, and then the program entersan endless loop, waiting for events to
occur. When an event occurs, GL calls the
relevant handler function.
Effect of Program
7/13/2019 It Sem7 Cs2401nol
245/325
Drawing Dots in OpenGL
7/13/2019 It Sem7 Cs2401nol
246/325
We start with a coordinate system basedon the window just created: 0 to 679 in xand 0 to 479 in y.
OpenGL drawing is based on vertices
(corners). To draw an object in OpenGL,you pass it a list of vertices. The list starts with glBegin(arg);and ends with
glEnd();
Argdetermines what is drawn. glEnd()sends drawing data down theOpenGL pipeline.
Example
7/13/2019 It Sem7 Cs2401nol
247/325
glBegin (GL_POINTS); glVertex2i (100, 50); glVertex2i (100, 130);
glVertex2i (150, 130);
glEnd(); GL_POINTS is constant built-into Open-
GL (also GL_LINES, GL_POLYGON, ) Complete code to draw the 3 dots is in
Fig. 2.11.
Display for Dots
7/13/2019 It Sem7 Cs2401nol
248/325
What Code Does: GL Function
Construction
7/13/2019 It Sem7 Cs2401nol
249/325
Example of Construction
lV t 2i ( ) t k i t l
7/13/2019 It Sem7 Cs2401nol
250/325
glVertex2i () takes integer values glVertex2d () takes floating point
values
OpenGL has its own data types to makegraphics device-independent
Use these types instead of standard ones
Open-GL Data Types
ffi d t t C/C t O GL t
7/13/2019 It Sem7 Cs2401nol
251/325
suffix data type C/C++ type OpenGL type nameb 8-bit integer signed char GLbyte
s 16-bit integer Short GLshort
i 32-bit integer int or long GLint, GLsizei
f32-bit float Float GLfloat, GLclampf
d 64-bit float Double GLdouble,GLclampd
ub 8-bit unsigned
numberunsigned char GLubyte,GLboolean
us 16-bit unsigned
numberunsigned short GLushort
ui 32-bit unsigned
numberunsigned int or
unsigned longGLuint,Glenum,GLbitfield
Setting Drawing Colors in GL
7/13/2019 It Sem7 Cs2401nol
252/325
glColor3f(red, green, blue);// set drawing color glColor3f(1.0, 0.0, 0.0); // red
glColor3f(0.0, 1.0, 0.0); // green glColor3f(0.0, 0.0, 1.0); // blue glColor3f(0.0, 0.0, 0.0); // black glColor3f(1.0, 1.0, 1.0); // bright white glColor3f(1.0, 1.0, 0.0); // bright yellow glColor3f(1.0, 0.0, 1.0); // magenta
Setting Background Color in GL
C C ( )
7/13/2019 It Sem7 Cs2401nol
253/325
glClearColor (red, green, blue, alpha); Sets background color.Alpha is degree of transparency; use 0.0 for
now. glClear(GL_COLOR_BUFFER_BIT);
clears window to background color
Setting Up a Coordinate System
id I i ( id)
7/13/2019 It Sem7 Cs2401nol
254/325
void myInit(void){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();gluOrtho2D(0, 640.0, 0, 480.0);
}
// sets up coordinate system for windowfrom (0,0) to (679, 479)
Drawing Lines
lB i (GL LINES) //d li
7/13/2019 It Sem7 Cs2401nol
255/325
glBegin (GL_LINES); //draws one line glVertex2i (40, 100); // between 2 vertices glVertex2i (202, 96);
glEnd (); glFlush(); If more than two vertices are specified
between glBegin(GL_LINES) andglEnd() they are taken in pairs, and aseparate line is drawn between eachpair.
Line Attributes
C l thi k ti li
7/13/2019 It Sem7 Cs2401nol
256/325
Color, thickness, stippling. glColor3f()sets color.
glLineWidth(4.0)sets thickness. The default
thickness is 1.0.a). thin lines b). thick lines c). stippledlines
Setting Line Parameters
P l li d P l li t f ti
7/13/2019 It Sem7 Cs2401nol
257/325
Polylines and Polygons: lists of vertices. Polygons are closed (right); polylines
need not be closed (left).
Polyline/Polygon Drawing
lB i (GL LINE STRIP)
7/13/2019 It Sem7 Cs2401nol
258/325
glBegin (GL_LINE_STRIP); // GL_LINE_LOOP to close p