You are on page 1of 79

Chapter 3 & 4

Rendering Process with OpenGL


What is OpenGL?
OpenGL (Open Graphics Library)
- an Application Programming Interface (API) that
allows the programmer to create 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
- The fact that it is windowing-system independent, makes it
portable
- a number of windowing toolkits have been developed for use
with OpenGL
OpenGL is based on GL graphics package
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
the early 1992 as a free platform-independent version
of GL
OpenGL is the core library that contains the
majority of the functionality (around 130 graphics
drawing and operation functions), there are a
number of associated libraries that are also useful
You should make sure that you have access to a
C++ development environment that supports these
two libraries (OpenGL & glut)
Turbo C++ does not support either of them
Two possibilities are:
 free Dev-C++ environment (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 free download
from http://www.xmission.com/~nate/glut.html
Related Graphics Libraries
glut (GL Utilities Toolkit): contains some 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, checkboxes,
radio buttons,.. to OpenGL applications
Lack of Object Orientation: OpenGL is not object
oriented so that there are multiple functions for a
given logical function,
e.g. glVertex3f, glVertex2i, glVertex3dv,…..
Underlying storage mode is the same
Easy to create overloaded functions in C++ but
issue is efficiency
GLUT Functions:
Primitives: Points,Line Segments ,Polygons
Attributes
Transformations- Viewing ,Modeling
Control
Input (GLUT)
Every routine provided by OpenGL or associated 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 convention as function names
- E.g., GL_RGB, GL_POLYGON and GLUT_SINGLE used by
OpenGL and its associated libraries
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
OpenGL has a number of built-in data types to
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 – are
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>
- Include glut automatically includes other header files
Getting Started with OpenGL
we need to know to be able to start writing OpenGL
programs is exactly which header files to include 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 also want to use the GL Utilities library,:
#include <GL/glu.h>
 For the glui user-interface library we must add:
#include <GL/glui.h>
 If we want to use the glut library (and this makes using
OpenGL a lot easier) we do not need to include the
OpenGL or glu header files
#include <GL/glut.h>
The following lines initialise the glut library:
 glutInit(&argc, argv); // we must call this function before
any others in our glut/OpenGL program
 glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE
); // type of frame buffer we want to have, ask for a
double RGB frame buffer
 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 the attributes defined by the
previous calls
OpenGL Event Loop
OpenGL is an event-driven package
- means that 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
 glutDisplayFunc(myDisplay);
To start the event loop we write:
 glutMainLoop();
OpenGL Initialisation Routines
OpenGL graphics package is a state system
- means that 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
so 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
glPointSize(4.0); // sets the point size to 4 pixels
OpenGL Coordinate system
In a 2-D coordinate system, the X axis generally points from left to
right, and the Y axis generally points from bottom to top. (Although
some windowing systems will have their Y coordinates going from
top to bottom). When we add the third coordinate Z, we have a
choice as to whether the Z-axis points into the screen or out of the
screen

In Right Hand Coordinate System (RHS), Z is coming out of the


screen and in Left Hand Coordinate System (LHS), Z is going into
the screen. Generally OpenGL uses a right-hand coordinate system
In a typical graphics program, have to deal with a number
of different coordinate systems, conversion of coordinates
from one system to another is very important
Model Coordinate System is defined as reference space of
the model with respect to which all the model geometrical
data is stored. The origin of MCS can be arbitrary chosen
by the user
• World Coordinate System : every object has its own MCS
relative to which its geometrical data is stored. In case of
multiple objects in the same working space then there is
need of a World Coordinate System which relates each
MCS to each other with respect to the orientation of the
WCS. It can be seen by the picture shown above
• 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. For example, a 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.
• Viewpoint Coordinate System Also known as the "camera" coordinates
system. This coordinate system is based upon the viewpoint of the observer,
and changes as they change their view.
• Model Window (Screen) Coordinate System This coordinate system refers
to the subset of the overall model world that is to be displayed on the
screen. Depending on the viewing parameters selected, the model window
may be rectalinear or a distorted viewing frustrum of some kind. This 2D
coordinate system refers to the physical coordinates of the pixels on the
computer screen, based on current screen resolution
• Viewport Coordinate System This coordinate system refers to a subset of
the screen space where the model window is to be displayed. Typically the
viewport will occupy the entire screen window, or even the entire screen,
but it is also possible to set up multiple smaller viewports within a single
screen window. As discussed that the objects are modeled in WCS, before
these object descriptions can be projected to the view plane, they must be
transferred to viewing coordinate system. The view plane or the projection
plane is set up perpendicular to the viewing zv axis. The World coordinate
positions in the scene are transformed to viewing coordinates, and then
viewing coordinates are projected onto the view plan
functions that define how the 3-D primitives 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
routines in the display function:
 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
