0% found this document useful (0 votes)
8 views103 pages

Chapter - 3 - (0) Graphics

Uploaded by

mamok9635
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views103 pages

Chapter - 3 - (0) Graphics

Uploaded by

mamok9635
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 103

Faculty of

Computing &
Software
Eng’g
Program:
Computer
Science​
G3 CS
Computer Graphics

(Regular)

Instructor:
Addisu M. (Asst.
Prof)
2

Rendering Process
Ch re
r T ou
&

with OpenGL
ap e
h
F

te
r
3
What is OpenGL?
 OpenGL (Open Graphics Library)

Computer Graphics Sep 10, 2


- widely-used cross-platform appln programming
Interface (API) for rendering 2D and 3D graphics
images
- generate high-quality color images by rendering
with geometric and image primitives
- It forms many interactive applications
- It is independent of the hardware, operating, and
windowing systems in use
- provides a set of commands for rendering
graphics, making it a crucial tool for developers in
the game and simulation industries, among others.
- provides a set of functions that allows developers
4
What is OpenGL?
 OpenGL is based on GL graphics package

Computer Graphics Sep 10, 2


developed by the graphics hardware
manufacturer Silicon Graphics
- GL was a popular package but it was specific to
Silicon Graphics systems, i.e. code written
using GL would only run on Silicon Graphics
hardware
- to overcome this limitation, OpenGL was
developed in early 1992 as a free platform-
independent version of GL
 OpenGL - core library that contains the majority
of the functionality (around 130 graphics
5
What is OpenGL?
 You should make sure that you have access to

Computer Graphics Sep 10, 2


a C++ dev’t env’t that supports these two
libraries (OpenGL & glut)
 Turbo C++ does not support either of them
 Two possibilities are:
• Dev-C++ env’t (www.bloodshed.net) has
OpenGL built-in and glut can be easily added on
as a separate package
• Microsoft Visual C++ also has OpenGL built-
in but not glut. The glut library is available as a
6
Related Libraries
 glut (GL Utilities Toolkit): contains some

Computer Graphics Sep 10, 2


extra routines for drawing 3-D objects &
other primitives
- Using glut with OpenGL enables us to write
windows-system independent code
 glu (OpenGL Utilities): contains some extra
routines for projections and rendering
complex 3-D objects
 glui (OpenGL User Interface): contains some
extra routines for creating user-interfaces
- provides controls such as buttons,
7 Lack of Object
Orientation
 OpenGL is primarily a procedural API, which means it

Computer Graphics Sep 10, 2


doesn't follow OOP principles
 so there are multiple functions for a given logical
function,
 E.g. glVertex3f, glVertex2i, glVertex3dv,…..
 Characteristics of OpenGL leads to challenges
 Procedural Nature: OpenGL relies on a series of funcn
calls to perform operations, rather than encapsulating
functionality
 Multiple Functions for Similar Tasks: Because OpenGL
doesn't use classes to encapsulate related
functionality, there are multiple functions to handle
similar tasks.
8 Output Primitives &
Attributes
 OpenGL allows for rendering of several output

Computer Graphics Sep 10, 2


primitives, the basic building blocks for creating
images:
 Points: simplest primitive representing individual
vertices that can be rendered as points on the
screen.
 Lines: Represented as either individual line
segments or as connected continuous line strips.
 Triangles: composed of three vertices
 grouped into triangle strips or fans
 Quads: four-sided polygons that could also be
rendered using two triangles.
 less commonly used in modern OpenGL
 Polygons: General shapes defined by multiple
9 Output Primitives &

Attributes
attributes associated with primitives

Computer Graphics Sep 10, 2


determine how they are rendered, key
attributes include:
 Color: can be set for both the vertices and
fragments
 Texture: can be mapped onto primitives,
providing detailed surface appearances.
 Shading: OpenGL supports different shading
models, such as flat and smooth shading,
which determine how colors are interpolated
across the surface of a primitive.
 Lighting: define how light sources affect the
10
GLUT Functions
 Every routine provided by OpenGL or associated

Computer Graphics Sep 10, 2


libraries follows the same basic rule of syntax:
 prefix of the function name is either gl, glu, or glut
depending on which of these 3 libraries the routine
is from
 main part of the function name indicates the
purpose of the function
 suffix of the function name indicates the number
and type of arguments expected by the function
- eg., suffix 3f  3 floating point arguments are
expected
 Some function arguments can be supplied as
predefined symbolic constants – are always in
capital letters, and have the same prefix
11
GLUT Functions

Computer Graphics Sep 10, 2


glVertex3fv( ... )

Number of Data Type Vector


components b - byte omit “v” for
ub - unsigned byte
2 - (x,y) s - short scalar form
3 - (x,y,z) us - unsigned short
4 - (x,y,z,w) i - int glVertex2f( x, y )
ui - unsigned int
f - float
d - double
vector v refers to a array of three
floating-point values (coordinates of
a vertex in 3D space)
12
GLUT Functions
 OpenGL has a number of built-in data types to

Computer Graphics Sep 10, 2


help make it into a platform-independent
package
 Mostly, they have the same names as C++
data types but with the prefix GL attached
 E.g., GLshort, GLint, GLfloat & GLdouble –
built-in OpenGL data types
 Although you will find that your OpenGL code
will still work on your computer if you do not
use these data types, it will not be as portable
to other platforms so it is recommended that
you do use them
 #include <GL/glut.h>
13
Program Structure
 Most OpenGL programs have a similar

Computer Graphics Sep 10, 2


structure that consists of the following
functions
 main():
 defines the callback functions
 opens one or more windows with the
required properties
 enters event loop (last executable
statement)
 init(): sets the state variables
 Viewing
 Attributes
 Callbacks
14
Program Structure
#include <GL/glut.h> includes gl.h

Computer Graphics Sep 10, 2


int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|
GLUT_RGB);
glutInitWindowSize(500,500); define window
glutInitWindowPosition(0,0); properties
glutCreateWindow("simple");
glutDisplayFunc(mydisplay);display callback
set OpenGL state
init();
glutMainLoop(); enter event loop
}
15 Getting Started with
OpenGL
 to start writing OpenGL programs - header files

