Computer Graphics
Computer Graphics
2D PRIMITIVES
Line and Curve Drawing
Algorithms
7/19/2017
Line Drawing
y=m.x+b
yend if |m|<1
y0
xk+1 = xk + 1
yk+1 = yk + m
x0 xend
yend if |m|>1
yk+1 = yk + 1
y0 xk+1 = xk + 1/m
x0 xend
DDA Algorithm
#include <stdlib.h>
#include <math.h>
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;
yk+1
yk
xk xk+1
yk+1 du
y
dl
yk
xk xk+1
Bresenhams Line Algorithm
#include <stdlib.h> else {
#include <math.h> x = x0;
/* Bresenham line-drawing procedure for |m|<1.0 */ y = y0;
}
void lineBres (int x0, int y0, int xEnd, int yEnd) setPixel (x, y);
{
int dx = fabs(xEnd - x0), while (x < xEnd) {
dy = fabs(yEnd - y0); x++;
int p = 2 * dy - dx; if (p < 0)
int twoDy = 2 * dy, p += twoDy;
twoDyMinusDx = 2 * (dy - dx); else {
int x, y; y++;
p += twoDyMinusDx;
/* Determine which endpoint to use as start }
position. */ setPixel (x, y);
if (x0 > xEnd) { }
x = xEnd; }
y = yEnd;
xEnd = x0;
}
Circle Drawing
Pythagorean Theorem:
(x, y)
r x2 + y2 = r2
yc
(x-xc)2 + (y-yc)2 = r2
xc
(xc-r) x (xc+r)
y = yc r2 - (x-xc)2
Circle Drawing
change x
change y
Circle Drawing
using polar coordinates
x = xc + r . cos
r (x, y)
y = yc + r . sin
(xc, yc)
change with step
size 1/r
Circle Drawing
using polar coordinates
x = xc + r . cos
r (x, y)
y = yc + r . sin
(xc, yc)
change with step
size 1/r
(-x, y) (x, y)
450 use symmetry if >450
(xc, yc)
Midpoint Circle Algorithm
f(x,y) = x2 + y2 - r2
Ex:
glBegin(GL_LINES);
glVertex2iv(p1);
glVertex2iv(p2);
glEnd();
OpenGL
glBegin(GL_LINES); GL_LINES GL_LINE_STRIP
glVertex2iv(p1); p3 p3
glVertex2iv(p2); p5
p1 p1
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5); p2 p4 p2 p4
glEnd();
GL_LINE_LOOP
p3
p5 p1
p2 p4
Antialiasing
Supersampling
Count the
number of
subpixels
that overlap
the line path.
Area Sampling
Line is treated as a rectangle.
80% 25%
Antialiasing
Pixel Sampling
Micropositioning
The element on the ith row and jth column is denoted by ai,j. Note
that we start indexing at 1, whereas C indexes arrays from 0.
Matrices Addition
1 2 5 6 1 5 2 6 6 8
3 4 7 8 3 7 4 8 10 12
Matrices Multiplication
2 6 7 6 8 44 76
4 5 8 3 3 55 95
9 2 3 2 6 66 96
6 8
2 6
4 5 3 3
Undefined!
2 6 2x2 x 3x2 2!=3
Translate
Shear
Rotate Scale
Translate Points
x' x d x
y' y d
y
d x
If we define the translation matrix T , then we have P =P + T.
d y
Scale Points
To double the size of an object we use a scale factor of 2, to half the size of
an obejct we use a scale factor of 0.5
x' s x x
y
y' s y y
P(x,y)
sy y
P(x,y) x' s x 0 x
y' 0 s y y
sx x x
sx 0
If we define S , then we have P =SP
0 s y
Rotate Points (cont.)
x cos y sin
x' cos sin x
y ' | OP ' | sin( ) l sin( ) y ' sin cos y
l cos sin l sin cos
x sin y cos
P =RP
Review
Translate: P = P+T
Scale: P = SP
Rotate: P = RP
[x, y, 1]
[x, y, W]
P' T P
On the other hand, we can define T21= T(dx1, dy1) T(dx2, dy2) first, then
apply T21 to P: P' ' T21P
T21 T (d x 2 , d y 2 )T (d x1 , d y1 )
where
1 0 d x 2 1 0 d x1 1 0 d x1 d x 2
0 1 d y 2 0 1 d y1 0 1 d y1 d y 2
0 0 1 0 0 1 0 0 1
Examples of Composite 2D Transformations
(1,3)
T(-1,2) T(1,-1)
(2,2)
(2,1)
1 0 1 1 0 1
T21 0 1 1 0 1 2
0 0 1 0 0 1
1 0 0
0 1 1
0 0 1
Composition of 2D Transformations (cont.)
where
S 21 S ( s x 2 , s y 2 ) S ( s x1 , s y1 )
sx 2 0 0 s x1 0 0
0 sy2 0
0 s y1 0
0 0 1 0 0 1
s x 2 * s x1 0 0
0 s y 2 * s y1 0
0 0 1
Composition of 2D Transformations (cont.)
P ' ' R ( 2 )[ R (1 ) P ]
[ R ( 2 ) R (1 )] P
R21P
where
R21 R ( 2 ) R (1 )
cos 2 sin 2 0 cos 1 sin 1 0
sin 2 cos 2 0
sin 1 cos 1 0
0 0 1 0 0 1
cos( 2 1 ) sin( 2 1 ) 0
sin( 2 1 ) cos( 2 1 ) 0
0 0 1
Composition of 2D Transformations (cont.)
M R( )T (d x , d y )
where
Consider the following two questions:
P2(3,3)
P2
P1(1,2)
P1
P1(1,2) P1
Other Than Point Transformations
P1 P1
Another Example.
Translate Translate
Rotate
Scale
Order Matters!
M 2 R ( ) S ( s x , s y )
M 1 S ( s x , s y ) R ( ) cos sin 0 s x 0 0
0 0
sx 0 0 cos sin 0 sin cos 0 sy
1 1
0 0 0
0 0
0 sy 0 sin cos s * cos s * sin 0
0 0 1
0 0 1
s * sin
x y
x s y * cos 0
s x * cos s x * sin 0 1
0 0
s y * sin s y * cos 0
if s = s , M = M .
0 0 1
x y 1 2
Rigid-Body vs. Affine Transformations
1 a 0 1 0 0
SH x 0 1 0 SH y b 1 0
0 0 1 0 0 1
2D Output Primitives
Points
Lines
Circles
Ellipses
Other curves
Filling areas
Text
Patterns
Polymarkers
Filling area
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 pairwise
intersection points
Main idea
Scan-Line filling, contd
xn+1 = xn + x/y , n = 0, 1, 2, ..
Representation:
* bitmapped (raster)
+ fast
- more storage
- less good for
styles/sizes
* outlined (lines and
curves)
+ less storage
+ good for styles/sizes
- slower
Other output primitives
Line caps
Joins
Attributes for area fill
fill style
hollow, solid, pattern, hatch fill,
color
pattern
tiling
Tiling
style
font (typeface)
color
size (width/height)
orientation
path
spacing
alignment
Text attributes
Text attributes, contd
Text attributes, contd
Text attributes, contd
Color as attribute
P = polygon intensity
B = background intensity
f = the extent of the pixel
area covered by the true
polygon
pixel intensity =
P*f + B*(1 - f)
Note! Time consuming to
calculate f
Topics
Clipping
Cohen-Sutherland Line Clipping Algorithm
Clipping
Why clipping?
Not everything defined in the world
coordinates is inside the world window
Where does clipping take place?
Model Clipping Viewport
Transformation
OpenGL does it for you
BUT, as a CS major, you should know how it is
done.
Line Clipping
int clipSegment(p1, p2, window)
Input parameters: p1, p2, window
p1, 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, p2
p1 and/or p2s value might be changed so
that both p1 and p2 are inside the window
Line Clipping
Example o P4 o P1
Line RetVal Output
AB o P3
o P2
BC
CD
o P4 o P1
DE
EA o P3
o P2
Cohen-Sutherland Line Clipping
Algorithm
L2
L3
L1
L5
L6
Cohen-Sutherland Line Clipping
Algorithm
Use region outcode
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)
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 turn
Throw away clipped off part of line each time
Cohen-Sutherland Line Clipping
Algorithm
Examples: L4
outcodes?
trivial accept? window
trivial reject? L2
L3
L1
L5
L6
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 left
else if(p1 is to the right) chop against the right
else if(p1 is below) chop against the bottom
else if(p1 is above) chop against the top
while(1);
Cohen-Sutherland Line Clipping
Algorithm
A segment that requires 4 clips
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
Algorithm
THREE-
DIMENSIONAL
CONCEPTS
3D VIEWING
3D Viewing-contents
Viewing pipeline
Viewing coordinates
Projections
View volumes and general projection
transformations
clipping
3D Viewing
World coordinate system(where the
objects are modeled and defined)
Viewing coordinate system(viewing objects
with respect to another user defined coordinate
system)
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.)
3D viewing
Simple camera analogy is adopted
3D viewing-pipeline
3D viewing
Defining the viewing coordinate system and
specifying the view plane
3D viewing
steps to establish a Viewing coordinate system or view reference
coordinate system and the view plane
First pick up a world coordinate position
called the view reference point. This is the origin
of the VC system
Pick up the +ve direction for the Zv axis
and the orientation of the view plane by
specifying the view plane normal vector N.
Choose a world coordinate position and
this point establishes the direction for N relative
to either the world or VC origin. The view plane
normal vector is the directed line segment.
3D viewing
steps to establish a Viewing coordinate system or view reference coordinate
system and the view plane
3D viewing
yw yw
xv yv
zv xv yv
Mwc,vc=RzRyRx.T
zv xw
xw
zw zw
(a) (b)
Invert Viewing Translate Viewing
z Axis Origin to World Origin
yw yw yw
xv yv yv
yv xv
xw xw xv xw
zv zv
zv
zw (c) zw (d) zw (e)
Rotate About World x Axis Rotate About the World Rotate About the World
to Bring Viewing z Axis into y Axis to Align z Axis to Align the Two
the xz Plane of the World System the Two z Axes Viewing Systems
What Are Projections?
Picture Plane
Objects in
World Space
Converting From 3-D To 2-D
Projection is just one part of the process of converting from 3-D
world coordinates to a 2-D image
3-D world
Project onto Transform to
coordinate Clip against 2-D device
projection 2-D device
output view volume coordinates
plane coordinates
primitives
Types Of Projections
There are two broad classes of
projection:
Parallel: Typically used for architectural and engineering
drawings
Perspective: Realistic looking and used in computer graphics
Orthographic oblique
Orthographic Projection(axonometric)
Parallel Projections
Some examples of parallel projections The projection
plane is aligned so that it
intersects each coordinate
axes in which the object is
defined (principal axes) at
the same distance from the
origin.
All the principal
axes are foreshortened
equally.
x p 1 0 L1 cos 0 x
y
p 0 1 L1 sin 0 y
z p 0 0 0 0 z
p
w 0 0 0 1 1
Parallel Projections Oblique projections
Transformation equations for oblique projections is as below.
Perspective projection
Parallel projection
The size of the view volume depends on the size of the window but the
shape depends on the type of projection to be used.
Both near and far planes must be on the same side of the reference
point.
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 projection
reference point relative to the view plane
View volume - PHIGS
View
VPN
Plane
Front
Clipping
Plane VRP Back
Clipping
Plane
Direction of
Propagation B
F Back
Back Clipping
View Clipping Plane
Front View
Plane Plane
Clipping Plane VPN
Front
Plane Direction of Clipping
Propagation Plane
VRP VPN VRP
B F B
F
View volume
In an animation sequence, we can
place the projection reference point at the
viewing coordinate origin and put the view
plane in front of the scene.
We set the field of view by
adjusting the size of the window relative to
the distance of the view plane from the
PRP.
We move through the scene by
moving the viewing reference frame and
the PRP will move with the view reference
point.
General parallel projection
transformation Parallel
Far
Plane
View
Near Direction of
Volume
Plane Projection
N
Window
(a)
Original Orientation
Far
Plane View Direction of
Near Volume Projection
Plane
N
Window
(b)
After Shearing
General parallel projection
transformation Parallel
N N
Window Window
Center of Center of
Projection Projection
Steps
1. Shear the view volume so that the
Mperspective=Mscale.Mshear
centerline of the frustum is
perpendicular to the view plane
2. Scale the view volume with a
scaling factor that depends on 1/z.
A shear operation is to align a general
perspective view volume with the
projection window.
The transformation involves a
combination of z-axis shear and a
translation.
Clipping
View volume clipping boundaries are planes whose
orientations depend on the type of projection, the projection
window and the position of the projection reference point
The process of finding the intersection of a line with one
of 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 orthographic
parallel coordinates.
Oblique projection view volumes are converted to a
rectangular parallelepiped by the shearing operation and
perspective view volumes are converted with a combination of
shear and scale transformations.
Clipping-normalized view
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
volumes
There are several advantages to clipping against the
unit cube
1. The normalized view volume provides a standard
shape for representing any sized view volume.
2. Clipping procedures are simplified and standardized
with unit clipping planes or the viewport planes.
3. Depth cueing and visible-surface determination are
simplified, since Z-axis always points towards the
viewer.
Unit cube
Mapping positions within a rectangular
view volume to a three-dimensional
rectangular viewport is accomplished
with a combination of scaling and
translation. 3D viewport
Clipping-normalized view
volumes
Mapping positions within a
rectangular view volume to a
three-dimensional rectangular
viewport is accomplished with a
combination of scaling and
Unit cube
translation.
Dx 0 0 Kx
0 Dy 0 Ky 3D viewport
0 0 Dz Kz
Where
0 0 0 1
Dx=(xvmax-xvmin)/(xwmax-xwmin) and Kx= xvmin- xwmin Dx
Dy= (yvmax-yvmin)/(ywmax-ywmin) and Ky= yvmin - ywmin Dy
Dz= (zvmax-zvmin)/(zwmax-zwmin) and Kz= zvmin- zwmin Dz
Viewport clipping
For a line endpoint at position
(x,y,z) we assign the bit positions
in the region code from right to left
as
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)
Viewport clipping
WORLD-COORDINATE
Object descriptions
Clipping Operations
2D coordinates 3D coordinates
y
y
x
x
z
y
z
Right-handed coordinate system: x
3D Transformations (cont.)
1 0 0 dx
0 1 0 d y
T (d x , d y , d z )
0 0 1 dz
0 0 0 1
sx 0 0 0
0 sy 0 0
S (sx , s y , sz )
0 0 sz 0
0 0 0 1
3D Transformations (cont.)
1 0 0 0 cos 0 sin 0
0 cos sin 0 0 1 0 0
Rx ( ) Ry ( )
0 sin cos 0 sin 0 cos 0
0 0 0 1 0 0 0 1
Composition of 3D Rotations
Ry ( ) Rz ( ) Rz ( ) Ry ( )
More Rotations
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:
Z P1(x1, y1 , z1) X
Rotating About An Arbitrary Axis
Y Y
P2
P1
P1
Z X Z P2 X
1). Translate the object by (-x1, - 2). Rotate the axis about x so
y1, -z1): T(-x1, -y1, -z1) that it lies on the xz plane: Rx()
Y Y
P1 P1
Z P2 X Z X
P2
3). Rotate the axis about y so 4). Rotate object about z by : Rz()
that it lies on z: Ry ()
Rotating About An Arbitrary Axis (cont.)
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)
Try to transform the line segments P1P2 and P1P3 from their start position in (a)
to their ending position in (b).
y y
P3
P1 P2 P3
x P1 x
z z P2
(a) (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 an
understanding. The 2nd, more abstract approach is to use the properties of
special orthogonal matrices.
Composition of 3D Transformations
4 3
P3 P3 P3
P2 P1
P1 x P2 P1 x x
z P2 z z
Composition of 3D Transformations
1. T ( x1 , y1 , z1 )
1 0 0 x1 P1' T ( x1 , y1 , z1 ) P1 [0 0 0 1]T
0 y1
1 0 P2' T ( x1 , y1 , z1 ) P2 [ x2 x1 y2 y1 z 2 z1 1]T
0 0 1 z1 P3' T ( x1 , y1 , z1 ) P3 [ x3 x1 y3 y1 z3 z1 1]T
0 0 0 1
y R y ( (90 ) )
2.
sin 0 cos 0
P3 0 1 0 0
cos 0 sin 0
P1
P2
0 0 0 1
D1
x
z
Composition of 3D Transformations
3 y Rx ( )
1 0 0 0
0 cos sin 0
0 sin cos 0
D2 P1
P2 0 0 0 1
x
z
y
4.
Rz ( )
P3
D3 Finally, we have the composite matrix:
P1
x Rz ( ) Rx ( ) R y ( 90) T ( x1 , y1 , z1 ) R T
z
P2
Vector Rotation
y y
u
Rotate the vector
x x
1
0
The unit vector along the x axis is [1, 0]T. After rotating about the origin by
, the resulting vector is
y y
Similarly, the unit vector along the y axis is [0, 1]T. After rotating about the
origin by , the resulting vector is
The reversed operation of the above rotation is to rotate a vector that is not
originally pointing the x (or y) direction into the direction of the positive x or y
axis. The rotation matrix in this case is R(- ), expressed by R-1( )
y y
u u
Rotate the vector
x x
what is the rotation matrix if one wants the vector T in the left figure to be
rotated to the direction of u.
u
2 3 2 T
3
T
(2, 3) |u| 22 32 13 13
2 3
R u | v 13 13
3 2
T 13 13
If, on the other hand, one wants the vector u to be rotated to the direction of
the positive x axis, the rotation matrix should be
2 3
u
T
13 13
R T
v 3 2
13 13
Rotation Matrices
Each row is perpendicular to the other, i.e. their dot product is zero.
cos sin cos ( sin ) 0
Each vector will be rotated by R() to lie on the positive x and y axes,
respectively. The two column vectors are those into which vectors
along the positive x and y axes are rotated.
y1 z2 y2 z1
v1 v2 ( x1 z2 x2 z1 )
x1 y2 x2 y1
v1 v2 v2
v1
Extension to 3D Cases
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 the
example:
y Note, in this example, vector P1P2 will be
P3
rotated to the positive z direction. Hence the
fist column vector in the rotation matrix is the
P1 P2
normalised P1P2. But what about the other
x
z two columns? After all, P1P3 is not perpendi-
y
And the third direction is decide by the cross
v
P3 product of the other two directions, which is
z
P1 x
P1 P2
P P
1 2
Yaw, Pitch, and Roll
Consider the following example. An airplane is oriented such that its nose is
pointing in the positive z direction, its right wing is pointing in the positive x
direction, its cockpit is pointing in the positive y direction. We want to
transform the airplane so that it heads in the direction given by the vector
DOF (direction of flight), is centre at P, and is not banked.
Solution to the Airplane Example
First we are to rotate the positive zp direction into the direction of DOF,
which gives us the third column of the rotation matrix: DOF / |DOF|. The xp
axis must be transformed into a horizontal vector perpendicular to DOF
that is in the direction of yDOF. The yp direction is then given by xp zp =
DOF (y DOF).
1. Translation: T 1 (d x , d y , d z ) T (d x ,d y ,d z )
1 1 1
2. Scaling: S 1 ( sx , s y , sz ) S ( , , )
sx s y sz
3. Rotation: R 1 ( ) R( ) RT ( )
GRAPHICS
PROGRAMMING
Color Models
Color models,contd
subtractive mixing
Additive mixing
pure colors are put close to each other => a mix on the
retina of the human eye (cp. RGB)
overlapping gives yellow, cyan, magenta and white
the typical technique on color displays
Subtractive mixing
Commission
Internationale de
LEclairage (1931)
not a computer
model
each color = a
weighted sum of
three imaginary
primary colors
RGB model
c 1 r
m 1 g
y 1 b
CMYK model
Computer Animations
Steps
1. Dividing Ne edges of keyframemin into Ns+1 sections
2. Dividing the remaining lines of keyframemin into Nssections
1
1
3
2 2
Key frame K
Key frame K+1
Computer Animations
Key frame systems
Morphing Transformation 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+1 denote 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 = (Vmax 1)mod (Vmin 1)
Np = int((Vmax 1) / (Vmin 1)
Steps
1. adding Np points to Nls line sections of keyframemin sections
2. Adding Np-1 points to the remaining edges of keyframemin
Computer Animations
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 sub
intervals, yielding an in-between spacing of t
t = t2-t1/(n+1)
We can calculate the time for in-betweens as
tBj=t1+j t for j=1,2,.,n
Computer Animations
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< </2
For n-inbetweens the time for the jth inbetween would then be calculated as
tBj=t1+t(1-cosj /2(n+1))
j=1,2,.,n
For j=1
tB1=t1+t(1-cos /2(n+1))
For j=1
tB2=t1+t(1-cos 2/2(n+1))
where t is the time difference
between any two key frames.
Computer Animations
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 the
function
sin, 0< </2
For n-inbetweens the
time for the jth inbetween would
then be calculated as
tBj=t1+t.sinj /2(n+1))
j=1,2,.,n
Computer Animations
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< </2
The time for the jth inbetween is calculated as
tBj=t1+t 1-cos j[(n+1)/2)
j=1,2,.,n
Computer Animations
Motion specifications
Direct motion specifications
Here we explicitly give the rotation angles and translation vectors.
Then the geometric transformation matrices are applied to transform
coordinate 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
Motion specifications
Goal directed systems
We can specify the motions that are to take place in general terms
that abstractly describe the actions, because they determine specific
motion paramters given the goals of the animation.
Computer Animations
Motion specifications
Kinematics
Kinematic specification
of of a motion can also be
given by simply describing
the motion path which is
often done using splines.
In inverse kinematics
we specify the intital and
final positions of objects at
specified times and the
motion parameters are
computed by the system.
Computer Animations
Motion specifications
dynamics
specification of the forces that produce the velocities and
accelerations. Descriptions of object behavior under the influence of
forces are generally referred to as a Physically based modeling (.rigid
body 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 initial
and final position of objects and the type of motion.
Computer Animations
Ideally suited for:
Physics based animations
Large volumes of objects wind effects, liquids
Cloth animation/draping
Underlying mechanisms are usually:
Particle systems
Mass-spring systems
Computer Animations
Physics based animations
Computer Animations
Secondary Motion
Computer Animations
Motion Capture
Computer
Graphics using
OpenGL
Initial Steps in Drawing Figures
Using Open-GL
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 lib
directory of Visual C++
The individual dll files are placed in
C:\Windows\System32
Using Open-GL (2)
Includes:
<windows.h>
<gl/gl.h>
<gl/glu.h>
<gl/glut.h>
<gl/glui.h> (if used)
Include in order given. If you use capital
letters for any file or directory, use them
in your include statement also.
Using Open-GL (3)
Changing project settings: Visual C++
6.0
Project menu, Settings entry
In Object/library modules move to the end of
the line and add glui32.lib glut32.lib glu32.lib
opengl32.lib (separated by spaces from last
entry and each other)
In Project Options, scroll down to end of box
and add same set of .lib files
Close Project menu and save workspace
Using Open-GL (3)
Changing Project Settings: Visual C++
.NET 2003
Project, Properties, Linker, Command Line
In the white space at the bottom, add
glui32.lib glut32.lib glu32.lib opengl32.lib
Close Project menu and save your solution
Getting Started Making Pictures
Graphics display: Entire screen (a);
windows system (b); [both have usual
screen coordinates, with y-axis down];
windows system [inverted coordinates]
(c)
Basic System Drawing Commands
setPixel(x, y, color)
Pixel at location (x, y) gets color specified by
color
Other names: putPixel(), SetPixel(), or
drawPoint()
line(x1, y1, x2, y2)
Draws a line between (x1, y1) and (x2, y2)
Other names: drawLine() or Line().
Alternative Basic Drawing
current position (cp), specifies where
the system is drawing now.
moveTo(x,y) moves the pen invisibly to
the location (x, y) and then updates the
current position to this position.
lineTo(x,y) draws a straight line from the
current position to (x, y) and then
updates the cp to (x, y).
Example: A Square
moveTo(4, 4);
//move to starting
corner
lineTo(-2, 4);
lineTo(-2, -2);
lineTo(4, -2);
lineTo(4, 4);
//close the
square
Device Independent Graphics and
OpenGL
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
What Code Does: GL Function
Construction
Example of Construction
glVertex2i () takes integer values
glVertex2d () takes floating point
values
Register functions:
glutMouseFunc (myMouse);
glutKeyboardFunc (myKeyboard);
Write the function(s)
NOTE that any drawing you do when
you use these functions must be done IN
the mouse or keyboard function (or in a
function called from within mouse or
keyboard callback functions).
Example Mouse Function
void myMouse(int button, int state, int x,
int y);
Button is one of GLUT_LEFT_BUTTON,
GLUT_MIDDLE_BUTTON, or
GLUT_RIGHT_BUTTON.
State is GLUT_UP or GLUT_DOWN.
X and y are mouse position at the time of
the event.
Example Mouse Function (2)
The x value is the number of pixels from the
left of the window.
The y value is the number of pixels down from
the top of the window.
In order to see the effects of some activity of
the mouse or keyboard, the mouse or
keyboard handler must call either myDisplay()
or glutPostRedisplay().
Code for an example myMouse() is in Fig.
2.40.
Polyline Control with Mouse
Example use:
Code for Mouse-controlled Polyline
Using Mouse Motion Functions
glutMotionFunc(myMovedMouse); //
moved with button held down
glutPassiveMotionFunc(myMovedMouse
); // moved with buttons up
myMovedMouse(int x, int y); x and y are
the position of the mouse when the
event occurred.
Code for drawing rubber rectangles
using these functions is in Fig. 2.41.
Example Keyboard Function
void myKeyboard(unsigned char theKey, int mouseX, int mouseY)
{
GLint x = mouseX;
GLint y = screenHeight - mouseY; // flip y value switch(theKey)
{case p: drawDot(x, y); break;
// draw dot at mouse position
case E: exit(-1); //terminate the program
default: break; // do nothing
}
}
Example Keyboard Function (2)
Parameters to the function will always be
(unsigned char key, int mouseX, int
mouseY).
The y coordinate needs to be flipped by
subtracting it from screenHeight.
Body is a switch with cases to handle
active keys (key value is ASCII code).
Remember to end each case with a
break!
Using Menus
Both GLUT and GLUI make menus
available.
GLUT menus are simple, and GLUI
menus are more powerful.
We will build a single menu that will
allow the user to change the color of a
triangle, which is undulating back and
forth as the application proceeds.
GLUT Menu Callback Function
Int glutCreateMenu(myMenu); returns menu ID
void myMenu(int num); //handles choice num
void glutAddMenuEntry(char* name, int value);
// value used in myMenu switch to handle
choice
void glutAttachMenu(int button); // one of
GLUT_RIGHT_BUTTON,
GLUT_MIDDLE_BUTTON, or
GLUT_LEFT_BUTTON
Usually GLUT_RIGHT_BUTTON
GLUT subMenus
Create a subMenu first, using menu
commands, then add it to main menu.
A submenu pops up when a main menu item is
selected.
glutAddSubMenu (char* name, int menuID); //
menuID is the value returned by
glutCreateMenu when the submenu was
created
Complete code for a GLUT Menu application is
in Fig. 2.44. (No submenus are used.)
GLUI Interfaces and Menus
GLUI Interfaces
An example program illustrating how to
use GLUI interface options is available
on book web site.
Most of the work has been done for you;
you may cut and paste from the example
programs in the GLUI distribution.
UNIT-IV
RENDERING
Polygon shading model
perceived intensity
n3 n4
n = (n1 + n2 + n3 + n4) / 4.0
Gouraud Shading
C2 C3
* lerp: linear interpolation
Lerp(Ca, Cb)
Gouraud Shading
Linear interpolation
x= a / (a+b) * v1 + b/(a+b) * v2
a b
v1 x v2
Interpolate triangle color: use y distance to interpolate the two end
points in the scanline, and use x distance to interpolate interior
pixel colors
Gouraud Shading Problem
Normal interpolation
n1
lerp(na, nb)
n2
n3
1 1/3 1/3
Generator
Generator
Generator
do {
x1 = 2.0 * 0.001*(float)(rand()%1000) - 1.0;
x2 = 2.0 * 0.001*(float)(rand()%1000) - 1.0;
w = x1 * x1 + x2 * x2;
} while ( w >= 1.0 );
Statistically self-affine
random variations
Sx<>Sy<>Sz
terrain, water, clouds
Invariant fractal sets
Nonlinear transformations
Self squaring fractals
Julia-Fatou set
Squaring function in complex space
Mandelbrot set
Squaring function in complex space
Self-inverse fractals
Inversion procedures
x=>x2+c
x=a+bi
Julia-Fatou and
Modulus
Complex number Mandelbrot
Sqrt(a2+b2)
If modulus < 1
Squaring makes it go Julia-Fatou
toward 0
If modulus > 1
Squaring falls towards
infinity
If modulus=1
Some fall to zero
Some fall to infinity
Some do neither
Boundary between
numbers which fall to
zero and those which
fall to infinity
Julia-Fatou Set
Initiator
Given geometric shape
Generator
Pattern which replaces subparts of initiator
Koch Curve
First iteration
Initiator generator
Fractal dimension
D=fractal dimension
Amount of variation in the structure
Measure of roughness or fragmentation of the object
Small d-less jagged
Large d-more jagged
Self similar objects
nsd=1 (Some books write this as ns-d=1)
s=scaling factor
n number of subparts in subdivision
d=ln(n)/ln(1/s)
[d=ln(n)/ln(s) however s is the number of segments versus how much
the main segment was reduced
I.e. line divided into 3 segments. Instead of saying the line is 1/3,
say instead there are 3 sements. Notice that 1/(1/3) = 3]
If there are different scaling factors
n
Skd=1
K=1
Figuring out scaling factors
I prefer: ns-d=1 :d=ln(n)/ln(s)
Kochs snowflake
Dimension is a ratio of
the (new size)/(old size) After division have 4 segments
Divide line into n identical n=4 (new segments)
segments s=3 (old segments)
n=s Fractal Dimension
Divide lines on square D=ln4/ln3 = 1.262
into small squares by
dividing each line into n For your reference: Book method
identical segments n=4
n=s2 small squares Number of new segments
Divide cube s=1/3
Get n=s3 small cubes segments reduced by 1/3
d=ln4/ln(1/(1/3))
Sierpinski gasket Fractal
Dimension
Divide each side by 2
Makes 4 triangles
We keep 3
Therefore n=3
Get 3 new triangles from 1 old
triangle
s=2 (2 new segments from one
old segment)
Fractal dimension
D=ln(3)/ln(2) = 1.585
Cube Fractal Dimension
Apply fractal algorithm
Divide each side by 3
Image from
Now push out the middle face of each cube Angel book
Now push out the center of the cube
What is the fractal dimension?
Well we have 20 cubes, where we used to have 1
n=20
We have divided each side by 3
s=3
Fractal dimension ln(20)/ln(3) = 2.727
Language Based Models of
generating images
Typical Alphabet {A,B,[,]} B
Rules A[B]AA[B]
A=> AA
B=> A[B]AA[B]
AA[A[B]AA[B]]AAAA[A[B]AA[B]]
Starting Basis=B AA A
Generate words A
Represents sequence of
B
B B A
segments in graph A
structure A
A
Branch with brackets A
B AA A
Interesting, but I want a
A
A
tree B B A
Language Based Models of
generating images cond
Modify Alphabet B
{A,B,[,],(,)} A[B]AA(B)
Rules AA[A[B]AA(B)]AAAA(A[B]AA(B))
A=> AA B
B=> A[B]AA(B) AA A
[] = left branch () = right A
branchStarting Basis=B B
A
Generate words B
A
Represents sequence of A B A
segments in graph A
structure B AA A
Branch with brackets A
A
B A
Language Based models have no
inherent geometry
B
Grammar based model requires AA A
Grammar
Geometric interpretation A B
Generating an object from the word A
is a separate process
examples A
Branches on the tree drawn B A
at upward angles
Choose to draw segments AA A
of tree as successively
smaller lengths A
The more it branches, B A
the smaller the last
branch is
Draw flowers or leaves at
terminal nodes
Grammar and Geometry
Non-rigid object
Rope, cloth, soft rubber ball, jello
Describe behavior in terms of external and internal forces
Approximate the object with network of point nodes k
connected by flexible connection
Example springs with spring constant k k k
Homogeneous object k
All ks equal
Hookes Law
Fs=-k x
x=displacement, Fs = restoring force on spring
Could also model with putty (doesnt spring back)
Could model with elastic material
Minimize strain energy
Turtle Graphics
Turtle can
F=Move forward a unit
L=Turn left
R=Turn right
Stipulate turtle directions, and
angle of turns
Equilateral triangle
Eg. angle =120
FRFRFR
What if change angle to 60
degrees
F=> FLFRRFLF
Basis F
Koch Curve (snowflake)
Example taken from Angel
book
Using turtle
graphics for trees