draw any primitives now to the frame buffer
Sample
#include <GL/glut.h>
Program
#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();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
} /* GLUT display callback handler */
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
}
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
myInit(); // perform other initialisation
glutMainLoop(); // enter the GL event loop
return EXIT_SUCCESS;
}
Single or Double Buffering
 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 drawing
 swapping to update the image
Depth buffer
 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
GLUT Callback Functions
Event-driven: Programs that use windows
- 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.
Your OpenGL program will be in infinite loop
Callback function : Routine to call when an event
happens
- Window resize or redraw
- User input (mouse, keyboard)
- Animation (render many frames)
“Register” input callbacks functions with GLUT
- glutDisplayFunc( display );
- glutIdleFunc( idle );
- glutKeyboardFunc( keyboard );
- glutMouseFunc( mouse );
Events in OpenGL
Event Example OpenGL Callback Function
Keypress KeyDown glutKeyboardFunc
KeyUp
Mouse leftButtonDown glutMouseFunc
leftButtonUp
Motion With mouse press glutMotionFunc
Without glutPassiveMotionFunc
Window Moving glutReshapeFunc
Resizing
System Idle glutIdleFunc
Timer glutTimerFunc
Software What to draw glutDisplayFunc
Rendering Callback
Callback function where all our drawing is 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();
}
Idle Callback
Use for animation and continuous update
- Can use glutTimerFunc or timed callbacks for
animations

glutIdleFunc( idle );
void idle( void )
{
/* change something */
t +=dt;
glutPostRedisplay();
}
Mouse Callback
glutMouseFunc(myMouse);
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) when the event occurred
Captures mouse press and release events
glutMouseFunc( my_mouse);

void my_mouse( int button, int state, int x, int y )


{
If (button == GLUT_LEFT_BUTTON && state ==
GLUT_DOWN)
{

}
}
Menu
GLUT provides pop-up menu features
- that we can use with the mouse to create
sophisticated interactive applications
We must link the menu to a particular mouse button
(left, right or middle)
Finally, we must 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 placed in main func
int main(){
glutCreateMenu(menu);
glutAddMenuEntry(“Square", 1);
glutAddMenuEntry(“Triangle", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
…..
}
void menu(GLint option)
{
if (option == 1)
//statement
else
//statements
}
GLUT also supports hierarchical menus
- Submenu to pop up
sub_menu = glutCreateMenu(polygon);
glutAddSubMenu(“Polygon", sub_menu)
glutAddMenuEntry(“Square", 1);
glutAddMenuEntry(“Triangle", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
Keyboard Event
Link a keyboard key with a routine that‟s invoked 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;
}
}
Reshape Functions
Indicates what action should be taken 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 after it has
been changed
Output Primitives and
Attributes
Output Primitives
Graphics primitives: All graphics packages 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
the 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 polygons))
All of these primitives are specified using sequence of vertices
Attributes?
Attribute – any parameter that affects the 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
Remain in effect until new values specified
Some state variables can be changed within
glBegin() … glEnd() pairs
Output Primitive Attributes
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)
OpenGL Point Functions
Point - most basic type of primitive
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
We have already seen the OpenGL routines for
drawing points:
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();
The following code fragment draws three 2-D
points with a size of 2 pixels which illustrates an example
of how the sequences of vertices are passed to OpenGL
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
Line Drawing Primitives
3 kinds of line primitives, based on different
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 ignored.
GL_LINES
 Unconnected line segments

