Download as pdf or txt
Download as pdf or txt
You are on page 1of 123

CURVES

CURVED SURFACES

• Sometimes it is required to generate curved objects instead of polygons, for the


curved objects the equation can be expressed either in parametric form or non
parametric form.
• Parametric form:
• When the object description is given in terms of its dimensionality parameter, the
description is termed as parametric representation.
• A curve in the plane has the form C(t) = (x(t), y(t)), and a curve in space has the
form C(t) = (x(t), y(t), z(t)).
• The functions x(t), y(t) and z(t) are called the coordinates functions.
• A parametric curve defined by polynomial coordinate function is called a
polynomial curve.
• The degree of a polynomial curve is the highest power of the variable occurring in
any coordinate function.
Non parametric form
• When the object descriptions are directly in terms of coordinates of
reference frame, then the representation is termed as non
parametric.
• Example: a surface can be described in non parametric form as:
f1(x,y,z)=0 or z=f2(x,y)
QUADRIC SURFACES
• A frequently used class of objects is the quadric surfaces, which are
described with second - degree equations (quadratics).
• They include spheres, ellipsoids, torus, paraboloids, and hyperboloids.
Sphere
• A spherical surface with radius r
centered on the coordinate origin is
defined as the set of points (x, y, z) that
satisfy the equation x2 + 𝑦 2 + 𝑧 2 =𝑟 2 .
• We can also describe the spherical
surface in parametric form, using
latitude and longitude angles as shown
in figure

x = r cos φ cos θ, − π/2 ≤ φ ≤ π/2


y = r cos φ sin θ, − π ≤ θ ≤ π
z = r sin φ
Ellipsoid
• An ellipsoidal surface can be
described as an extension of a
spherical surface where the radii
in three mutually perpendicular
directions can have different
values.
• The Cartesian representation for
points over the surface of an
ellipsoid centered on the origin
is
Torus
• A torus is a doughnut-shaped
object, as shown in fig. below.
• It can be generated by rotating a
circle or other conic about a
specified axis.
• The equation for the cross-
sectional circle shown in the side
view is given by (y − raxial)𝟐 +
𝒛𝟐 = 𝒓𝟐
OpenGL Quadric-Surface and Cubic-Surface
Functions
• A number of other three-dimensional quadric-surface objects can be
displayed using functions that are included in the OpenGL Utility
Toolkit (GLUT) and in the OpenGL Utility (GLU).
• With the GLUT functions, we can display a sphere, cone, torus, or the
teapot
• With the GLU functions, we can display a sphere, cylinder, tapered
cylinder, cone, flat circular ring (or hollow disk), and a section of a
circular ring (or disk).
GLUT Quadric-Surface Functions
• Sphere
Function:
glutWireSphere (r, nLongitudes, nLatitudes);
or
glutSolidSphere (r, nLongitudes, nLatitudes);
• where, r is sphere radius which is double precision point.
• nLongitudes and nLatitudes is number of longitude and latitude lines
used to approximate the sphere.
Cone
• Function:
glutWireCone (rBase, height, nLongitudes, nLatitudes);
or
glutSolidCone (rBase, height, nLongitudes, nLatitudes);
where,
• rBase is the radius of cone base which is double precision point.
• height is the height of cone which is double precision point.
• nLongitudes and nLatitudes are assigned integer values that specify the
number of orthogonal surface lines for the quadrilateral mesh
approximation.
Torus
• Function:
glutWireTorus (rCrossSection, rAxial, nConcentrics, nRadialSlices);
or
glutSolidTorus (rCrossSection, rAxial, nConcentrics, nRadialSlices);
where,
• rCrossSection radius about the coplanar z axis rAxial is the distance of the
circle center from the z axis
• nConcentrics specifies the number of concentric circles (with center on the
z axis) to be used on the torus surface,
• nRadialSlices specifies the number of radial slices through the torus surface
GLUT Cubic-Surface Teapot Function
• Function:
glutWireTeapot (size);
or
glutSolidTeapot (size);
• The teapot surface is generated using OpenGL B´ezier curve funcions.
• Parameter size sets the double-precision floating-point value for the
maximum radius of the teapot bowl.
GLU Quadric-Surface Functions
To generate a quadric surface using GLU functions
1. assign a name to the quadric,
2.activate the GLU quadric renderer, and
3.designate values for the surface parameters
• The following statements illustrate the basic sequence of calls for
displaying a wireframe sphere centered on the world-coordinate origin:
GLUquadricObj *sphere1;
sphere1 = gluNewQuadric ( );
gluQuadricDrawStyle (sphere1, GLU_LINE);
gluSphere (sphere1, r, nLongitudes, nLatitudes);
where,
• sphere1 is the name of the object the quadric renderer is activated with
the gluNewQuadric function, and then the display mode GLU_LINE is
selected for sphere1 with the gluQuadricDrawStyle command
• Parameter r is assigned a double-precision value for the sphere radius
• nLongitudes and nLatitudes. number of longitude lines and latitude lines
• To produce a view of a cone, cylinder, or tapered cylinder, we replace
the gluSphere function with
gluCylinder (quadricName, rBase, rTop, height, nLongitudes,
nLatitudes);
• The base of this object is in the xy plane (z=0), and the axis is the z
axis.
• rBase is the radius at base and rTop is radius at top
• If rTop=0.0,we get a cone; if rTop=rBase,we obtain a cylinder
• Height is the height of the object and latitudes and longitude values
will be given as nLatitude and nLongitude.
• A flat, circular ring or solid disk is displayed in the xy plane (z=0) and
centered on the world-coordinate origin with
gluDisk (ringName, rInner, rOuter, nRadii, nRings);
• We set double-precision values for an inner radius and an outer
radius with parameters rInner and rOuter.
• If rInner = 0, the disk is solid.
• Otherwise, it is displayed with a concentric hole in the center of the
disk.
• The disk surface is divided into a set of facets with integer parameters
nRadii and nRings
BÉZIER SPLINE CURVES
• It was developed by the French engineer Pierre Bézier for use in the
design of Renault automobile bodies.
• Bézier splines have a number of properties that make them highly
useful and convenient for curve and surface design. They are also
easy to implement.
• In general, a Bézier curve section can be fitted to any number of
control points, although some graphic packages limit the number of
control points to four.
Bézier Curve Equations
• We first consider the general case of n + 1 control-point positions,
denoted as pk = (x𝑘 , yk , zk), with k varying from 0 to n.
• These coordinate points are blended to produce the following
position vector P(u), which describes the path of an approximating
Bézier polynomial function between p0 and pn:

• The Bézier blending functions BEZk,n(u) are the Bernstein polynomials


• where parameters C(n, k) are the binomial coefficients

• A set of three parametric equations for the individual curve


coordinates can be represented as
Properties of Bézier Curves

Property1:
• A very useful property of a Bézier curve is that the curve
connects the first and last control point.
Property 2:
• Another important property of any Bézier curve is that it lies within
the convex hull (convex polygon boundary) of the control points.
• This follows from the fact that the Bézier blending functions are all
positive and their sum is always 1:
Other Properties:

• The basic functions are real.


• The degree of the polynomial defining the curve segment is one less
than the number of defining points.
• The curve generally follows the shape of the defining polygon,
• The tangent vectors at the ends of the curve have the same direction
as the first and last polygon spans respectively
Bézier Surfaces
• The parametric vector function for the Bézier surface is formed as
the tensor product of Bézier blending functions:
Input devices
• We can think about input devices in two
distinct ways.
• Physical devices-keyboard or a mouse
• logical devices - properties are specified in
terms of what they do from the perspective of
the application program
int x;
scanf(&x);
printf(“%d”,x);
Physical Input devices
• Two primary types of physical devices:
pointing devices
keyboard devices
Incremental (Relative) Devices
• Devices such as the mouse, trackball, joy stick
return incremental inputs (or velocities) to the
operating system.
• The computer can then integrate these values
to obtain a two- dimensional position.
• Thus as a mouse cursor moves across a
surface, the integrals of the velocities x,y
values can be converted to indicate the
position for a cursor on the screen.
Absolute positioning Devices

• Devices such as the data tablet return a


position directly to the operating system.
• A typical data tablet has rows and columns of
wires embedded under its surface.
• The position of the stylus is determined
through the electromagnetic interactions
between the signals travelling through the
wires and sensors in the stylus.
LightPen

• The lightpen contains a light sensing device