Computer Graphics Sep 10, 2


should be included depends upon which library(s)
are being used
 For example:
 If we only using the core OpenGL library, then add:
#include <GL/gl.h>
 If we want to use GL Utilities (routines for
projections and rendering complex) library:
#include <GL/glu.h>
 For the glui UI library we must add:
#include <GL/glui.h>
 If we want to use glut library (and this makes using
OpenGL) we do not need to include OpenGL or glu
16 Getting Started with
OpenGL
Libra Description Purpose Usage Functions

Computer Graphics Sep 10, 2


ry
GL/  Core  Provides the  Basic 3D  Vertex specification
gl.h OpenGL fundamental functions (glVertex*), Primitive
header file. functions, and drawing (glBegin,
 Contains transformations, constant glEnd), Matrix
the basic lighting for s manipulation
functions rendering (glMatrixMode,
primitives, glTranslate*), State
managing state, management
and interacting (glEnable, glDisable),
with the graphics Framebuffer
pipeline. operations
GL/  OpenGL  Offers higher-  Simplifie  Creating complex
glu.h Utility level utility s shapes (spheres,
Library functions for 3D complex cylinders, disks),
header objects, renderin Viewing
projections g tasks transformations
17 Getting Started with
OpenGL
Libra Description Purpose Usage Functions

Computer Graphics Sep 10, 2


ry
GL/  GLUI  Provides a way to  Used  GLUI_Button, GLUI_Sli
glui. (OpenGL create GUI when der, GLUI_EditText
h User elements like interacti
Interface) menus, buttons, ve GUI is
header checkboxes, text needed
boxes…
GL/  OpenGL  Provides  Ideal for  Window creation and
glut. Utility functions for beginner management, Input
h Toolkit window s and handling (keyboard,
header management, small mouse), Event loop
input handling, projects management, Simple
and event-driven primitive rendering
programming in  glutInit(), glutCreate
OpenGL. Window(), glutDispla
yFunc()
18 Getting Started with
OpenGL
 The following lines initialise the glut

Computer Graphics Sep 10, 2


library:
 glutInit(&argc, argv); // we must call this function