GL_LINE_STRIP
 Connected line segments
(a polyline)

GL_LINE_LOOP
 Connected line segments, and last
point connected to first point
Line Attributes
Line Attribute
- Line Style
- Line Width
- Line Color
- Pen & Brush options
Line Drawing
Description:
Given the specification for a straight line, find the collection of addressable
pixels which most closely approximates this line.

Goals:
 Straight lines should appear straight
 lines should start and end accurately, matching endpoints with
connecting line
 Lines should have constant brightness
 Lines should be drawn as rapidly as possible

Problems:
 How do we determine which pixels to illuminate to satisfy the above
goals
 Vertical, horizontal, and lines with slope = + / - 1, are easy to draw.
 Other create problems: stair-case/jaggies/aliasing
It is difficult to determine whether a pixel belongs to an object or not.

Direct Solution:
Solve y = mx + b, where (0, b) is the y-intercept and m is the slope.
Go from 𝑥0 to 𝑥1 :
calculate round(y) from the equation.
Take an example, b = 1 (starting point (0,1)) and m = 3/5.
Then
x = 1, y = 2 = round(8/5)
x = 2, y = 2 = round(11/5)
x = 3, y = 3 = round(14/5)
x = 4, y = 3 = round(17/5)
x = 5, y = 4 = round(20/5)
ideal case of line drawn in graph paper
Choice of pixels in the raster, as integer values:
x = 1, y = 2 = round(8/5)
x = 2, y = 2 = round(11/5)
x = 3, y = 3 = round(14/5)
x = 4, y = 3 = round(17/5)
x = 5, y = 4 = round(20/5)

From the above example:


Algorithm is needed to select the appropriate pixel to draw the line
the display using raster.
DDA (Digital Difference Analyzer) algorithm:
It is an incremental algorithm. Based on the line equation:
y = (𝒚𝟏 - 𝒚𝟎 ) / (𝒙𝟏 - 𝒙𝟎 )x + b
Assume 𝒙𝟏 > 𝒙𝟎 and |dx| > |dy|
Algorithm:
dx = 𝒙𝟏 - 𝒙𝟎
dy = 𝒚𝟏 - 𝒚𝟎
m = dy/dx
y = 𝒚𝟎
for (x = 𝒙𝟎 to 𝒙𝟏 )
draw_point (x, round(y));
y = y + m;
end for
Problem:
it is using the floating point and round () inside the loop.
So its taking more time to draw line.
Midpoint Line Algorithm:
Its also an incremental algorithm, integer based
Mid point criteria algorithm.(Assume first octant)
Given the choice of the current pixel, which one
Do we choose next: E or NE?
Line equations:

Rewrite as:

Gives:

 a = dy, b = -dx, c = B*dx


Criteria: evaluate the mid point , M with respect to
The equation of the line. Mid point on the line

Choice: E or NE?
If F(x, y) > 0; then mid point is available below the line
If F(x, y) < 0; then mid point is available above the line
Algorithm for next choice:
if F(M) > 0 /* Q is above M*//* mid point is below line*/
then select NE pixel
else /* Q is below M*/ /*mid point is above line*/
select E
In this figure: Q is above the midpoint
That means line path is near to the NE
Pixel so based on algorithm we can
Choose the NE pixel to draw the line.

In this figure: Q is below the midpoint


That means line path is near to the E
Pixel so based on algorithm we can
Choose the E pixel to draw the line.
Algorithm:
1. Input the two line endpoints (𝑥0 , 𝑦0 ) 𝑎𝑛𝑑 (𝑥1 , 𝑦1 )
2. Load the (𝑥0 , 𝑦0 ) in to the frame buffer to plot the first point
3. Calculate the constants: dx, dy, 2dy, 2dy-2dx and find the decision
parameter d = 2dy – dx
4. At each 𝑥𝑘 , along the line, starting at k=0: perform the below steps:

5. Repeat the step 4


6. end
OpenGL Line Functions
draw using glBegin … glEnd functions
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)
GL_LINE_STRIP and GL_LINE_LOOP
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);
glEnd();
Line style – is specified using a pixel mask
 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: a
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
- repeat factor is 1 so each one or zero in the pixel mask
corresponds to a single pixel in the line
glEnable(GL_LINE_STIPPLE);
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);
Circle Generating Algorithm:
consider the circle centered at origin with integer radius. For non
origin centered circle can apply the translation.
Equation:
F(x, y) = 𝑥 2 + 𝑦 2 - 𝑅2 = 0
From the two fig: we have to calculate the
parameters for one octant. By using that
octant values: easily can find the
parameters.
begin
plotpoint (x, y); plotpoint (y, x);

plotpoint (x, -y); plotpoint (-y, x);

plotpoint (-x, -y); plotpoint (-y, -x);

plotpoint (-x, y); plotpoint (-y, x)


end
MidPoint Circle Algorithm:
Using this algorithm: we can draw the circle in the display. This
algorithm is starting to draw the circle from the 2nd octant of the circle. After
finished the 2nd octant using the draw_circle procedure to calculate the
remaining octant.
now the choice is between pixels E and SE
Condition is:
F(x, y) > 0 if point is outside the circle
F(x, y) < 0 if point is inside the circle
Decision Parameter d
use dold = F(M)
Midpoint Circle Algorithm:
1. Input radius R and obtain the first point on the
circumference of a circle.
2. Calculate the decision parameter
d > 0 select SE point
d < 0 select E point
3. Determine the symmetry points in the other seven
octants
4. Repeat the step 2 and 3 for remaining 7 octant
5. End
Triangle Drawing Primitives
triangle - a primitive formed by 3 vertices
It is 2D shape with the smallest number of vertices
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.
Fill-Area Primitives
Refers to any enclosed boundary that can be
filled with a solid color or pattern
How do we fill shapes?

Texture Fill
Solid Fill Pattern Fill
Fill-area primitives are normally polygons, as they 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)
- Each pair of adjacent vertices is connected in sequence by edges
OpenGL Polygon Fill-Area Functions
To fill polygons with a fill-area pattern:
- 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
glRect*
 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
All other fill-area functions use the functions
glBegin… glEnd:
 GL_POLYGON
 GL_TRIANGLES
 GL_TRIANGLE_STRIP
 GL_TRAINGLE_FAN
 GL_QUADS
 GL_QUAD_STRIP
GL_POLYGON:
 Displays a single convex polygon
 Vertices of the 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();
GL_TRIANGLES:
 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();
GL_TRIANGLE_STRIP:
 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();
GL_TRIANGLE_FAN:
 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();
GL_QUADS:
 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();
GL_QUAD_STRIP:
 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();
Character Primitives
Many pictures require text
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
Another category of fonts
 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)
Two ways of representing characters:
 Bitmap (Raster)

00111000
01101100
11000110
11000110
11111110
11000110
11000110
00000000
 Stroke(outline)
 Defined using line/curve primitives
 Each character represented (stored) as a series of line
segments
 Takes longer time draw than bitmap fonts
 we can change the font, colour, and also line width and
line style
 width of these lines can be changed using
glLineWidth
 style using
glLineStipple
OpenGL Character Primitives
glut library supports display of
character primitives
All characters displayed at current raster position:
 glRasterPos2i(x, y);
Bitmap characters are drawn using
 glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, „a‟);
To change colour of the character use
glColor* routine
Stroke characters, e.g.
 glutStrokeCharacter(GLUT_STROKE_ROMAN_10, „a‟);

You might also like