such as a photocell.
• If the lightpen is positioned on the face of the
CRT , the light emitted exceeds a threshold in
the photo detector and a signal is sent to the
computer.
Joystick
• The motion of the stick in two orthogonal
directions is encoded, interpreted as two
velocities, and integrated to identify a screen
location.
• The integration implies that if the stick is left in its
resting position, there is no change in the cursor
position and that farther the stick is moved from
its resting position, the faster the screen location
changes.
• advantage of the joystick is that the device can be
constructed with mechanical elements, such as
springs and dampers, that give resistance to a
user who is pushing the stick.
SpaceBall
• For three dimensional graphics , we might
prefer to use three-dimensional input devices.
• A spaceball looks like a joystick with a ball on
the end of the stick; however the stick does
not move.
• The pressure sensors in the ball measure the
forces applied by the user.
Logical Devices

• The two major characteristics describe the


logical behaviour of an input device:
• (1) the measurements that the device returns
to the user program
• (2) the time when the device returns those
measurements.
Classes of logical input devices
• String: A string device is a logical device that
provides ASCII strings to the user program,
implemented by means of a physical keyboard.
• Locator: A locator device provides a position in
the world coordinates to the user program,
implemented by means of a pointing device, such
as a mouse or a trackball.
• Pick: A pick device returns the identifier of an
object on the display to the user program,
implemented with the same physical device as a
locator
• Choice: Choice devices allow user to select one of the
discrete number of options.
In OpenGL, we can use various widgets provided by the
window system. A widget is a graphical interactive
device, provided by either the window system or a
toolkit.

• Stroke: A stroke device returns an array of locations.


Although we can think of a stroke device as similar to
multiple uses of a locator , it is often implemented
such that an action say, pushing down a mouse button ,
starts the transfer of data into the specified array, and a
second action , such as releasing the button , ends this
transfer.
Clients and Servers
• In this world our building blocks are entities
called servers that can perform tasks for
clients.
• Examples of servers include print servers,
which can allow sharing of high-speed printer,
compute servers, file servers.
• Users and the user programs that make use of
these services are clients or client programs.
Display Lists
• Display lists illustrate how we can use clients and
servers on a network to improve interactive graphics
performance.
• The Display Processor in modern graphics systems
could be considered as a graphics server.
• Retained mode – We define the object once, and then
put its description in a display list. The display list is
stored in the server and redisplayed by a simple
function call issued from the client to the server.
• It provides the advantage of reduced network traffic
• Executing the commands once and the results are
stored in display list on the graphics server.
• Disadvantage: requires memory on the server.
Definition and Execution of display
lists
• For example the following code defines a red box.

#define BOX 1
glNewList(BOX, GL_COMPILE);
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-1.0,-1.0);
glVertex2f(1.0,-1.0);
glVertex2f(1.0,1.0);
glVertex2f(-1.0,1.0);
glEnd();
glEndList();
• GL_COMPILE – Tells the system to send the list to
the server but not to display its contents.
• GL_COMPILE_AND_EXECUTE – Immediate display
of the contents while the list is being constructed.

• Each time that we wish to draw a box on the


server, we execute the function as follows:
glCallList(BOX);
• glPushAttrib(GL_ALL_ATTRIB_BITS) : used to
push the attributes into the stack
• glPushMatrix() : used to push matrix values
into the stack
• glPopAttrib() and glPopMatrix() are used to
pop the elements from the stack.
Text and Display Lists

• Code fragment to display letter ‘O’.

void ourFont()
{
glTranslatef(0.5,0.5,0.0);
glBegin(GL_QUAD_STRIP);
for(int i=0;i<=12;i++)
{
angle=3.14159/6.0*i;
glVertex2f(0.4*cos(angle),0.4*sin(angle));
glVertex2f(0.5*cos(angle),0.5*sin(angle));
}
glEnd();
}
Fonts in Glut
• GLUT provides a few raster and stroke fonts

• Function call for stroke text :


glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, int
character)
• Control the position of a character by using a translation
before the glutStrokeCharacter() function is called.

• Function call for bitmap text