before any others in our glut/OpenGL program
 glutInitDisplayMode(GLUT_RGB|
GLUT_DOUBLE
Display ); // type of frame buffer we want
Mode Meaning
to have, double RGB buffer
GLUT_RGB Use RGB colors
GLUT_RGBA Use RGB plus a (for transparency)
GLUT_DOUBLE Use double buffering (recommended)
GLUT_SINGLE Use single buffering (not
recommended)
GLUT_DEPTH Use depth buffer (for hidden surface
19 Getting Started with
OpenGL
 The following lines initialise the glut

Computer Graphics Sep 10, 2


library:
 glutInitWindowSize(640, 480); // sets the
size of the display window in pixels
 glutInitWindowPosition(10, 10); // sets the
position at 10, 10 of the top-left corner of
the display window measured in pixels
 glutCreateWindow(“GLUT Points Demo”); //
creates the display window with attributes
defined by the previous calls
20 Getting Started with
OpenGL black clear color
void init()

Computer Graphics Sep 10, 2


{ opaque
glClearColor (0.0, 0.0, 0.0, 1.0); window

glColor3f(1.0, 1.0, 1.0);


. c fill with white
it
in glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
viewing volume
21 OpenGL Event
 Loop
OpenGL is an event-driven package

Computer Graphics Sep 10, 2


- means - it always executes code in response to
events
- code that is executed is known as a callback
function, and it must be defined by the programmer
- E.g., mouse clicks & keyboard presses - events
 The most important event is the display event
- occurs whenever OpenGL decides that it needs to
redraw
 To specify a callback function we must first
write a programmer-defined function, and then
specify that this function should be associated
with a particular event

22 OpenGL Initialisation
Routines
 OpenGL graphics package is a state system

Computer Graphics Sep 10, 2


- means - it maintains a list of state variables, or
state parameters, which will be used to define how
primitives will be drawn
 These state variables are specified separately,
before the primitives are drawn
 E.g., if we want to draw a red point, we first set
drawing colour state variable to red, and then we
draw the point
 before we draw the points we assign values for
three state variables:
glClearColor(1.0, 1.0, 1.0, 0.0); // background color to
white and alpha value (opacity) of background color
glColor3f(0,0,0); // defines drawing color to be black
23 OpenGL Coordinate
 system
fundamental to 3D rendering

Computer Graphics Sep 10, 2


 some of the coordinate systems:
 Modeling Coordinate System - all primitives
start off in their own private coordinate system
(local coordinates of the object being rendered)
- Modelling – process of building scene from a # of
primitives.
- these primitives must be transformed to get
them in the correct position, scale and
orientation
 World Coordinate System: accounts for the
position, rotation, and scale of the models in
relation to each other in 3D scene
24 OpenGL Coordinate
 system
List of some of the coordinate systems you may

Computer Graphics Sep 10, 2


encounter:
 Hierarchical Coordinate Systems - Sometimes
objects in a scene are arranged in a hierarchy, so that
the position of one object in the hierarchy is relative to
its parent in the hierarchy scheme, rather than to the
world coordinate system
- E.g., hand may be positioned relative to an arm, and the
arm relative to the torso
- When the arm moves, the hand moves with it, and when
the torso moves, all three objects move together
 Viewing (Camera) Coordinate System - viewpoint of
the observer, and changes as they change their view
- represent the positions of objects after being
transformed in relation to camera
25 OpenGL Coordinate
 system
List of some of the coordinate systems you may

Computer Graphics Sep 10, 2


encounter:
 Clip Coordinates: After applying the projection
transformation (perspective or orthographic
projection), objects are transformed into clip
coordinates which are necessary for perspective
division.
 Normalized Device Coordinates (NDC): After
clipping, coordinates are converted into NDC,
which range from -1 to 1 in the x, y, and z axes.
 dependent on viewport settings; crucial for
rasterization
 Window Coordinates: final coordinates used to
map the NDC to actual pixel positions on the
26
system
OpenGL Coordinate

Computer Graphics Sep 10, 2


27 OpenGL Coordinate
system
Viewing Using Synthetic Camera

Computer Graphics Sep 10, 2


 In OpenGL, the concept of a synthetic
camera is used to simulate how a real camera
captures a scene.
 Camera defines what part of the 3D world is
visible and how it is projected onto 2D screen.
 Key components include:
 Camera Position: location of camera in world
coordinates
 Viewing Direction: direction the camera is
pointing.
 Up Vector: Defines orientation of camera (e.g.,
which way "up")
28 OpenGL Coordinate
system
Viewing Using Synthetic Camera

Computer Graphics Sep 10, 2


 synthetic camera is defined by two main
components:
 View Matrix: allows to position & orient
camera in scene
 transforms world coordinates into camera
coordinates
 gluLookAt - employed to set up this
transformation
 Projection Matrix: responsible for simulating
the perspective or orthographic projection that
the camera will use
29 OpenGL Coordinate
 system
functions that define how the 3-D primitives

Computer Graphics Sep 10, 2


will be projected onto the 2-D image plane
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0); // any
point/primitives whose x coordinate lies between 0
and 640 and whose y coordinate lies between 0 and
480, will be seen by the virtual camera and
therefore drawn in the display window
30 OpenGL Coordinate
 system
Note the ff routines in the display function:

Computer Graphics Sep 10, 2


 glutWindowSize(640, 480); // sets the size of the
display window in pixels
 glClear // to clear the screen before drawing
 glBegin, glVertex2i, glEnd // this sequence of
commands draws a number of point primitives
 glBegin … glEnd pair of commands  used to
draw many different types of primitive in
OpenGL, with the symbolic constant argument to
glBegin defining how the vertices in between
should be interpreted
 GL_POINTS means that each vertex should be
considered to be a point primitive
 glFlush // tells OpenGL to ‘flush’ the buffer, i.e. to
31 OpenGL Coordinate
system
 Single or Double Buffering

Computer Graphics Sep 10, 2


 GLUT_SINGLE & GLUT_DOUBLE specify whether we
want to use single or double buffering respectively
 In raster graphics systems, whatever is written to
the frame buffer is immediately transferred to the
display
- repeated frequently (30 – 60 times a second)
 To do this a typical approach is to first erase the
old contents by setting all the pixels to some
background color, i.e. black
- after, the new contents are drawn
 Double buffering:
 two separate: front buffer and back buffer
 front buffer for displaying & back buffer for
32 OpenGL Coordinate
system
 Depth buffer

Computer Graphics Sep 10, 2


 Is needed in 3-dimensional graphics for
hidden surface removal
 Use a special array called depth buffer.
 It is a 2-dimensional array that stores the
distance (or depth) of each pixel from the
viewer
- This makes it possible to determine which
surfaces are closest, thus visible, which are
farther and thus hidden.
 In OpenGL, we use GLUT_DEPTH for this
purpose
33
Sample Program
#include <GL/glut.h>

Computer Graphics Sep 10, 2


#include <stdlib.h>
void myInit(void) {
glClearColor(1.0, 1.0, 1.0, 0.0); // white background
glColor3f(0,0,0); // black foreground
glPointSize(4.0); // size of points to be drawn
// establish a coordinate system for the image
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
/* GLUT display callback handler */
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
} void display(void){
glClear(GL_COLOR_BUFFER_BIT); // Clear
Screen
glBegin(GL_POINTS); // draw 3 points
glVertex2i(100,50);
glVertex2i(100,130);
glVertex2i(150,130);
glEnd();
glFlush(); // send all output to the display
}
34
Sample Program

Computer Graphics Sep 10, 2


int main(int argc, char *argv[]){
glutInit(&argc, argv); // initialise the glut
library
glutInitWindowSize(640,480); // set size of
the window
glutInitWindowPosition(10,10); // position
of window
glutInitDisplayMode(GLUT_SINGLE |
GLUT_RGB);
glutCreateWindow("GLUT Points demo");
glutDisplayFunc(display); // set display
callback
35 GLUT Callback
 Functions
Event-driven: Programs that use windows

Computer Graphics Sep 10, 2


- Input/Output
- Wait until an event happens and then execute
some pre-defined functions according to the
user’s input
 Events – key press, mouse button press and
release, display, window resize, animation,
etc.
 OpenGL program will be in infinite loop
 Callback function: Routine to call when an
event happens
- Window resize or redraw
- User input (mouse, keyboard)
36 GLUT Callback
Functions
 “Register” input callbacks functions

Computer Graphics Sep 10, 2


with GLUT
- glutDisplayFunc( display );
- glutIdleFunc( idle );
- glutKeyboardFunc( keyboard );
- glutMouseFunc( mouse );
37
Events in OpenGL
Event Example OpenGL Callback

Computer Graphics Sep 10, 2


Function
Keypres KeyDown glutKeyboardFunc
s KeyUp

Mouse leftButtonDown glutMouseFunc


leftButtonUp
Motion With mouse glutMotionFunc
press glutPassiveMotionFunc
Without
Window Moving glutReshapeFunc
Resizing
System Idle glutIdleFunc
38 Rendering
 Callback
Callback function where all our drawing is

Computer Graphics Sep 10, 2


done
 Every GLUT program must have a display
callback
glutDisplayFunc(display);/* this part is in main */
void display( void ){
glClear( GL_COLOR_BUFFER_BIT );
glBegin( GL_TRIANGLE );
glVertex3fv( v[0] );
glVertex3fv( v[1] );
glVertex3fv( v[2] );
glEnd();
glFlush();
39
Idle Callback
 Use for animation and continuous update

Computer Graphics Sep 10, 2


- Can use glutTimerFunc or timed callbacks for
animations
glutIdleFunc( idle );
void idle( void ){
/* change something */
t +=dt;
glutPostRedisplay();
}
40
Mouse Callback
 Position in the screen window is usually

Computer Graphics Sep 10, 2


measured in pixels with the origin at the top-
left corner
 OpenGL uses a world coordinate system with
origin at the bottom-left
- Must invert y coordinate returned by callback by
height of window
- y’ = h - y
41
Mouse Callback
glutMouseFunc(myMouse);

Computer Graphics Sep 10, 2


void myMouse(GLint button, GLint state, GLint x,
GLint y)
- button specifies which mouse button was
pressed:
GLUT_LEFT_BUTTON,
GLUT_RIGHT_BUTTON, or
GLUT_MIDDLE_BUTTON
- state of that button
GLUT_UP, GLUT_DOWN
- position in window
x and y: screen coordinates of
mouse position (origin at top-left corner)
42
Mouse Callback
 Captures mouse press and release

Computer Graphics Sep 10, 2


events
glutMouseFunc( my_mouse);

void my_mouse( int button, int state, int


x, int y){
if (button == GLUT_LEFT_BUTTON &&
state == GLUT_DOWN)
{

}
}
43
Menu
 Creating a menu in an OpenGL application

Computer Graphics Sep 10, 2


typically involves integrating a UI library, as
OpenGL itself does not provide built-in menu
functionality.
 GLUT provides pop-up menu features
- use with mouse to create sophisticated
interactive applns
- must link the menu to a particular mouse
button (left, right or middle)
- define a callback function corresponding to
each menu entry
 function calls to set up the menu and to
link it to the mouse button should be
44
Menu
int main(){

Computer Graphics Sep 10, 2


glutCreateMenu(menu);
glutAddMenuEntry(“Square", 1);
glutAddMenuEntry(“Triangle", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
…..
}
void menu(GLint option){
if (option == 1)
//statement
else
//statements
}
45
Menu
 GLUT also supports hierarchical menus

Computer Graphics Sep 10, 2


- Submenu to pop up
sub_menu =
glutCreateMenu(polygon);
glutAddMenuEntry(“Square", 2);
glutAddMenuEntry(“Triangle", 3);
glutCreateMenu(menu);
glutAddMenuEntry("Quit",1);
glutAddSubMenu(“Polygon",
46
Keyboard Event
 Link a keyboard key with a routine that’s invoked

Computer Graphics Sep 10, 2


when key is pressed
 key is the ASCII value of the key that was pressed
GLUT_KEY_LEFT, GLUT_KEY_RIGHT … (Arrow keys)
 x and y: screen coordinates of cursor position (origin
at top-left corner) when a key is pressed
glutKeyboardFunc( keyboard );
void keyboard( unsigned GLchar key, GLint x,
GLint y ){
switch( key ) {
case ‘q’ : case ‘Q’ :
exit( EXIT_SUCCESS );
break;
}
}
47
Reshape Functions
 Indicates what action should be taken

Computer Graphics Sep 10, 2


when the window is resized
glutReshapeFunc(myReshape);
 myReshape(int, int)  “reshape” event
- automatically passed arguments that
report the new width and height of the
reshape window
- This function manages any changes
needed in the view setup to
accommodate the reshape window
- Parameter: width & height of the window
48
Output Primitives
 Graphics primitives: All graphics packages

Computer Graphics Sep 10, 2


construct pictures from basic building blocks
 Output Primitives: Basic geometric structures
(points, straight line segment, circles and other
conic sections, quadric surfaces, spline curve and
surfaces, polygon color areas, and character
strings)
 Geometric primitives: primitives or routines to
describe geometry (i.e. shape) of objects
(components of the scene), e.g. Point drawing,
Line drawing, Polygon drawing,…
- can be 2-D (points, lines, quadrilaterals, & general
polygons) and more complex 3-D primitives
(spheres and polyhedral (made from mesh of 2-D
49
Attributes
 Attribute – any parameter that affects the

Computer Graphics Sep 10, 2


way a primitive will be displayed
e.g.: Colour, type, line thickness, fill style,
etc.
 OpenGL maintain a list of current state
variables that are used to modify the
appearance of each primitive as it is
displayed
 state variables represent attributes of the
primitives
 All OpenGL state variables have default
values
50
Attributes
Output Attributes

Computer Graphics Sep 10, 2


Primitive
Point Size
Color
Line Thickness (1pt, 2pt …)
Type (Dashed, Dotted, Solid)
Color
Text Font (Arial, Courier, Times Roman…)
Size (12pt, 16pt ..)
Spacing
Orientation (Slant angle)
Style (Bold, Underlined, Double
lined)
Color
Filled Region Fill Pattern
Fill Type (Solid Fill, Gradient Fill)
Fill Color
Images Color Depth (Number of bits/pixel)
51 OpenGL Point
 Functions
Point - most basic type of primitive

Computer Graphics Sep 10, 2


 use the pair of functions glBegin … glEnd, using
the symbolic constant GL_POINTS
 Point attributes:
- Point size: glPointSize(size)
 Points are drawn as squares with a side length equal
to the point size, default point size is 1 pixel
- Point colour: glColor*
 glVertex*
 * specifies # of arguments, and type of arguments
 glVertex3f: 3 Glfloat arguments
 If we specify 2-D point, OpenGL will actually create
3-D point with z=0
52 OpenGL Point
 Functions
OpenGL routines for drawing points:

Computer Graphics Sep 10, 2


glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
glVertex2i(50, 100);
glPointSize(2.0);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(75, 150);
glPointSize(3.0);
glColor3f(0.0, 0.0, 1.0);
glVertex2i(100,200);
glEnd();
53 OpenGL Point
 Functions
The following code fragment draws three 2-D

Computer Graphics Sep 10, 2


points with a size of 2 pixels
glPointSize(2.0);
glBegin(GL_POINTS);
glVertex2i(50, 100);
glVertex2i(75, 150);
glVertex2i(100,200);
glEnd();
 If we specify a 2-D point, OpenGL will actually
create a 3-D point with z=0
54 Line Drawing
 Primitives
3 kinds of line primitives, based on different

Computer Graphics Sep 10, 2


interpretations of a vertex stream
- GL_LINES: Vertices 0 and 1 are considered a line.
Vertices 2 and 3 are considered a line. And so on. If
the user specifies a non-even (odd) number of
vertices, then the extra vertex is ignored
- GL_LINE_STRIP: adjacent vertices are considered
lines. Thus, if you pass n vertices, you will get n-1
lines. If the user only specifies 1 vertex, the
rendering command is ignored.
- GL_LINE_LOOP: As line strips, except that the first
and last vertices are also used as a line. Thus, you
get n lines for n input vertices. If the user only
specifies 1 vertex, the rendering command is
55 Line Drawing
 Primitives
GL_LINES

Computer Graphics Sep 10, 2


 Unconnected line segments

 GL_LINE_STRIP
 Connected line segments
(a polyline)

 GL_LINE_LOOP
 Connected line segments, and last
point connected to first point
56 Line Drawing
 Algorithms
Lines are a very common primitive

Computer Graphics Sep 10, 2


- form the basis of more complex primitives such as
polylines (connected sequence of straight-line
segments) or polygons (2-D objects formed by
straight-line edges)
 Drawing a line on a computer can be tricky for
computer. How?
- Computer has to select to pixels
- lot of computations required
 Lines - normally represented by two end-points,
and points (x,y) along the line must satisfy slope-
intercept straight-line equation:
y = mx + c…………………………………………...
57 Line Drawing
 Algorithms
Slope – indicates the steepness of the line.

Computer Graphics Sep 10, 2


 Given end points (x0, y0) and (xend, yend), it is
calculate as:
m = (yend - y0)/(xend - x 0)
………………………… (2)
c = y0 - m.x0 ……………………………...…….…
(3)
 two line-drawing algorithms:
 DDA and Bresenham’s algorithm
 For any given x-interval δx, we can find the
corresponding y-interval δy:
58 Line Drawing
Algorithms
Line Drawing: DDA Algorithm

Computer Graphics Sep 10, 2


 DDA = Digital Differential Analyser
 Operates: starting at one end-point of the line,
and then using Eqs. (4) and (5) to generate
successive pixels until the second end-point is
reached.
 For lines with |m|≤1: line more horizontal than
vertical
 Start with (x0, y0), successive pixel positions
calculated using δx=1, δy=m
 For lines with |m|>1: more vertical than
horizontal
 Start with (x0, y0), successive pixel positions
59 Line Drawing
Algorithms
Line Drawing: DDA Algorithm

Computer Graphics Sep 10, 2


 Example:
 m=3/5=0.6
 |m|≤1, so
δx=1, δy=0.6

 Start with (x0,y0) = (10,10) – colour this pixel


 Next, (x1,y1) = (10+1,10+0.6) = (11,10.6) – so we colour
pixel (11,11)
 Next, (x2,y2) = (11+1,10.6+0.6) = (12,11.2) – so we colour
pixel (12,11)
 Next, (x3,y3) = (12+1,11.2+0.6) = (13,11.8) – so we colour
60 Line Drawing
Algorithms
Line Drawing: Bresenham’s Algorithm

Computer Graphics Sep 10, 2


 DDA Algorithm involves floating point operations so
can be slow & time consuming
 Bresenham’s algorithm uses only integer operations
– much faster
 If we know the previous pixel location, we only have
a choice of 2 locations for the next pixel,
 (xk, yk) is a point on the line, next line
point must be either pixel A or pixel B
 At each stage, we need to decide which of
A=(xk+1, yk+1) or
B=(xk+1,yk) pixel to choose
 Therefore, we do not need to compute the
actual floating-point location of the ‘true’ line
point; we need only make a decision between pixels
61 Line Drawing
Algorithms
Line Drawing: Bresenham’s Algorithm

Computer Graphics Sep 10, 2


 If (dupper - dlower) is positive, then we choose
B as the next position in the line, otherwise
choose A
 Decision variable:
 Pk=2Δy.xk - 2Δx.yk+ d
where d = 2Δy –2cΔx - Δx
 Pk has the same sign as
(dupper - dlower)
 incremental calculation - next
value of pk from the last one
62 Line Drawing
Algorithms
Line Drawing: Bresenham’s Algorithm

Computer Graphics Sep 10, 2


 If pk < 0, then yk+1 = yk, otherwise yk+1 = yk+1
pk 1  pk  2y if pk < 0
pk 1  pk  2y  2x
p0 2y  x
 Summary
 Plot the start-point of the line (x0,y0)
 Compute p0 2y  x
 For each k, starting with k=0:
 If pk < 0: pk 1  pk  2y
 Plot (xk+1,yk)
 Otherwise: pk 1  pk  2y  2x
 Plot (xk+1,yk+1)
63 Line Drawing
Algorithms
Line Drawing: Bresenham’s Algorithm

Computer Graphics Sep 10, 2


 incremental calculation - next value
of pk from the last one
 Always xk+1 = xk+1
 If pk < 0, then yk+1 = yk, otherwise yk+1 = yk+1
p  p  2y if pk < 0
k 1 k

pk 1  pk  2y  2x
p0 2y  x
64 Line Drawing
Algorithms
Line Drawing: Bresenham’s Algorithm

Computer Graphics Sep 10, 2


 Example:
 Δx = 5  2Δy = 6
 Δy = 3  2Δy - 2Δx = -
4 Δx 2 3  5 1
p 2ΔΔ0
 Plot (x0,y0) = (10,10)
 Iteration 0: p0 ≥ 0, so
 Plot (x1,y1) = (x0+1,y0+1) = (11,11)
p1  p 0  2y  2x 1  4  3
 ext, (x1,y1) = (10+1,10+0.6) = (11,10.6) – so we colour
pixel (11,11)
 Next, (x2,y2) = (11+1,10.6+0.6) = (12,11.2) – so we colour
pixel (12,11)
 Next, (x3,y3) = (12+1,11.2+0.6) = (13,11.8) – so we colour
65 Line Drawing
 Algorithms
Line Attribute

Computer Graphics Sep 10, 2


- Line Style
- Line Width
- Line Color
- Pen & Brush options
 Width - tickness
 Specify in pixels and proportion of a standard
line width
 Issues:
 Line have different thickness on the slope
 Problem with
 End of the line
 Joining the two lines (polygon)
66 Line Drawing
 Algorithms
Line Attribute - Width

Computer Graphics Sep 10, 2


 simplest and most common technique for
increasing the width of a line
 plot a line of width 1 pixel, and then
 add extra pixels in either horizontal or vertical
directions
 these two approaches depends on gradient m
of line
 If |m| ≤ 1: line more horizontal than vertical 
plot extra pixels vertically, i.e. same x-
coordinate, different y-coordinate, as
 If |m| > 1: line more vertical than horizontal
plot extra pixels horizontally, i.e. same y-
67 Line Drawing
 Algorithms
Line Attribute - Width

Computer Graphics Sep 10, 2


Fig. Increasing Line Width by Plotting Extra
Pixels in the Vertical (a) and Horizontal (b)
68 Line Drawing
 Algorithms
Line Attribute -

Computer Graphics Sep 10, 2


Width
 2 problems with technique:
- Thickness depends on
slope, e.g.
 If slope = 0, plotting n
pixels gives thickness n
 If slope = 1 (45o), plotting
n pixels gives thickness of
n/√2
- Ends of lines: depending
on whether we are plotting
extra pixels in the
horizontal or vertical
directions,
69 Line Drawing
 Algorithms
Line Attribute - Width

Computer Graphics Sep 10, 2


 Answer to the second problem – use line caps
 Line cap is a shape that is applied to the end of
the line only to give them a better appearance
 Three types of line cap are common in computer
graphics:
- Butt cap - is formed by drawing a line through
each end-point at an orientation of 90o to the
direction of the line
- Round cap - formed by drawing a semi-circle at
each end-point with radius equal to half the line
width
- Projecting square cap – similar to the butt
cap but the position of the line is extended by a
70 Line Drawing
 Algorithms
Line Attribute - Width

Computer Graphics Sep 10, 2


 Types of line cap

 The process introduce a new problem


 If we are drawing polylines, or a connected
series of line segments, with these line caps,
we can get problems at line joins
 For example
 what happens at the line join of two line
segments drawn with butt caps
 There is a small triangular area at the join that
does not get filled
71 Line Drawing
 Algorithms
Line Attribute - Width

Computer Graphics Sep 10, 2


 To overcome this problem – use the ff join
types:
 Miter join – extend the outer boundaries of
each of the two lines until they meet
 Round join – draw a circular boundary centred
on the join point with a diameter equal to the
line width
 Bevel join – use butt caps, then fill in triangle
that is left unfilled
Line join
types
72 Line Drawing
 Algorithms
Line Attribute - Style

Computer Graphics Sep 10, 2


 Solid
 Dotted – very short dash with spacing
equal to or greater than dash itself
 Dashed – an interdash spacing
 normal approach to change line style – define a
pixel mask
- Pixel mask means a sequence of bit values that
determine whether pixels in the plotted line
should be on or off, e.g.,
- Mask 11111000 specifies a dash length of 5
pixels followed by a spacing of 3 pixels
- In other words,
 if bit in PM is 1  plot pixel
73 OpenGL Line
 Functions
draw using glBegin … glEnd functions

Computer Graphics Sep 10, 2


 we specify that vertices should be interpreted as line
end-points by using the symbolic constant GL_LINES
 E.g.,
glLineWidth(3.0);
glBegin(GL_LINES);
glVertex2f(100.0, 200.0);
glVertex2f(150.0, 200.0);
glVertex2f(150.0, 250.0);
glVertex2f(200.0, 250.0);
glEnd()
 line will be drawn in the current drawing colour and
with a width defined
 two separate line segments: from (100,200) to
(150,200) and from (150,250) to (200,250)
74 OpenGL Line
 Functions
GL_LINE_STRIP and GL_LINE_LOOP

Computer Graphics Sep 10, 2


Glint p1[] = {200,100}; Glint p2[] = {50,0}
Glint p3[] = {100,200}; Glint p4[] = {150,0}; Glint p5[] =
{0,100};
glBegin(GL_LINE_STRIP);
glVertex2i(p1);
glVertex2i(p2);
glVertex2i(p3);
glVertex2i(p4);
glVertex2i(p5);
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2i(p1);
glVertex2i(p2);
glVertex2i(p3);
glVertex2i(p4);
glVertex2i(p5);
75 OpenGL Line
 Functions
Line style – is specified using a pixel mask

Computer Graphics Sep 10, 2


 Stippled lines – to make stippled (dotted or dashed) lines
 Firstly, must enable line stipple using:
glEnable(GL_LINE_STIPPLE);
 Next, use glLineStipple function to define line style,
takes 2 arguments:
glLineStipple(GLint repeatFactor, GLushort
pattern);
 repeatFactor, specifies how many times each bit in the
pixel mask should be repeated, and
 pattern, which is a 16-bit pixel mask, with the low-order
bit used first – series of 0’s and 1’s
 E.g., pixel mask is the hexadecimal number 00FF,
which is
- 8 zeros followed by 8 ones
-
76 OpenGL Line
Functions
glEnable(GL_LINE_STIPPLE);

Computer Graphics Sep 10, 2


glLineWidth(3.0);
glLineStipple(1, 0x00FF);
glBegin(GL_LINE_STRIP);
glVertex2i(100,100);
glVertex2i(150,100);
glVertex2i(150,200);
glVertex2i(250,250);
glEnd();
glDisable(GL_LINE_STIPPLE);
77

Functions
OpenGL Line

Computer Graphics Sep 10, 2


78 Triangle Drawing
Primitives
 triangle - a primitive formed by 3 vertices

Computer Graphics Sep 10, 2


 3 kinds of triangle primitives, based again on
different interpretations of the vertex stream:
- GL_TRIANGLES: vertices 0, 1, and 2 form a triangle.
Vertices 3, 4, and 5 form a triangle. And so on.
- GL_TRIANGLE_STRIP: Every group of 3 adjacent
vertices forms a triangle. A vertex stream of n
length will generate n-2 triangles
- GL_TRIANGLE_FAN: The first vertex is always
held fixed. From there on, every group of 2
adjacent vertices form a triangle with the first
- So with a vertex stream, you get a list of triangles like so: (0,
1, 2) (0, 2, 3), (0, 3, 4), etc. A vertex stream of n length will
generate n-2 triangles.
79
Fill-Area Primitives
 Refers to any enclosed boundary that can be

Computer Graphics Sep 10, 2


filled with a solid color or pattern
 How do we fill shapes?

Texture Fill
Solid Fill Pattern Fill
80
Fill-Area Primitives
 Fill-area primitives are normally polygons, as they

Computer Graphics Sep 10, 2


can be filled more efficiently by graphics packages
 Fill-Area algorithms are used to fill the interior of a
polygonal shape
 If the polygon is to be filled we can specify a fill style
 Options for filling a defined region include
- choice between a solid color or a pattern
fill and
- choices for particular colors and patterns
 Polygons are 2-D shapes whose boundary is formed
by any number of connected straight-line segments
- defined by 3 or more coplanar vertices (points positioned
on the same plane)
81
Fill-Area Primitives
 polygons should have no edge crossings: known as

Computer Graphics Sep 10, 2


simple polygons or standard polygons
 Edge crossings, e.g.

 Polygons are the most common form of graphics


primitive because they form the basis of polygonal
meshes, which is the most common representation
for 3-D graphics objects.
 Polygonal meshes approximate curved surfaces by
forming a mesh of simple polygons.
82 Presentation
Assignments
 Concave and Convex

Computer Graphics Sep 10, 2


Polygons
 Identify concave polygons
 Splitting concave polygons
 Polygon Inside-Outside
Tests
 Representing polygons
 Polygon Front and Back
83 OpenGL Polygon Fill-Area
Functions
 To fill polygons with a fill-area pattern:

Computer Graphics Sep 10, 2


- Define the pattern
- Enable polygon-fill feature of OpenGL
- Draw polygons
 A number of different ways:
 glRect*
 6 different symbolic constants
 For all:
 Polygons must be convex (all interior angles ≤
180o)
 Must specify vertices in anti-clockwise order when
viewing the polygon from “outside”
 Default fill-style is solid color, determined by
current color settings
84 OpenGL Polygon Fill-Area
Functions
 glRect*

Computer Graphics Sep 10, 2


 OpenGL provides special routine that takes 2-D points only
glRect* (x1, y1, x2, y2)
 (x1,y1) and (x2,y2) define opposite corners of the
rectangle
 when we call the glRect* routine, OpenGL will construct
a polygon with vertices defined in the following order:
(x1,y1), (x2,y1), (x2,y2), (x1,y2).
 e.g: glRecti(200,100,50,250);
 We can draw rectangles with
other functions, but glRect*can
be more efficient
85 OpenGL Polygon Fill-Area
Functions
 All other fill-area functions use the

Computer Graphics Sep 10, 2


functions
glBegin… glEnd:
 GL_POLYGON
 GL_TRIANGLES
 GL_TRIANGLE_STRIP
 GL_TRAINGLE_FAN
 GL_QUADS
 GL_QUAD_STRIP
86 OpenGL Polygon Fill-Area
Functions
 GL_POLYGON:

Computer Graphics Sep 10, 2


 Displays a single convex polygon
 Vertices of polygon are specified in anti-clockwise
direction
 E.g.
glBegin(GL_POLYGON);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glEnd();
87 OpenGL Polygon Fill-Area
Functions
 GL_TRIANGLES:

Computer Graphics Sep 10, 2


 Vertex list treated as groups of 3 triangle vertices
 Vertices must be specified in anti-clockwise order
 E.g.
glBegin(GL_TRIANGLES);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p6);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glEnd();
88 OpenGL Polygon Fill-Area
Functions
 GL_TRIANGLE_STRIP:

Computer Graphics Sep 10, 2


 Displays set of connected triangles
 First triangle vertices must be anti-clockwise
 E.g.
glBegin(GL_TRIANGLE_STRIP);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p6);
glVertex2iv(p3);
glVertex2iv(p5);
glVertex2iv(p4);
glEnd();
89 OpenGL Polygon Fill-Area
Functions
 GL_TRIANGLE_FAN:

Computer Graphics Sep 10, 2


 First vertex is the ‘source’ of the fan
 Subsequent pairs of vertices form triangles with the
first one
 E.g.
glBegin(GL_TRIANGLE_FAN);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glEnd();
90 OpenGL Polygon Fill-Area
Functions
 GL_QUADS:

Computer Graphics Sep 10, 2


 Vertex list treated as groups of 4 quadrilateral
vertices
 Vertices must be specified in anti-clockwise order,
glBegin(GL_QUADS);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glVertex2iv(p7);
glVertex2iv(p8);
glEnd();
91 OpenGL Polygon Fill-Area
Functions
 GL_QUAD_STRIP:

Computer Graphics Sep 10, 2


 One quadrilateral drawn for each pair of vertices
after the first two
glBegin(GL_QUAD_STRIP);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glVertex2iv(p7);
glVertex2iv(p8);
glEnd();
92
Character Primitives
 Many pictures require text

Computer Graphics Sep 10, 2


 attributes: Font size, Color and Orientation
 Attributes can be set both for entire character strings
(text) and for individual characters
 Most graphics packages have some support for
displaying character primitives
 Type Faces (fonts) can be divided into two:
 Serif – has small lines or accents at the ends of the main
character stroke. And so makes readable.
 Sans-Serif – does not have accents.
Arial is a sans-serif font
Verdana is a sans-serif font
Times Roman is a serif font
Garamond is a serif font
93
Character Primitives
 Another category of fonts

Computer Graphics Sep 10, 2


 Monospace font: always take up the same width on the
display, regardless of which character is being drawn
 Proportional fonts: width used on the display will be
proportional to the actual width of the character
 Two ways of representing characters:
 Bitmap (Raster)
 Binary pattern defined on rectangular grid
 bitmap is a mapping from some domain
(e.g., a range of integers) to bits
 Each character represented (stored) as a 2-D array
- Each element corresponds to a pixel in a
rectangular “character cell”
- Simplest: each element is a bit (1=pixel on,
0=pixel off)
94
Character Primitives
 Two ways of representing characters:

Computer Graphics Sep 10, 2


 Bitmap (Raster)

00111000
01101100
11000110
11000110
11111110
11000110
11000110
00000000
95
Character Primitives
 Two ways of representing characters:

Computer Graphics Sep 10, 2


 Stroke(outline)
 Defined using line/curve primitives
 Each character represented (stored) as a series
of line segments
 Takes longer time to draw than bitmap fonts
 change the font, colour, and
also line width and line style
 width of these lines
glLineWidth
 style using
glLineStipple
96 OpenGL Character
Primitives
 glut library supports display of character

Computer Graphics Sep 10, 2


 All characters displayed at current raster
position:
 glRasterPos2i(x, y);
 Bitmap characters are drawn using
 glutBitmapCharacter(GLUT_BITMAP_TIMES
_ROMAN_10, ‘a’);
 glutBitmapCharacter(GLUT_BITMAP_9_BY_
15, ‘a’);
To change colour of the character use
glColor* routine
 Stroke characters, e.g.
97
Color Attributes
 Colors are represented by code which are positive

Computer Graphics Sep 10, 2


integers
 Color information is stored in frame buffer or in
separate table and use pixel values as index to
the color table.
 Two ways to store colour values in a frame buffer:
- Direct storage
colour (RGB) values of each pixel are stored
directly in the frame buffer
Each pixel in the frame buffer must have 3 (RGB)
or 4 (RGBA) values stored.
Frame buffer take up a lot of memory.
E.g., for a screen resolution of 1366x768, total
98
Color Attributes
 Two ways to store colour values in a frame buffer:

Computer Graphics Sep 10, 2


- Look-up/indirect table
Store an index for each pixel in the frame buffer.
actual colours are stored in a separate look-up
table, and the index looks up a colour in this
table
Reduce the amount of storage
Have a limited # of different colours in scene (#
of rows in the look-up table)
 For example, if each colour uses 8 bits (=24
bits in all), and the look-up table has 256 rows
the total range of colours
99
Color Attributes

Computer Graphics Sep 10, 2


10
0 OpenGL Color Modes
 2 ways to specify colours in OpenGL:

Computer Graphics Sep 10, 2


- RGB:
 Uses standard RGB colors (24-bit color,
consisting of 8 bits of red, green and blue) and is
the default
 3 numbers represent the amount of red, green
and blue
- RGBA:
 Optional fourth value is the alpha coefficient
 Specifies degree of transparency of the primitive
 Useful for controlling colour blending for
overlapping primitives
 If no alpha value is defined it is assumed to be
equal to 1, which is completely opaque.
10
1 OpenGL Color Modes
 glutInitDisplayMode, e.g.

Computer Graphics Sep 10, 2


glutInitDisplayMode(GLUT_SINGLE|
GLUT_RGB)

 glColor*, e.g.
glColor3f(1.0,1.0,1.0);  white foreground

 glClearColor, e.g.
glClearColor(0,0,0,0)  black background
WHITE
10
2 OpenGL Color Modes
 Some color types

Computer Graphics Sep 10, 2


glColor3f(0.0, 0.0, 0.0);
black
glColor3f(1.0, 0.0, 0.0);
red
glColor3f(0.0, 1.0, 0.0);
green
glColor3f(1.0, 1.0, 0.0);
yellow
glColor3f(0.0, 0.0, 1.0);
THANKS
!
Questions,
Ambiguities,
Doubts, … ???

You might also like