Lecture1-Introduction To Computer Graphics
Lecture1-Introduction To Computer Graphics
501472-3
Lecture 1: Introduction to Computer Graphics
Logistics
2
Course Description:
■ This course introduces techniques for constructing 2D and 3D Graphics using OpenGL.
■ The topics include the rendering pipeline, primitive drawings, geometric
transformations, clipping, lighting and illumination, color models texture mapping, and
ray-tracing animation.
Course Content:
1. Overview of computer graphics concepts
2. Cathode Ray Tube (CRT), spots and lights, raster and random scan displays, color models
3. Color CRT monitors, color models, flat CRT and Video controller systems Raster and vector
graphics.
4. OpenGl program and structures, Windows, points, coordinate system
5. Primitive objects and fill colors in OpenGL
6. Line drawing: DDA algorithm, Brasenham’s algorithm
7. Circle and midpoint circle algorithms, Brasenham’s algorithm
8. 2D/3D transformation such as translation, scaling, shearing, rotation, and affine
transformations
9. 2D/3D deformation such as shearing, tapering, twisting, bending
10. Model view
11. Light and Shadow
Prerequisites
■ Textbook (Required):
o Computer Graphics with OpenGL by Donald D. Hearn, M. Pauline Baker, 4th Edition
■ Recommended References (Not obligatory):
o Computer Graphics Through OpenGL: From Theory to Experiments , 4th edition,
published in 2022
■ Software: C++ with FreeGlut library
■ Others: Lecture slides
7
Policies
• Attendance: Students are allowed up to 20% absence, including sick leave, which still
counts towards this limit.
• Homework and Tests: Must be submitted by the due date. Late submissions will receive a
zero.
• Honor Code: Plagiarism and cheating are strictly prohibited. Violations result in a zero for
the assignment and may be subject to university disciplinary actions. Final exams will
adhere to university regulations.
• Generative AI Policy: If you use generative AI, you must cite it and explain its role in your
work. Using AI to complete entire assignments is not allowed.
• Phone Policy: Phones must be kept on silent during class. Taking pictures without prior
permission is not allowed.
9
Policies
■ Quizzes: Students will be informed of quiz dates in advance. There will be 2 quizzes,
contributing 10 points to the final grade.
■ Test Absence: Absence from tests is only allowed with a valid sick leave from a
public hospital or in the event of a first-degree relative's death. For any other
reasons, students must seek permission prior to missing the test.
10
OVERVIEW OF COMPUTER
GRAPHICS CONCEPTS
What is an image?
■ 2D: flat images, Objects has no notion of distance from viewer and only (x,y)
color values on screen.
■ 3D: Objects have distances from viewer with (x,y,z) values on screen.
Why Computer Graphics are important?
Creation of VR environments in
which user interact with objects
in a 3D scene.
Educational and
Training
■ For training applications,
special hardware systems are
designed, such as training ship
Designing Effective Step-By-Step Assembly Instructions
(Maneesh Agrawala et. al)
captains, aircraft pilots.
GT Racer 3
software hardware
Conceptual Framework for Interactive
Graphics
• Graphics System is the actual hardware that renders the graphics.
The Graphics Processing Unit takes instructions from the graphics
library and uses them to process the application model data and
generate the final image or frame.
• The GPU is specialized hardware optimized for tasks such as shading,
texturing, and rendering 3D models.
• User interaction results in modification of image and/or model
software hardware
Graphics Library
■ Graphics Library are functions to draw line, circle, image, etc.
■ They are cross-platform, device-independent libraries. Examples:
OpenGL, Vulkan, DirectXTM, Windows Presentation Foundation (WPF),
and RenderManTM.
Graphics Library
Logical input devices: Two major characteristics: the measurements that the device
returns to the user program and the time when the device returns those measurements.
■ String device: the use of character input through scanf or cin.
■ Locator: it can provide a position to the application in either a device-independent
coordinate system, or in screen coordinates
■ Logical pick device returns the identifier of an object on the display to the
application program.
■ Widget is a graphical interactive device, provided by either the window system or a
toolkit. Such as menus, scrollbars, and graphical buttons.
■ Logical valuator provides analog input to the user program, usually through a widget
such as a slidebar, or a physical keyboard
2 Central processing unit (CPU)
■ The CPU, often called the "brain" of the computer, is a general-purpose
processor designed for sequential task execution and system
management.
■ General-purpose processing: Optimized for logic, math, and I/O
operations, not specialized for graphics.
– Sequential execution: Handles tasks one at a time with high
precision, unlike GPUs, which excel in parallel tasks.
– Managing operating systems and running diverse applications.
– Handling logical operations and decision-making processes.
– Performing tasks like browsing, word processing, and system control.
3 Graphics Processing Unit (GPU)
■ This is a place where images and pictures are stored as a 2D array (matrix of 0 & 1,
0 represents darkness and 1 represents image or picture).
■ In today’s term frame buffer is called V-RAM (video RAM) and it helps to store the
image in bit form.
■ Frame buffer accessible to CPU of the main computer. This allowing repaid update of
the stored image.
5 Output devices
■ Viewing Angle: It is angle from which the screen can be seen from side.
Related Terminologies
■ The electron beam is directed only to the part of the screen where the
picture is to be drawn rather than scanning from left to right and top
to bottom as in raster scan.
■ Picture definition is stored as a set of line-drawing commands in an
area of memory referred to as the refresh display file.
■ To display a specified picture, the system cycles through the set of
commands in the display file, drawing each component line in turn.
Random Scan Displays
■ Picture definition is now stored as a line-drawing commands an area
of memory referred to as refresh display file (display list).
■ Random scan displays have higher resolution than raster systems.
■ Random scan displays are designed for line-drawing applications and
cannot display realistic shaded scenes.
Exercise 2:
1. What are the two main types of display methods in computer
graphics?
2. Which display method is better suited for rendering complex images
with shading and colors?
3. In which type of display system would you expect to find a frame
buffer?
4. Which type of display can directly draw lines between any two points
without concerning about pixel resolution.
CATHODE RAY TUBE (CRT)
Cathode Ray Tube (CRT)
Cathode Ray Tube (CRT) related terms
■ A Cathode Ray Tube (CRT) is a vacuum tube once widely used in older computer
monitors and TVs.
■ In computing, it served as the primary display technology before LCDs and LEDs.
■ The CRT beam transfers energy to the phosphor coating on the screen, producing
visible light.
■ CRT displays relied on raster scanning techniques, forming images by rapidly moving
the electron beam across the screen, a process managed by the computer’s
graphics hardware and software.
Cathode Ray Tube (CRT) related terms
● Refresh rate: # of complete images (frames)
drawn on the screen in 1 second. Frames/sec.
● Frame time: the time elapsed between two
consecutive frames, divided by the refresh rate.
sec/frame.
● Intensity Distribution: The intensity is
greatest at the center of the spot and decrease
with Gaussian distribution out to the edges of
the spot.
Intensity Distribution
Cathode Ray Tube (CRT) related terms
● Resolution: a 2D term, maximum number of points that can be
displayed without overlap on a CRT
● Resolution of a CRT is dependent on:
Overlap
Color CRT Monitors
■ A CRT monitor displays color pictures by using a combination of phosphors that emit
different color lights.
■ Methods:
– Beam Penetration: Two layers of phosphor (red and green) are coated onto the
inside of the CRT screen.
FYI ■ Used with random scan monitors
■ Only four colors are possible (red, green, orange, and yellow).
■ Quality of pictures is not as good as with other methods.
– Shadow Mask: Three color phosphor dots (red, green and blue) at each point
on the screen.
■ Used in raster scan system (including color TV)
■ Designed as RGB monitors.
FYI
Flat CRT
■ Electron beams are accelerated parallel to the screen, then deflected 90º to the
screen.
Color Models
■ The RGB Color Model: R, G, and B represent the colors produced by red, green
and blue phosphors, respectively.
Color Models
■ CMY Color Model: CMY (short for Cyan, Magenta, Yellow, and key) is a
subtractive color model.
■ .
Liquid Crystal Display (LCD)
■ Thinner and lighter. No tube or electron beams. requires a backlight to illuminate the
screen.
■ Blocking/unblocking light through polarized crystals. Crystals liquefy when excited
by heat or E field.
Polarizer
■ A matrix of LC cells one for each pixel.
■ No refresh unless the screen changes. Color filtering
Light
Plasma Displays
■ Plasma display panels
– Similar in principle to fluorescent light tubes
– Small gas-filled capsules are excited by electric
field, emits UV light
– UV excites phosphor
– Phosphor relaxes, emits some other color
Plasma Displays
■ Plasma Display Panel Pros
– Large viewing angle
– Good for large-format displays
– Fairly bright
■ Cons
– Expensive
– Large pixels (~1 mm versus ~0.2 mm)
– Phosphors gradually deplete
– Less bright than CRTs, using more power
Display Technology: DMD / DLP
■ Digital Micromirror Devices (projectors) or Digital Light Processing
■ Microelectromechanical (MEM) devices, fabricated with VLSI techniques
Display Technologies: LED
■ A Light Emitting Diode (LED) screen is a display technology that
uses LEDs as backlight to illuminate pixels in an LCD (Liquid Crystal
Display) panel
■ A type of LCD screen that uses LEDs as the backlight instead of older
CCFL (Cold Cathode Fluorescent Lamp) backlights.
Display Technologies: Organic LED
Arrays
■ Organic Light-Emitting Diode (OLED) Arrays
– OLEDs function like regular semiconductor LEDs
– But they emit light
■ They are made by putting a very thin layer of special materials that glow
when electricity goes through them, onto the screen in a vacuum.
■ To make different colors, they add some glowy substances to these layers
with fluorescent molecules.
■ Can emit true black color compared to LCD and LED.
Exercise 3:
Character animation is a
type of animation that uses
movement, speech and tone
to bring a character to life.
Animators can shape
characters to take on a
desired personality,
experience specific
emotions, or embark on a
physical or mental journey.
Modeling
■ Modeling refers to the techniques involved with creating, scanning,
editing, and manipulating 3D geometric data.
■ Modeling is often done by a human user with an interactive editing
program but complex objects, such as trees, can be constructed with
automatic procedural modeling algorithms
■ 3D models are also often acquired from real world objects using laser
scanning or computer vision techniques
Modeling
■ Modeling also includes the use of curved surfaces and other higher
order primitives, which are often converted into triangles using various
tessellation algorithms.
■ Another important area of modeling includes mesh reconstruction for
surface simplification
■ Modeling makes heavy use of computational geometry
tessellation algorithms
Modeling
Before the next lecture:
#include <iostream>
// This is a comment line.
int main() {
return 1; // return EXIT_SUCCESS;
}
C++ Overview
• Example:
int a = 5, b = 3;
int c = a; // c = 5
b = a*c; // b = 25
c = b/2; // c = 12 (trucated)
a = 7; // a = 7
c = a % 2; // c = 1 (remainder 7/2 = 3 ½.
• Be careful of order of operations (priority), use brackets (and) Combined operators: ++a means a=a+1,
--a means a = a-1
a +=b means a=a+b a *=b means a=a*b
a /=3 means a=a/3 a -= 5 means a=a-5
C++ Overview
• Example on while-loop
i=1;
while (i<10) {
std::cout << i++ << std::endl;
}
• Example on do-while loop:
i=1;
do {
std::cout << i++ << std::endl;
} while (i<10);
C++ Overview
Additional resources:
■ [Link]/doc/tutorial
■ [Link]
■ [Link]
Computer Graphics
501472-3
Lecture 2- OpenGL Introduction
What is OpenGL
• OpenGL is a computer graphics rendering API
• With it, you can generate high-quality color images by rendering with
geometric primitives.
• Objects in OpenGL are built by assembly vertices into primitives. Example:
A triangle is a primitive with 3 vertices.
What is OpenGL
• By using OpenGL, the graphics part of your application can be
• operating system independent
• Window system independent
• The first sentence in the "main" function is setting up the OpenGL library:
(&argc, argv);
Setting up a Window to Draw in OpenGL
• Then we should initialize the display frame buffer, we are going to use a single
buffer (other option is double buffer for animation) and a colored RGB monitor.
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
• After that, we define the window size in pixels:
glutInitWindowSize(600, 600); //physical window size in pixels
void init() {
glClearColor(1,1,1,0);
gluOrtho2D(-20,20, -20,20); }
Source: [Link]
Drawing in OpenGL
• There are several methods to draw in OpenGL.
• The simplest method to draw primitives is to use the OpenGL begin and
end calls.
• Attributes (e.g., GL_POINT) are set within a glBegin/glEnd block.
• Each vertex is defined using glVertex, along with its attributes.
• A vertex is a location in the form (x, y) for 2D or (x, y, z) for 3D.
• Using glBegin/glEnd, we can draw points (or pixels), lines, triangles, or
polygons.
OpenGL Command Notation
glVertexDTv( ... )
glColor3ub(255, 0, 0);
glBegin(GL_POINTS);
glVertex2i(2, 2);
glVertex2i(5, 5);
glVertex2i(6, 6);
glEnd();
• The above code will draw three pixels at locations (2,2), (5,5) and (6,6) in red color.
You can use glPointSize(5.0) to increase the size of the pixel.
Draw a Point or Pixel
// The full body of the draw function
void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
glPointSize(5.0); // Set the point size to 5 pixels
// Draw three points in red color
glColor3ub(255, 0, 0); // Set the color to red
glBegin(GL_POINTS);
glVertex2i(2, 2);
glVertex2i(5, 5);
glVertex2i(6, 6);
glEnd
glBegin(GL_LINE_STRIP);
glVertex*(…);
…
glEnd();
Lines Strip Example
glBegin(GL_LINES_STRIP);
glVertex2i( 0,-20);
glVertex2i( 0, 20);
glVertex2i(-20, 0);
glVertex2i( 20, 0);
glVertex2i( 0, 20);
glEnd();
Line Loop
• The first 2-points from the list of points will construct a line.
• The last point from the last line with the point from the list of points
will form a line.
• The last point from the list of points with the first point from the list
of points will form a line.
glBegin(GL_LINE_LOOP);
glVertex*(…);
…
glEnd();
Lines Loop Example
glBegin(GL_LINES_LOOP);
glVertex2i( 0,-20);
glVertex2i( 0, 20);
glVertex2i(-20, 0);
glVertex2i( 20, 0);
glEnd();
• Compare the above code with the one in the line strip. You can see
the last glVertex is removed from the line loop code.
glBegin(GL_LINE_ST
RIP);
glVertix2iv(p1);
glVertix2iv(p2);
glVertix2iv(p3);
glVertix2iv(p4);
glVertix2iv(p5);
glEnd();
glBegin(GL_LINES);
glVertix2iv(p1);
glVertix2iv(p2);
glBegin(GL_LINE_LO glVertix2iv(p3);
OP); glVertix2iv(p4);
glVertix2iv(p1); glVertix2iv(p5);
glVertix2iv(p2);
glVertix2iv(p3); glEnd();
glVertix2iv(p4);
glVertix2iv(p5);
glEnd();
Understanding Check 1
• How many vertices should we determine to draw
this shape using GL_LINES?
• How many vertices should we determine to draw
this shape using GL_LINE_STRIP?
• Write the code that draws this shape using
GL_LINE_STRIP
Draw Triangles
• There are three ways to draw triangles: normal triangles ,triangle
strip, triangle fan.
• A triangle has 3-vertices (corners).
• Set the color3ub or color3f before drawing the triangle.
• The triangles drawn are filled by default with the drawing color.
Draw Triangles
• Triangles are drawn filled by default. However, one can choose to use
glPolygonMode(face, fill_mode); where:
• face can be either GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK. It
indicates the drawing of the polygon is front faced or back faced. This used
in 3D drawing.
• fill_mode can be either GL_FILL, GL_LINE, GL_POINT. It indicate the filling
color of a triangle.
• GL_FILL is the default which fill the polygon with solid color.
• GL_LINE is drawing the polygon with border lines (outline or wireframe).
• GL_POINT is drawing the triangle with points.
• Remember a triangle is a polygon.
Normal Triangles
• Every 3-points from the list of points are grouped.
• Last points that are less than 3-points from the list of points are
discarded.
• Every group is drawn separately.
• Every group will construct a color filled triangle. Use glColor3f or
glColor3ub to fill the triangle color.
glBegin (GL_TRIANGLES);
glVertex*(…);
...
glEnd();
Normal Triangles
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLES);
glVertex2i(0, 0);
glVertex2i(10, 10);
glVertex2i(19, 0);
glVertex2i(4, 4);
glEnd();
glBegin (GL_TRIANGLE_STRIP);
glVertex*(…);
...
glEnd();
Strip Triangles
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(-10, 0);
glVertex2i(0, 10);
glVertex2i(10, 0);
glColor3f(0, 0, 1); // shading
glVertex2i(15, 10);
glEnd();
To avoid shading, we need to draw two triangles within separate glBegin/glEnd blocks.
Strip Triangles
glColor3f(0, 0, 0);
glBegin(GL_LINES);
glVertex2i(-20, 0); glVertex2i(20, 0);
glVertex2i(0,-20); glVertex2i(0, 20);
glEnd();
glColor3f(0, 0, 1);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(-3,0); glVertex2i(-5,-10);
glVertex2i(-3,-8); glVertex2i(5,-10);
glVertex2i(3,-8); glVertex2i(5,2);
glVertex2i(3,0); glVertex2i(-5,2);
glVertex2i(-3,0); glVertex2i(-5,10);
glEnd();
Triangle Fans
The first three points create the first triangle.
Each new point forms a triangle with the previous point and the
first point.
• Use glColor3f or glColor3ub to fill the triangle with a specified color.
Triangle Fans
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0, 0, 1);
glBegin(GL_TRIANGLE_FAN);
glVertex2i(0, 0);
glVertex2i(10, 0);
glVertex2i(7, 7);
(-7,7) (7,7)
glVertex2i(-7, 7); 2
glVertex2i(-10, 0); (-10,0)
3 1
(10,0)
glVertex2i(10, 0);
glEnd();
Quads
• There are two ways to draw quads: normal quads and quad strips. A
quad has four vertices (corners).
• Set the color using glColor3ub or glColor3f before drawing the quad.
Quads are filled by default with the assigned drawing color.
Normal Quads
• Every 4 points from the list of points are grouped.
• Any remaining points less than 4 are discarded.
• Each group is drawn separately.
• Each group forms a filled quad using the assigned color.
• Use glColor3f or glColor3ub to set the quad color.
glBegin(GL_QUADS);
glVertex*(...);
...
glEnd();
Quad Example
glColor3ub(255, 0, 0);
glBegin(GL_QUADS);
glVertex2i(0, 0);
(0,6) (6,6)
glVertex2i(6, 0);
glVertex2i(6, 6); (0,0) (6,0)
glVertex2i(0, 6);
glVertex2i(-6, 0);
glVertex2i(-6, -6);
glEnd();
10,10
0,0
Polygon
• A polygon is any shape with more than 2-sides (i.e. 3-points).
• Same as Line Loop but filled with color.
• However, when drawing a polygon, one must be careful in ensuring
that it is a plane convex figure, i.e., it lies on one plane and has no
'bays' or 'inlets’.
Polygon
A polygon is called convex if the line joining any two interior points of
the polygon lies completely inside the polygon. A non-convex polygon
is said to be concave.
(7,7)
• In OpenGL using GLUT, we can capture user input from the mouse and
keyboard by registering callback functions.
• Register functions:
glutMouseFunc (myMouse); // the mouse callback function
glutKeyboardFunc (myKeyboard); // the keyboard callback function
• 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) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
cout << "Left Mouse Button Pressed";
}
• Button: Identifies which button was clicked GLUT_LEFT_BUTTON,
GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON.
• State: Tells if the button was pressed (GLUT_DOWN) or released
(GLUT_UP).
• x, y: Mouse cursor position (in pixels) 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 the next slide
Code for Mouse-controlled Polyline (LINE_STRIP)
void myMouse(int button, int state, int x, int y){
#define NUM 20 // maximum of 20 points
static GLintPoint List[NUM]; // Stores the points
static int last = -1; // last point used so far
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && last < (NUM -1)){
List[++last].x = x; // add new point to list
List[ last].y = screenHeight - y; // GLUT (top-left)
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_LINE_STRIP); // redraw the polyline
for(int i = 0; i <= last; i++)
glVertex2i(List[i].x, List[i].y);
glEnd(); visualization of the polyline based on
sequential mouse clicks. Each blue dot
glFlush();} represents a mouse click, and
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) the lines connect these points to form
the polyline.
last = -1; // reset the list to empty
}
Example of the click events
• int glutCreateMenu(myMenu);
//Creates a menu and returns a menu ID
• void myMenu(int num);
// Call back, num is which menu item was selected
• void glutAddMenuEntry(char* name, int value);
// Adds an option (item) to the menu with a name and a
value.
• void glutAttachMenu(int button);
// Attach menu to one of (GLUT_RIGHT_BUTTON,
GLUT_MIDDLE_BUTTON, or GLUT_LEFT_BUTTON)
GLUT Menu-Example
y=2x+3
•Slope m=2 → The line rises by 2 for every 1 step right.
•Y-intercept b=3 → The line crosses the y-axis at (0,3).
Line Equation
■ Slope (m):
y
y2
y1
b x1 x2 x
6
Example
x y
0 2(0)+1 = 1
1 2(1)+1 = 3
2 2(2)+1 = 5
3 2(3)+1 = 7
4 2(4)+1 = 9
DDA ALGORITHM
DDA
Mar-26 9
DDA
Mar-26 10
DDA Algorithm for Drawing a Line
■ If m =1: y m=1
y2-y1 = x2-x1 y2
y2-y1
y2-y1 m= x2-x1
y1
45
x1 x2 x
x2-x1
DDA Algorithm for Drawing a Line
y m=1
• If |m|<1 (Left-to-right)
y2-y1
• ∆x = 1 m= x2-x1
• 𝑦𝑘+1 = 𝑦𝑘 + 𝑚; y2
y2-y1 y1
• For (k=0; k< 𝑥2 − 𝑥1 ; k++) {
𝑥𝑘+1 = 𝑥𝑘 + 1; x1 x2 x
𝑦𝑘+1 = 𝑦𝑘 + 𝑚;
x2-x1
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawing a Line
FYI
y m=1
• if |m|<1 (right-to-left)
y2-y1
• ∆x = -1 m= x2-x1
• 𝑦𝑘+1 = 𝑦𝑘 − 𝑚; y2
y2-y1 y1
• For (k=0; k< 𝑥2 − 𝑥1 ; k++) {
𝑥𝑘+1 = 𝑥𝑘 − 1; x1 x2 x
𝑦𝑘+1 = 𝑦𝑘 − 𝑚;
x2-x1
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawing a Line
y2-y1
y m= m=1
x2-x1
■ |m|>1 (left to right)
– ∆y=1 y2
1
– 𝑥𝑘+1 = 𝑥𝑘 + ; y2-y1
𝑚
y1
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawinga Line
|m|<1 |m|>1
Mar-26 16
Example 1
Mar-26 17
Example 1
𝑥1 = 2, 𝑦 =1,
m = 0.6667
𝑥𝑘+1 = 𝑥𝑘 + 1;
𝑦𝑘+1 = 𝑦𝑘 + 𝑚;
Mar-26 18
Example 2
Advantages: Disadvantages:
• Faster than direct use of line • Less suited for hardware
equation. implementation due to multiplication
and division operation.
• Does not use multiplication
theorem. • Involvement of round-off functionality
(consumes a lot of time) and
• Simple and easier to calculate since accumulations of rounding off values
each step has only two additions. cause accumulation error.
• Slower than Bresenham’s algorithm
because it uses real arithmetic
(Floating Point operation)
BRESENHAM’S
ALGORITHM
Bresenham’s Line Algorithm
Advantages Disadvantage:
■ Faster than DDA because it does not ■ This algorithm is meant for basic line
involve floating point calculations like drawing only Initializing is not a part
DDA Algorithm of Bresenham's line algorithm. So, to
draw smooth lines, you should want
■ Involves only integer arithmetic.
to look into a different algorithm.
■ It can be implemented using
hardware because it does not use
multiplication and division.
COMPUTER GRAPHICS
501472-3
Lecture 4- Circle and midpoint circle algorithms
Cartesian Coordinates
• Circle properties:
• Center (xc , yc)
• Radius r
• Equation of circle:
• Cartesian Coordinates: A point in this system is represented by a
pair of numerical coordinates, (x,y)
• r = (x − x )2 + ( y − y )2
c c
Cartesian Coordinates
Computer Graphics 3
Polar coordinates
◦ Polar coordinates: A point is represented by (r,θ), where r is the distance from
the origin (radius), and θ is the angle from the reference direction to the line
connecting the origin to the point.
◦ [Link]
◦ r = xc .cos
◦ x = xc + [Link]
◦ y = yc + [Link]
◦ = r
• Time consuming computation.
• Float numbers
• Require trigonometric and multiplication calculation.
Circles Symmetry
• Quadrant circle symmetry: A circle divided into four equal parts by its horizontal and
vertical diameters exhibits quadrant symmetry.
(-x,y) (x,y)
(-x,-y) (x,-y)
Circles Symmetry
Computer Graphics 7
Midpoint Drawing Circles Algorithm
• Given the center point and radius of circle, Mid Point Circle Drawing Algorithm
attempts to generate the points of one octant.
• The points for other octants are generated using the octant symmetry property.
Procedure-
Given:
•Centre point of Circle = (X0, Y0)
•Radius of Circle = R
The points generation using Mid Point Circle Drawing Algorithm involves the following steps-
Step-01:
Step-02:
Computer Graphics 9
Step-03:
• Suppose the current point is (Xk, Yk) and the next point is (Xk+1, Yk+1).
• Find the next point of the first octant depending on the value of decision parameter P k.
Follow the below two cases:
xk+1 = xk+1
pk <0 yk+1 = yk
pk+1 = pk + 2xk+1+1
Two cases
xk+1 = xk + 1
pk >0 yk+1 = yk - 1
pk+1 = pk + 2xk+1+1 – 2yk+1
Step-04:
If the given center point (X0, Y0) is not (0, 0), then do the following and plot the
point:
•Xplot = Xcurrent + X0
•Yplot = Ycurrent + Y0
Step-05:
Keep repeating Step-03 and Step-04 until Xplot >= Yplot.
Step-06:
• Step-05 generates all the points for one octant.
• To find the points for other seven octants, follow the eight-symmetry property
of circle.
Input r and (xc, yc).
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk)
xk+1 = xk+1
If (pk<0) {
yk+1 = yk
pk+1 = pk + 2xk+1+1
Draw (xc+xk+1, yc+yk+1) }
else {
yk+1 = yk-1
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) }
k=k+1 This figure help you complete the circle using the eight-
symmetry property of circle.
Computer Graphics 12
Drawing CirclesAlgorithm (octant)
Draw a circle r=10, (xc, yc)=(0, 0)
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk) k X Y P
xk+1 = xk+1 0
If (pk<0) { 1
Yk+1 = yk 2
pk+1 = pk + 2xk+1+1 3
else { 5
6
yk+1 = yk-1
7
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) } Algorithm Terminates
These are all points for Octant-1.
k=k+1
Drawing CirclesAlgorithm (octant)
Draw a circle r=10, (xc, yc)=(0, 0)
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk) k X Y P
xk+1 = xk+1 0 0 10 -9
If (pk<0) { 1 1 10 -6
Yk+1 = yk 2 2 10 -1
pk+1 = pk + 2xk+1+1 3 3 10 6
else { 5 5 9 8
6 6 8 5
yk+1 = yk-1
7 7 7 6
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) } Algorithm Terminates
These are all points for Octant-1.
k=k+1
Drawing CirclesAlgorithm (octant)
■ Algorithm calculates all the points of octant-1
and terminates. Octant-1 Octant-2
Points Points
■ Now, the points of octant-2 are obtained using
(0, 10) (7,7)
the mirror effect by swapping X and Y
coordinates (i.e., (1, 10) (8, 6)
(2, 10) (9, 5)
(3, 10) (9, 4)
(4, 9) (10, 3)
(5, 9) (10, 2)
(6, 8) (10, 1)
(7,7) (10, 0)
These are all points for
Quadrant-1 and 2. Do the same
with Octan 3-8
Drawing Circles Algorithm (Quadrant)
■ Here, all the points have been generated with respect to quadrant-1-
Q-1 (X,Y) Q-2 (-X,Y) Q-3(-X,-Y) Q-4 (X,-Y)
(0, 10) (0, 10) (0, -10) (0, -10)
(1, 10) (-1, 10) (-1, -10) (1, -10)
(2, 10) (-2, 10) (-2, -10) (2, -10)
(3, 10) (-3, 10) (-3, -10) (3, -10)
(4, 9) (-4, 9) (-4, -9) (4, -9)
(5, 9) (-5, 9) (-5, -9) (5, -9)
(6, 8) (-6, 8) (-6, -8) (6, -8)
(7,7) (7,7) (7,7) (7,7)
(8, 6) (-8, 6) (-8, -6) (8, -6)
(9, 5) (-9, 5) (-9, -5) (9, -5)
(9, 4) (-9, 4) (-9, -4) (9, -4)
(10, 3) (-10, 3) (-10, -3) (10, -3)
(10, 2) (-10, 2) (-10, -2) (10, -2)
(10, 1) (-10, 1) (-10, -1) (10, -1)
(10, 0) (-10, 0) (-10, 0) (10, 0) Computer Graphics 16
Drawing Circle using C++ functions
const int MAX_POINTS = 20; // Maximum number of points int // Function 2: Draw symmetric points using OpenGL
circlePointsX[MAX_POINTS]; void drawCirclePoints(int x, int y) {
int circlePointsY[MAX_POINTS]; glBegin(GL_POINTS);
int pointCount = 0; // Track the number of points glVertex2i(xc+x, yc+y); glVertex2i(xc-x, yc+y);
int xc = 0, yc = 0, r = 3; glVertex2i(xc+x, yc-y); glVertex2i(xc-x, yc-y);
glVertex2i(xc+y, yc+x); glVertex2i(xc-y, yc+x);
// Function 1: Midpoint Circle Algorithm for One Octant glVertex2i(xc+y, yc-x); glVertex2i(xc-y, yc-x);
void midpointCircleAlgorithm(int r, int xc, int yc) { glEnd();
int x = 0; int y = r; int p = 1 - r; }
circlePointsX[pointCount] = x;
circlePointsY[pointCount] = y; // Function 3: Draw all octants using computed points void drawCircle() {
pointCount++; glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
while (x < y && pointCount < MAX_POINTS) { for (int i = 0; i < pointCount; i++) {
x++; drawCirclePoints(circlePointsX[i], circlePointsY[i]);
if (p < 0) { }
p = p + 2 * x + 1; glFlush();
} else { }
y--; // Display function
p = p + 2 * x + 1 - 2 * y; void display() {
} midpointCircleAlgorithm(r, xc, yc);
circlePointsX[pointCount] = x; drawCircle();
circlePointsY[pointCount] = y; }
pointCount++;
}
}
HW: Drawing CirclesAlgorithm
Computer Graphics 18
COMPUTER GRAPHICS
501472-3
Lecture 5- Model Viewing
Windowing I
World
Coordinates
Windowing II
■ When we display a
Window
scene only those objects wymax
within a particular window
are displayed
wymin
wxmin wxmax
World Coordinates
Windowing III
wxmin wxma
World Coordinates x
TWO-DIMENSIONAL
VIEWING
Introduction To Windowing
■ Graphics software allows user to select which part of the picture to show on the display
device and where that part to be placed on the display device
■ A Cartesian coordinate system (world coordinate system) is used to define the picture
■ In a two-dimensional picture , a view is selected by deciding a subarea of total picture
■ A user can select single area or multiple areas for display
■ The picture part within the selected areas are then mapped (converted) onto the
specific areas of the device coordinates
Introduction To Windowing
wymin wymin
wymax wymax
wymin wymin
wymin wymin
wymax
wymin
wxmin wxmax
Understanding Check 1
3. If two users select different windows from the same scene, what changes?
A) The display device
B) The actual objects in the file
C) The part of the scene each user sees
D) The entire scene content
4. If two windows show different parts of the world coordinate scene but map to the
same viewport, what does the user experience?
A) They switch between scenes rapidly
B) They see different content in the same screen area
C) They see the full scene together
D) They get an error
THREE-DIMENSIONAL
VIEWING
Graphics Rendering Pipeline
● Rendering: conversion from scene to image
3D
2D Image
Scene
■ Model & Camera Transformation → Places objects in the world and sets the camera
viewpoint (place the model in the world and the camera view)
■ Lighting → Calculates how light hits the objects.
Graphics Pipeline
Projection NDCS
Normalized DCS
2D Image
Device
Coordinate
SCS
System
Three-Dimensional Viewing
2. Perspective Projection transforms object positions to the view plane while converging to a
center point of projection.
• Produces realistic views but does not preserve relative proportions. Projections of distant
objects are smaller than the projections of objects of the same size that are closer to the
projection plane.
Parallel Projection
■ Classification:
Orthographic Parallel Projection and Oblique Projection:
■ Orthographic parallel projections are done by projecting points along parallel lines
that are perpendicular to the projection plane.
■ Oblique projections are obtained by projecting along parallel lines that are NOT
perpendicular to the projection plane.
Parallel Projection
• Goal: Cut off parts of objects outside the view volume to save rendering effort.
• Any procedure that identifies which portion of a picture is inside or outside of a
specified region (area) is called as 'clipping algorithm)
• The region (area) which is used to clip an object is called as 'clip window'
Clipping
■ For the image below consider which lines and points should be kept and which ones
should be clipped
P4
Window P2
wymax
P6
P3
P1
P7 P5
P9
P8
wymin
P10
wxmin wxmax
Point Clipping
Window
• Example: wymax
P2
Clipped
• P5 is not clipped because: P5
P1
P7 Points Within the Window
• wxmin ≤ x ≤ wxmax AND wymin ≤ y ≤ wymax are Not Clipped
P9 P8
wymin
Clipped P10
wxmin wxmax
Understanding Check 3
Window
Is the point (2,6) clipped or not? 7
3 10
Line Clipping
Harder - examine the end-points of each line to see if they are in the window or not
Both end-points
Don’t know!
outside the window
Brute Force Line Clipping
In Part 2: We calculate the intersection points of lines that fall into category 3 (partially
inside and partially outside the window).
Bit-Based Calculations:
• If first bit is 1: Line intersects the left vertical boundary.
Intersection point Y=Y1+m(XWmin−X1)
• If second bit is 1: Line intersects the right vertical boundary.
Intersection point Y=Y1+m(XWmax−X1)
• If third bit is 1: Line intersects the bottom horizontal boundary.
Intersection point X = X1+(YWmin−Y1)/m
• If fourth bit is 1: Line intersects the top horizontal boundary.
Intersection point X=X1+(YWmax−Y1)/m
Cohen–Sutherland Line Clipping
Algorithm (Steps)
■ Step 1: Read the two end points of a line P1(X1,Y1) and P2(X2,Y2)
■ Step 2: Read the lower-left and upper-right coordinates of the clipping window.
■ Step 3: Assign 4-bit region codes to P1 and P2.
■ Step 4: Check the category of the line based on region codes:
• Category 1: Line is completely inside the window, accept and display the line.
• Category 2: Line is completely outside the window, reject the line
• Category 3: Line is partially inside and partially outside the window, continue to
next steps.
■ Step 6: Find the intersection boundaries of the clipping window and proceed with
calculating intersection points.
Cohen–Sutherland Example
Window
Consider the line P₉ to P₁₀ below: wymax
• Start at P₁₀
• From the region codes of the two end-
points, we know the line doesn’t cross the P9 [0000]
left or right boundary wymin
P10’ [0000]
Given:
Window
• Clipping Window boundaries: 30
• WXmin=10
(5,15)
• WXmax=40
• WYmin=10
• WYmax=30 10
• Point A: (5,15) 10 40
• Point B: (30,5)
Polygon Clipping
■ Collection of connected lines is considered as Polygon.
■ A polygon clipper takes as input the vertices of a polygon and returns one(or more)
polygons.
■ A closed Polygon when clipped then we may get one or more open polygon or lines.
– After clipping the resulting polygon should be closed.
– It requires that lines ab & cd be added to make it closed polygon.
– Hence it is difficult to find out which pieces of sections should be joined to
make the clipped polygon closed.
C
d c
D
a
A
b
B
Polygon Clipping
■ Another problem occurs when clipping a closed polygon into several distinct smaller
polygons as shown:
Clipping
Window
Concave
Polygon
Polygon Clipping
C D
D C
L R
E
L R
E B B
A
A
SUTHERLAND-HODGMAN ALGORITHM
Each edge of the polygon must be tested
against each edge of the clip rectangle; new
edges must be added, and existing edges must
be discarded, retained, or divided. Multiple
polygons may result from clipping a single
polygon. We need an organized way to deal
with all these cases.
Steps of Sutherland-Hodgman's polygon
clipping algorithm
■ Polygons can be clipped against each edge of the window one at a
time.
■ Vertices which are kept after clipping against one window edge are
saved for clipping against the remaining edges.
■ Note that the number of vertices usually changes and will often
increases.
V1
V2 V1
V1’
V2
Out → in in → in
Save V1’,V2 Save V2
V2
V1
V1’
V2 V1
• [Link]
• [Link]
Coordinate Systems
■ In 3D we have XYZ-coordinates.
■ The three axes are perpendicular to each other.
■ The point of intersection is called the origin which is (0,0,0).
■ To define a point in space, we give 3-numbers (X,Y, Z).
Coordinate Systems
Range of view
• In OpenGL, negative Z axis is inside the
screen. (i.e. moving object toward Your eyes
negative Z-axis will move the object Negative z-axis
deeper into the scene, away from the
viewer.
Imaginary line
• OpenGL simulate your eyes.
• Your eyes is looking into the negative z-
axis.
Coordinate Systems
Range of view
Q2: Which projection would you choose for accurately displaying an architectural
blueprint?
A) gluPerspective
B) glFrustum
C) glOrtho
D) gluLookAt
3D SHAPES
3D Functions:
• glutSolidCube(side)
• glutWireCube(side)
3D Functions:
A ring-shaped object:
• glutSolidTorus(thickness, radius, subdiv1, subdiv2)
• glutWireTorus(thickness, radius, subdiv1, subdiv2):
3D Functions:
• glutSolidTeapot(size)
• glutWireTeapot(size)
Understanding Check 2
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glFrustum(-2.0, 2.0, -2.0, 2.0, 5.0, 100.0);
gluLookAt(5.0, 5.0, 10.0, // Camera position
0.0, 0.0, 0.0, // Look-at point (center of cube)
0.0, 1.0, 0.0); // Up vector
glColor3f(0.8f, 0.1f, 0.1f); // Dice red
glutSolidCube(4) // Call the cube drawing function
glutSwapBuffers();
}
ANIMATION
Animations
Animation is the art of making drawings move or the method of photographing successive
drawings, models, and puppets and manipulating them to appear as moving images.
Double buffer
3D_LecTorus
Double buffer
Example:
void update(int value) {
…
}
int main(int argc, char **argv) {
…
glutTimerFunc(30, update, 0);
…
}
#include <GL/glut.h>
float posX = 0.0f; // Initial x position of the square
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glTranslatef(posX, 0.0f, 0.0f); // Translate the square along the x-axis
glColor3f(1.0, 1.0, 1.0); // Set color to white
glBegin(GL_QUADS);
glVertex2f(-0.2, -0.2); glVertex2f(0.2, -0.2); glVertex2f(0.2, 0.2); glVertex2f(-
0.2, 0.2);
glEnd();
glutSwapBuffers();
}
void update(int value) {
posX += 0.01f; // Increment x position
if (posX > 1.0) {
posX = -1.0; // Reset x position when reaching the right edge of the screen
}
glutPostRedisplay(); // Request redisplay to animate continuously
glutTimerFunc(16, update, 0); // Call update function again after 16 milliseconds
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Animation Example");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Understanding Check 3
Q1: Why is glutSwapBuffers() preferred over glFlush() in an animation loop using double
buffering?
A) It improves color rendering
B) It allows drawing in both front and back buffers simultaneously
C) It avoids the need for a depth buffer
D) It swaps the completed frame to the screen for smooth rendering
Q2: An animation appears choppy and inconsistent in speed. Which of the following is the
most likely cause?
A) The field of view is too wide
B) glutSwapBuffers() is not used
C) The viewport is not resized properly
D) No timer function is the frame rate
Understanding Check 3
1. 2D animation
2. 3D animation
3. Stop motion animation
4. Motion graphics
■ 2D ANIMATION
With traditional animation, animators were required to keep drawing
the same characters over and over again.
■ That is not needed with vector-based 2D animation since the
motion is controlled by vectors.
■ With vectors, every creation can be reused as many times as the
animator wishes, without having to re-create the same
backgrounds, characters, and so on.
■ Moreover, the movement of the characters is controlled by
vectors.
Types Of Animation
■ 3D ANIMATION
■ They continue this process until they have a photo for each frame they want to use
for their animation.
■ Similar to traditional 2D animation, when all frames are shown in a sequence right
after the other, the objects seem like they are moving on their own. That’s how the
illusion of movement is created with stop motion animation.
■ Before CGI animation, stop motion animation was the only animation type that gave
viewers that “special effects” feeling.
Motion Graphics
■ Motion graphics can be 2D and 3D and are mainly used to animate text, logos, and
video clips. Motion graphics are called all digital graphics that create the illusion of
motion.
Computer Graphics 5
Why use transformations?
Computer Graphics 6
Why Transformations?
Computer Graphics 7
ObjectsTransformation
• 5-type of object Transformation:
• Translation or Shifting: moving objects
• Scaling: change size.
• Rotation: moving about a point by an angle.
• Reflection: mirror of an object.
• Shearing: distort the object (deformation).
1 0 0 𝑑𝑥 1 0 0 0
𝑑𝑦 0 cos 𝜃 − sin 𝜃 0
Translation: 0 1 0 Rotation Rx 𝜃 :
0 sin 𝜃 cos 𝜃 0
0 0 1 𝑑𝑧
0 0 0 1 0 0 0 1
𝑠𝑥 0 0 0 cos 𝜃 0 sin 𝜃 0
0 𝑆𝑦 0 0 Rotation Ry 𝜃 : 0 1 0 0
Scale: 0 − sin 𝜃 0 cos 𝜃 0
0 𝑆𝑧 0
0 0 0 1 0 0 0 1
TRANSLATION
Translation
Computer Graphics 12
Translation
Computer Graphics 14
Translation Example 1
Computer Graphics 15
Translation Example 2:
■ A triangle with vertices coordinates: (1,0), (3,0), (2,2). What its new coordinates
after shifting it by 1 in the x-axis and y-axis.
■ Solution:
(3,3)
– x’= x + 1 and y’ = y+1.
(2,2)
Old New
Coordinate Coordinate (4,1)
(2,1)
s s
(1,0) (2,1) (1,0) (3,0)
(3,0) (4,1)
(2,2) (3,3)
Computer Graphics 16
Translation In OpenGL
glTranslate[fd](Tx, Ty, Tz): It will shift the whole coordinates by Tx, Ty, Tz.
■ glTranslated() takes double-precision floating-point values.
■ glTranslatef() takes single-precision floating-point values.
glColor3ub(255, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(2,0); glVertex2i(2,2);
glVertex2i(0,2);
glEnd();
glColor3ub(0, 0, 255);
glTranslatef(1.0,1.0,0); // Translate the coordinate system by
(1.0, 1.0, 0)
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(2,0); glVertex2i(2,2);
glVertex2i(0,2);
glEnd();
Computer Graphics 17
Understanding Check 1
Computer Graphics 21
Scaling Example:
■ Sx=Sy=0.5:
Old New
Coordinates Coordinates
(0,0) (0,0)
(4,0) (2,0) (4,3)
(0,4)
(4,3) (2,1.5)
(0,1.5) (2,1.5)
(0,3) (0,1.5)
Computer Graphics 23
Scaling Example 2
■ Solution:
Old New
◦ Sx=Sy=2: Coordi Coordin
◦ Shift point (1,1) to (0,0) nates ates
■ (Xf,yf) = (1,1). (1,1) (1,1)
◦ x’ = xf + (x-xf)*sx; (2,1) (3,1)
◦ y’ = yf + (y-yf)*sy (2,2) (3,3)
(1,2) (1,3)
Computer Graphics 24
Scaling Example 2
(1,3) (3,3)
(1,2) (2,2) (1,2)
(2,2)
Computer Graphics 25
OpenGL Scaling
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();
Computer Graphics 26
OpenGL Scaling:
Example .. What is the output of this code?
#include <GL/glut.h> void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
void drawTriangle() {
glEnd();
void drawScaledTriangle() {
glPushMatrix();
drawTriangle();
glPopMatrix();
}
Understanding Check
Draw a rectangle then apply a scaling transformation to make the width half its
size and keep the height the same. Draw the scaled rectangle.
ROTATION
Rotation
• In linear algebra, a rotation matrix is used to perform
a rotation in Euclidean space.
Computer Graphics 33
Rotation
• Thus, the new coordinates (x′, y′) of a point (x, y) after a 2D rotation
around the origin (0,0) by an angle θ in the counterclockwise
direction is:
• x' = x cos θ - y sin θ ; y' = x sin θ + y cos θ
Computer Graphics 35
Rotation In Opengl
• glRotatef(angle, x, y, z).
• The last three parameters (x, y, z) are clamped to the range of [0, 1].
Computer Graphics 36
Rotation In Opengl
Source: [Link]
Computer Graphics 37
Rotation In Opengl
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();
glRotatef(45, 0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();
Computer Graphics 38
Rotation In Opengl
Computer Graphics 39
REFLECTION
Reflection
Computer Graphics 41
Reflection
Computer Graphics 42
Reflection
Computer Graphics 43
Reflection Example
Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to x-axis
Solution:
Old Coordinates New Coordinates
(1,1) (1, -1)
(3,1) (3, -1)
(3,5) (3, -5)
(1,5) (1, -5)
Computer Graphics 44
Reflection Example
Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to y-axis
Solution:
Old Coordinates New Coordinates
(1,1) (-1, 1)
(3,1) (-3, 1)
(3,5) (-3, 5)
(1,5) (-1, 5)
Computer Graphics 45
Reflection Example
Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to origin
Computer Graphics 46
Reflection in OpenGL
glPushMatrix();
glScalef(-1.0, 1.0, 1.0); // across Y-axis
drawTriangle();
glPopMatrix();
glPushMatrix();
glScalef(-1.0, -1.0, 1.0); // across origin
drawTriangle();
glPopMatrix();
glPushMatrix();
glScalef(1.0, -1.0, 1.0); // across X-axis
drawTriangle();
glPopMatrix();
glFlush();
}
Order of transformation
■ Generally, do not expect different orders of transforms to produce the same result, because
matrix multiplication is not commutative.
■ Another way to think about transforms.
– Move a local coordinate system.
– Each object has a local coordinate system
– Transforms happen relative to this coordinate system.
– Unfortunately, breaks down when scale is involved.
Rotation About an Arbitrary Point
Note: The order in the code appears reversed compared to the written explanation because OpenGL
applies transformations in reverse order (matrix multiplication is done from the right).
Order of Transformations
■ The transformation matrices appear in reverse order to that in which the transformations
are applied.
■ In OpenGL, the transformation specified most recently is the one applied first.
■ In each step:
– C <= I
– C <= CT(4.0, 5.0, 6.0)
– C <= CR(45, 1.0, 2.0, 3.0)
– C < = CT(-4.0, -5.0, -6.0)
■ Finally
– C = T(4.0, 5.0, 6.0) CR(45, 1.0, 2.0, 3.0) CT(-4.0, -5.0, -6.0)
COMPUTER GRAPHICS
501472-3
Lecture 7- 2D/3D deformation
Deformation
■ X-Shear
■ The X-Shear preserves the Y coordinate, and changes are made to X
coordinates, which causes the vertical lines to tilt right or left as shown in
below figure.
Shearing
X’ = X + Shx . Y
Y’ = Y
■ Y-Shear
■ Similarly, the Y-Shear preserves the X coordinate and changes are made to Y
coordinates, which causes the horizontal lines to tilt up or down as shown in
below figure.
1 0 0 0
𝑠ℎ𝑦 1 0 0
𝑌𝑠ℎ =
0 0 1 0
0 0 0 1
X’ = X
Y’ = Y + Shy . X
Deformation - Shearing
0, 2 2, 2
0, 0 2, 0
■ The vertices are: (0, 0), (2, 0), (8, 2), 6, 2):
■ The new vertices are:
– X= x + shx.Y
– Y= y
■ (0,2) → x =6, y=2
■ (2,2) → x=8, y=2
■ (0,0) → remains unchanged (bottom-left).
■ (2,0) → remains unchanged (bottom-right).
Deformation - Shearing
1 𝑠ℎ𝑥 0 0
0 1 0 0
𝑋𝑠ℎ =
0 0 1 0
0 0 0 1
Deformation - Shearing
■ Another thing about OpenGL, is that it will consider the matrix in column-major order.
So, OpenGL stores matrices as (in transpose form):
■ The transformation matrix for the shearing, is stored in OpenGl in a transpose form.
Therefore, shearing in the x- direction as:
T
1 a 0 0 1 0 0 0
0
1 0 0 a 1 0 0
=
0 0 1 0 0 0 1 0
0 0
0 0 1 0 0 1
Deformation - Shearing
GLfloat shearMatrix[16] = { 1, 0, 0, 0,
3, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
glPushMatrix(); // Save the current matrix on the stack
// Multiply the current matrix(by the shearing matrix
glMultMatrixf(shearMatrix);
// Draw a square that will be sheared along the x-axis
glBegin(GL_QUADS);
glVertex2f(-2, -2);
glVertex2f(2, -2);
glVertex2f(2, 2);
glVertex2f(-2, 2);
glEnd(); // Restore the original matrix
glPopMatrix();
COMPUTER GRAPHICS
501472-3
Lecture 9- Light
Lighting Models and Shading
■ For visual realism, lighting models
Ambient lighting :
have been developed to illuminate
the surfaces of solid models
■ These models incorporate
– ambient lighting and illumination
incident reflected light
– diffuse reflection of directional
light
lighting
– specular reflection of directional
lighting
incident reflected light
light
2
Light Source
Ray Tracing Shadow Ray
Eye
Object
Eye Ray
Shadow Ray
Object
Light Source
■ Ray tracing traces a ray of
light from the eye to a light
source
■ Ray tracing realistically
renders scenes with shiny
and transparent objects
3
Radiosity
■ Diffuse illumination
results from the
absorption and reflection
of diffuse light from many
objects in the scene
■ Radiosity uses thermal
models of emission and
reflection of radiation to Radiosity is very good at rendering
accurately calculate architectural interiors
diffuse lighting
4
Light source Light
Object
sun
Light
rays
• Light source can be either:
– A light at some specified position (Positional light)
• In Opengl, you can define 8‐light sources, they are called: GL_LIGHT0, GL_LIGHT1,
GL_LIGHT2, …, GL_LIGHT7
Enable light in Opengl
• In order to work with light in Opengl, we should enable the lighting, this is
done by writing:
– glEnable(GL_LIGHTING).
• Then we need to enable the light source. For example, to enable light
source zero, we write:
– glEnable(GL_LIGHT0)
Different light source
■ Diffuse light: which is the color of the light that is directly falling on objects.
Ambient Light
■ Ambient light: is the light that is reflected many times such that its source is
unknown, then fall on objects.
Specular Light
■ Specular light: which is the shininess of the light source on the object.
Shading
■ Flat Shading
– Calculate one lighting calculation (pick a vertex) per triangle
– Color the entire triangle the same color
■ Gouraud Shading
– Calculate three lighting calculations (the vertices) per triangle
– Linearly interpolate the colors as you scan convert
■ Phong Shading
– While do scan convert, linearly interpolate the normals.
– With the interpolated normal at each pixel, calculate the lighting at each
pixel
Opengl functions forlight
• Example:
• To set the position of the light source light0, we write:
GLfloat light_position[] = {1.0, 1.0, 1.0} \\ white
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
• This will set the light source GL_LIGHT0 to be at position (1, 1, 1).
Opengl functions forlight
• In addition to the light color, we have material color for the object.
• We have the following for materials:
– Material color is called diffuse color.
– Material shininess color is called specular color
• Let's say you're looking at a red car. The sun emits a ray of white light.
• The ray bounces off the car and goes into your eye. Your eye detects that the
ray only contains red light, which is why you see a red car instead of a white
car.
• We know that white light contains all colors, so what happened to the green
and blue? The green and blue light was absorbed by the surface, and the
red light was reflected.
Absorption & Reflection Of Color
• When a light source with a color (such as red) illuminates a material with a different
color (like blue), the resulting color seen by the viewer is determined by the
interaction between the two colors.
• This interaction typically involves a component-wise multiplication of the light's color
with the material's color, a process known as "color blending.
• Resulting Diffuse Color:
• Red Component: 1 (light) * 0 (material) = 0
• Green Component: 0 (light) * 0 (material) = 0
• Blue Component: 0 (light) * 1 (material) = 0
• So, the resulting color will be (0, 0, 0) in RGB, which is black.
Absorption & Reflection OfColor
• What if we were to shine a pure cyan (blue + green) light on the red car? If
the car was pure red, it would look black, because it would absorb 100% of
the light.
Absorption & Reflection OfColor
• What about a cyan (blue + green) (0,1,1) light on a magenta (red + blue)
surface? Magenta color is (1, 0, 1). So green is absorbed and blue is
reflected.
Steps to Set the Light inOpengl
shadows
37
Example of Shading
38
Texture Mapping in OpenGL
■ GLubyte image[rows][cols]
void glTexImage2D (GLenum target, GLint level, GLint
internalFormat, GLsizei width, GLsizei height, GLint
border, GLenum format, GLenum type, const GLvoid
*pixels)
■ Note: both width and height must have the form 2m+2b, where m is
nonnegative integer, and b is the value of board.
Texture Object
■ Texture objects are an important new feature since OpenGL 1.1. A texture object
stores data and makes it readily available.
■ To use texture objects for your texture data, take these steps:
– Generate texture names.
– Initially bind (create) texture objects to texture data, including the image
arrays and texture properties.
– Bind and rebind texture objects, making their data currently available for
rendering texture models.
Naming a Texture Object
■ The same routine, glBindTexture(), both creates and uses texture objects.
void glBindTexture (GLenum target, GLuint textureName)
■ When using it first time, a new texture object is created. When binding to
previously created texture object, that texture object becomes active.
■ Example:
glBindTexture(GL_TEXTURE_2D, name);
Cleaning Up Texture Object
■ Rendering texture is similar to shading: It proceeds across the surface pixel-by pixel.
For each pixel, it must determine the corresponding texture coordinates (s, t), access
the texture, and set the pixel to the proper texture color.
Combining Lighting and Texturing
■ glEnable (GL_TEXTURE_2D)
■ glDisable (GL_TEXTURE_2D)
■ Enable/disable texture mapping
Automatic Texture-Coordinate Generation