glutBitmapCharacter(GLUT_BITMAP_8_BY_13, int
character)
• We usually control the position of a character by using the
glRasterPos*() before the glutBitMapCharacter() function is
called.
Display Lists And Modeling
#define EYE 1 glTranslatef(……);
glNewList(EYE);
/* code to draw eye */
glEndList();
# define FACE 2
glNewList(FACE);
/* Draw outline */
glTranslatef(…..) /*right eye position*/
glCallList(EYE);
glTranslatef(…..) /*left eye position*/
glCallList(EYE);
glTranslatef(…..) /*Nose position*/
glCallList(NOSE);
/*similar code for ears and mouth*/
Pointing Devices
• A mouse event occurs when the mouse is moved with one
of the buttons pressed.
• If the mouse is moved without a button being held down,
this event is called passive move event.
• After a move event, the position of the mouse – its
measure – is made available to the application program.
• A mouse event occurs when one of the mouse buttons is
either pressed or released.
• We register the mouse callback function, usually in the
main function, by means of the GLUT function as follows:
glutMouseFunc(mymouse);
• The mouse callback must have the form
void myMouse(int button, int state, int x, int y)
Window Events
• Most windows system allows user to resize
window.
• This is a window event and it poses several
problems like
• – Do we redraw all the images
• – The aspect ratio
• – Do we change the size or attributes of the
primitives to suit the new window
void myReshape(GLsizei w, GLsizei h)
{
/* first adjust clipping box */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble)w, 0.0, (GLdouble)h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
/* adjust viewport */
glViewport(0,0,w,h);
}
Keyboard Events
• Keyboard events are generated when the
mouse is in the window and one of the keys is
pressed or released.
• When a keyboard event occurs, the ASCII code
for the key that generated the event and the
mouse location are returned.
• All the keyboard callbacks are registered in a
single callback function, such as the following:
• glutKeyboardFunc(myKey);
• void myKey(unsigned char key, int x, int y)
{
if (key==‘q’ || key==‘Q’)
exit(0);
}
Callback : glutKeyboardFunc(myKey);
The Display and Idle callbacks
• Interactive and animation programs might contain many
calls for the reexecution of the display function.
• glutPostRedisplay() – Calling this function sets a flag inside
GLUT’s main loop indicating that the display needs to be
redrawn.
• At the end of each execution of the main loop, GLUT uses
this flag to determine if the display function will be
executed.
• The function ensures that the display will be drawn only
once each time the program goes through the event loop.
• Idle Callback is invoked when there are no other events to
be performed.
• Its typical use is to continuously generate graphical
primitives when nothing else is happening.
Idle callback : glutIdleFunc(function name)
Window Management
• GLUT supports creation of multiple windows
• Id = glutCreateWindow(“second window”);

• To set a particular window as the current


window where the image has to be rendered
glutSetWindow(id);
Menus

• GLUT supports pop-up menus to create a


sophisticated interactive applications.
• Three steps
• Define entries for the menu
• Define action for each menu item
• Action carried out if entry selected
• Attach menu to a mouse button
Input and Interaction

Module-5

1
Input Devices
• Physical input devices
– Keyboard devices and pointing devices
• Logical input devices

2
Pointing Devices – 1/2
• Mouse
– Mechanical versus optical

• Trackball

• Data tablet

3
Pointing Devices – 2/2

• Lightpen

• Joystick

• Spaceball

4
Positioning

• Relative
– Mouse, trackball, trackpoint
• Absolute
– Data tablet
5
Logical Input Devices – 1/2
• Characteristics
– The measurements returned to the programs
– The time these measurements returned
• Six classes of logical input devices

6
Logical Input Devices – 2/2
• String: by keyboard
• Locator: by mouse or trackball
• Pick: id of the selected object is returned
• Choice: select one of a distinct number of options,
e.g. menus
• Valuators: e.g. boxes to provide value.
• Stroke: returns an array of locations: multiple uses of
a locator, could be implemented by a “mouse
dragging”

7
Input Modes:
Measure and Trigger
• Measure: what returns to the user program
• Trigger: a physical input to signal the computer,
• for example:
– Measure of keyboard is single / set of chars
– Trigger is enter key.

8
Input Modes – 1/3
• Request mode: the measure of the device is
not returned to the program until the device is
triggered
• request_locator(device_id, &measure)

9
Input Modes – 2/3
• Sample mode: input is immediate, no trigger
is needed
• sample_locator(device_id, &measure)
• Both request and sample modes are useful for
the program where only one input device is
used.

10
Input Modes – 3/3
• Event mode: each time a device is triggered, an
event is generated, with the id for the device and
measurement is put in an event queue

11
Clients and Servers

• Servers: provide
services
– Print servers,
file servers,
graphics servers…
• Clients: users and user
programs that make
use of these services
– OpenGL application
programs
12
Display Lists

Simple graphics architecture

Display-processor architecture

13
Immediate Mode v.s. Retained Mode
• Immediate mode: as soon as the program
executes a statement for a object, the
primitive sent to the display and no memory is
retained for the object
• Retained mode: define an object once, and
put its description in the display list in the
server. Client issues a function call to the
server

14
Definition of Display Lists
• A unique identifier: #define BOX 1 /* or unused int */
• glNewList(BOX, GL_COMPILE);
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-1.0, -1.0);
glVertex2f(1.0, -1.0);
glVertex2f(1.0, 1.0);
glVertex2f(-1.0, 1.0);
glEnd();
glEndList();
• GL_COMPILE
• GL_COMPILE_AND_EXECUTE
15
Execution of Display Lists – 1/2
• glCallList(BOX);
• Different clipping windows
glMatrixMode(GL_PROJECTION);
for(i=1; i<5; i++)
{
glLoadIdentity();
gluOrtho2D(-2.0*i, 2.0*i,-2.0*i, 2.0*i);
glCallList(BOX);
}

16
Execution of Display List – 2/2
• Using stack to avoid interference with the current
matrix or attributes
• At the beginning of a display lists:
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushMatrix();
• At the end:
glPopAttrib();
glPopMatrix();

17
Raster Text v.s. Stroke Text
• Raster text:
– Fixed size for each character
e.g. a 8x13 raster character takes 13 bytes
– Not good for scaling or rotation
• Stroke text:
– No fixed size
– Could store the patterns in ROM,
selection is based on a single byte
– Good for scaling or rotation

18
A Stroke Text Example Using
void OurFont(char c) The Display Lists – 1/3
{
switch(c)
{
case ‘a’:

break;
case ‘A’:

break;

}
}

19
A Stroke Text Example Using
The Display Lists – 2/3

case ‘O’:
glTranslate(0.5, 0.5, 0.0); /* move to center */
glBegin(GL_QUAD_STRIP);
for(i=0; i<=12; i++) /* 12 vertices */
{
angle=3.14159/6.0*i; /* 30 degrees in radians */
glVertex2f(0.4*cos(angle), 0.4*sin(angle));
glVertex2f(0.5*cos(angle), 0.5*sin(angle));
}
glEnd();
glTranslate(0.5, -0.5, 0.0); /* move to lower right */
break; 20
A Stroke Text Example Using The
Display Lists – 3/3
• Base=glGenLists(256);
/* returns index of first of 256 consecutive available ids */
For(i=0; i< 256; i++)
{
glNewList(base+i, GL_COMPILE);
OurFont(I);
glEndList();
}
• glListBase(base);
• char *text_string;
glCallLists( (Glint strlen(text_string), GL_BYTE, text_string);
21
Fonts in GLUT

• GLUT provides a few raster and stroke fonts


• glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, int
character);
• glutBitmapCharacter(GLUT_BITMAP_8_BY_13,
int character);
• Raster position: where to place the next primitive
• glRasterPos2i(rx, ry);
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, k);
rx+=glutBitmapWidth(GLUT_BITMAP_8_BY_13, k);

22
Programming Event-Driven Input
• Using the pointing device
– Move event
• Mouse is moved and one of the button pressed
– Passive move event
• Mouse is moved and no buttons are pressed
– Mouse event: one of mouse buttons is pressed or
released
• glutMouseFunc(mouse): register the function
• void mouse(int button, int state, int x, int y)

23
Other Events and CallBacks

• Reshape event: whenever the window is resized


glutReshapeFunc(myReshape);
• Keyboard event:
glutKeyboardFunc(keyboard);
void keyboard(unsigned char key, int x, int y)
{
if(key==‘q’ || key == ‘Q’) exit();
}

24
Display and Idle CallBacks
• glutDisplay(display);
• Iconify
• glutPostRedisplay()
ensures the display will drawn at most once in the
main loop
• Idle callback: is invoked when there is no other
events
• Callback could be changed at any time or disabled by
set to NULL

25
A Program Example:
Drawing Squares with Mouse – 1/5
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutCreateWindow(“square”);
myinit();
glutReshapeFunc(myReshape);
glutMouseFunc(mouse);
glutMotionFunc(drawSquare);
glutDisplayFunc(display)
glutMainLoop();
} 26
A Program Example:
Drawing
void display(){} Squares with Mouse – 2/5
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_RIGHT_BUTTON &&
state==GLUT_DOWN) exit(0);
}
/* globals */
GLsize I wh=500, ww=500; /* initial window size */
GLfloat size=3.0; /* one-half of side length of square */

27
A Program Example:
Drawing Squares with Mouse – 3/5
void myinit(void)
{
/* set viewing conditions */
glViewport(0,0,ww,wh);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)ww, 0.0, (GLdouble) wh);
glMatrixMode(GL_MODELVIEW);
/* set clear color to black, and clear window */
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
} 28
A Program Example:
Drawing Squares
void drawSquare(int x, int y)
with Mouse – 4/5
{
y=wh-y;
glColor3ub((char) rand()%256, (char) rand()%256,
(char) rand()%256);
glBegin(GL_POLYGON);
glVertex2f(x+size, y+size);
glVertex2f(x-size, y+size);
glVertex2f(x-size, y-size);
glVertex2f(x+size, y-size);
glEnd();
glFlush();
} 29
A Program Example:
voidDrawing
myReshape(GLsizeiSquares
w, GLsizei h) with Mouse – 5/5
{
/* adjust clipping box */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (Gldouble)w, 0.0, (Gldouble)h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
/* adjust viewport and clear */
glViewport(0, 0, w, h);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
30
A Program Example:
Drawing Squares with Mouse

Demo

31
Window Management
• GLUT support multiple windows
• id=glutCreateWindow(“Second window);
glutSetWindow(id);
• Call glutInitDisplayMode before
glutCreateWindow() to set attributes

32
Menus – 1/2

• Pop-up menus
• glutCreateMenu(demo_menu); //register callback function
glutAddMenuEntry(“quit”,1);
glutAddMenuEntry(“increase square size”, 2);
glutAddMenuEntry(“decrease square size”, 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
• Void demo_menu(int id)
{
if(id == 1) exit();
else if(id==2) size=2*size;
else size=size/2;
glutPostRedisplay();
} 33
Hierarchical Menus – 2/2
• sub_menu=glutCreateMenu(size_menu);
glutAddMenuEntry(“increase square size”, 2);
glutAddMenuEntry(“decrease square size”, 3);
glutCreateMenu(top_menu);
glutAddMenuEntry(“quit”,1);
glutAddSubMenu(“resize”, sub_menu);
glutAttachMenu(GLUT_RIGHT_BUTTON);

34
Picking

35
Picking
• Identify a user-defined object on the display
• In principle, it should be simple because the mouse
gives the position and we should be able to determine
to which object(s) a position corresponds
• Practical difficulties
– Pipeline architecture is feed forward, hard to go from screen
back to world
– How close do we have to come to object to say we selected it?

36
Three Approaches
• Selection
– Adjusting the clipping region and viewport
such that we can keep track of which primitive
is near the cursor
• Use back or some other buffer to store
object ids as the objects are rendered
• Rectangular maps
– Easy to implement for many applications
– Boundary boxes or extents
37
Rendering Modes
• OpenGL can render in one of three modes
selected by glRenderMode(mode)
– GL_RENDER: normal rendering to the frame buffer
(default)
– GL_FEEDBACK: provides list of primitives rendered
but no output to the frame buffer
– GL_SELECTION: Each primitive in the view volume
generates a hit record that is placed in a name
stack which can be examined later

38
Selection Mode Functions
• glSelectBuffer(): specifies name buffer
• glInitNames(): initializes name buffer
• glPushName(id): push id on name buffer
• glPopName(): pop top of name buffer
• glLoadName(id): replace top name on buffer

• id is set by application program to identify


objects

39
Using Selection Mode
• Initialize name buffer
• Enter selection mode (using mouse)
• Render scene with user-defined identifiers
• Reenter normal render mode
– This operation returns number of hits
• Examine contents of name buffer (hit records)
– Hit records include id and depth information

40
Selection Mode and Picking
• As we just described it, selection mode won’t
work for picking because every primitive in
the view volume will generate a hit
• Change the viewing parameters so that only
those primitives near the cursor are in the
altered view volume
– Use gluPickMatrix(x,y,w,h,*vp)

41
Implementation of Picking
• Name stack: store the hit list
• glSelectBuffer(GLsizei n, GLuint *buff): specifies the
array “buff” of size n to place selection data
• glInitNames(): initializes the name stack
• glPushName(GLuint name): pushes name on the
name stack
• glPopName(): pops the top name from the name
stack
• glLoadName(GLuint name): replaces the top of the
name stack with the name

42
Implementation of Picking

• We cannot load a name onto an empty stack, so


we usually enter an unused name onto the stack
when we initializes it:
glInitName();
glPushName(0);
• We could set our new clipping volume to obtain a
hit list
• It’s better to use PushMatrix() to save our present
matrix
43
Implementation of Picking
• Use gluPickMatrix(x, y, w, h, *vp) to create a
projection matrix for picking that restricts drawing to
a w x h area centered at (x, y) in window coordinates
within the viewport vp

44
Example Code for Picking
void mouse(int button, int state, int x, int y)
{
GLuint nameBuffer[SIZE]; /* define SIZE 512 */
GLint hits;
GLint viewport[4];
if(button==GLUT_LEFT_BUTTON &&
state==GLUT_DOWN)
{
/* initialize the name stack */
glInitName();
glPushName(0);
}
45
Example Code for Picking
glSelectBuffer(SIZE, nameBuffer);
glRenderMode(GL_SELECT);
/* set up viewing for selecting mode */
glGetIntegerv(GL_VIEWPORT, viewport);
glMatrixMode(GL_PROJECTION);
/* save original viewing matrix */
glPushMatrix();
glLoadIdentity();

46
Example Code for Picking

/* 5 x 5 pick area around the cursor */


/* must invert mouse y to get in world coordinates */
gluPickMatrix((GLdouble)x, (GLdouble)
(viewport[3]-y), 5, 5, viewport);
/* same clipping window as in reshape callback */
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
drawObjects(GL_SELECT);
glMatrixMode(GL_PROJECTION);
/* restore viewing matrix */
glPopMatrix();
glFlush();
47
Example Code for Picking
/* return to normal render mode */
hits=glRenderMode(GL_RENDER);
/* the return of glRenderMode depends on the current
mode */

/* processHits(hits, nameBuffer);
/* normal render */
glutPostRedisplay();
}
}

48
Example Code for Picking
void display()
{
glClear(GL_COLOR_BUFFER_BUT);
draw_Objects(GL_RENDER);
glFlush();
}
void drawObjects(GLenum mode)
{
if(mode==GL_SELECT) glLoadName(1);
glColor3f(1.0, 0.0, 0.0);
glRectf(-0.5, -0.5, 1.0, 1.0);
if(mode==GL_SELECT) glLoadName(2);
glColor3f(0.0, 0.0, 1.0);
glRectf(-1.0, -1.0, 0.5, 0.5);
} 49
Example Code for Picking
void processHits(GLint hits, GLuint buffer[])
{ unsigned int i, j;
GLuint name, *ptr;
printf(“hits=%d\n”,hits);
for (i=0; i<hits; i++) /* loop over number of hits */
{ names=*ptr;
ptr+=3; /* skip over number of names and depths */
for(j=0; j< name; j++) /* check each name in record */
{ if(*ptr==1) printf(“red rectangle\n”);
else printf(“blue rectangle\n”);
ptr++;
}
/* go to next hit record */
}
} 50
Example Code for Picking

Demo

51
Animating Interactive Programs
• Suppose that we want to create a picture in
which one or more objects are changing or
moving and thus their images must change.
• For example, we might want to have an
animated character walk across the display, or
might want to move the viewer over time.
• We can gain insight into how we handle these
cases through a simple example.

52
Animating Interactive Programs
A Rotating Square

• Consider the two points x=cos y=sin


• (cos, sin ), (-sin, cos), (-cos, -sin),
(sin, -cos) lie on the unit circle

53
A Rotating Square
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
thetar=theta/((2*3.14159/360); /* degrees to radians */
glVertex2f((cos(thetar), sin(thetar));
glVertex2f(-sin(thetar), cos(thetar));
glVertex2f(-cos(thetar), -sin(thetar));
glVertex2f(sin(thetar), -cos(thetar));
glEnd();
}

54
A Rotating Square
glutIdleFunc(idle);
void idle()
{
theta+=2; /* or some other amount */
if(theta>=360.0) theta-=360.0;
glutPostRedisplay();
}

glutMouseFunc(mouse);
Void mouse(int button, int state, int x, int y) {
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
glutIdleFunc(idle);
if(button==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN)
glutIdleFunc(NULL);
} 55
A Rotating Square

Demo

56
Double Buffering
• When we display the contents of the frame
buffer, we want to do so at the rate
sufficiently high that we cannot notice the
clearing and redrawing of the screen.
• As long as the contents of the frame buffer are
unchanged and we refresh at the rate 60 and
85 times per second or we will notice the
display flickering.

57
• If the display being drawn is complex and
cannot be drawn in a single refresh cycle, we
see different parts of the objects on
successive refreshes.
• Double buffering provides the solution to this
problem.
• The front buffer is always the one displayed,
whereas the back buffer is the one into which
we draw.
• We can swap the front and back buffers at will
from the application program.
58
Double Buffering
• Front buffer and back buffer
• glutInitDisplayMode(GLUT_DOUBLE)
• Add glutSwapBuffers() at the end of the
display function.

59
Using a Timer
• Consider what happens if we take a simple
program such as the rotating square and
execute it on a fast GPU.
• Square will be rendered thousands of times
per second and we will see it rotating very fast
and hence it may look blur.

60
There are three approaches for this problem
– Use various timing mechanism provided by
libraries or OS to include delay in the application
program.
– Allow the user to set an option under which
swapping of buffers is locked to the refresh rate.
– GLUT provides the following third option through
the timer function:
glutTimerFunc(int delay, void (*timer_func)(int), int
value)

61
Design of Interactive Programs
• Features of good interactive program
– A smooth display with no flickering
– A variety of interactive devices
– A variety of methods for entering and displaying
information
– An easy-to-use interface
– Feedback to the user
– Tolerance for user error
– A design that incorporates consideration of both the visual
and motor properties of the human.

62
Rubberbanding

Demo

63
Rubberbanding
• Technique used for displaying primitives that
change as they are manipulated interactively.
• One end is fixed to the first location and the
other end are stretched to wherever the
cursor is moved.
• Rubber banding begins when a mouse button
is pressed and continues until the mouse
button is released.

64
Logic Operation
• When a program specifies a primitive that is visible,
OpenGL renders it into a set of colored pixels that are
written into the present drawing buffer.
• Default mode- pixels simply replace the corresponding
pixels that are in the frame buffer.
• Copy (replacement )mode-pixel that we want to write
is source pixel, the pixel in the drawing buffer that the
source pixel will affect is called destination pixels.
• In copy mode the source pixel replaces the destination
pixel.

65
Logic Operation
• There are 16 possible operations between 2 bits
Source pixel and destination pixel
• The first is replacement mode.
• Second mode is exclusive or
• d=ds, where  means XOR (exclusive or)
d=(ds) s, which means drawing something twice
will erase it
• OpenGL support all 16 logic modes, GL_COPY is the
default
• glEnable(GL_COLOR_LOGIC_OP);
glLogicOP(GL_XOR); /* change it to XOR mode */
66
XOR and Color
• (00000000, 00000000, 11111111) 
(11111111, 11111111, 11111111) =
(11111111, 11111111, 00000000)
Blue  White = Yellow
• If a blue line crosses a red object, it will be
colored as magenta inside the object
• XOR mode is used for drawing a Cursor on the
display.

67
• If there is a bit set in the red overlay plane and
the corresponding bit is not set in the green and
blue overlay plane, then the corresponding point
is red, no matter what its original RGB value is.
• The contents of the overlay planes act as if their
values were copied into the color buffer.
• Overlay planes are hardware features and are
not present in all systems.

69

You might also like