cap 4703 computer graphic methods prof. roy levow lecture 3
Post on 31-Dec-2015
222 Views
Preview:
TRANSCRIPT
CAP 4703CAP 4703Computer Graphic Computer Graphic
MethodsMethodsProf. Roy LevowProf. Roy Levow
Lecture 3Lecture 3
Input and InteractionInput and Interaction
User interaction is an important User interaction is an important aspect of many graphic applicationsaspect of many graphic applications
Best supported through a standard Best supported through a standard APIAPI– Programmer avoids nasty Programmer avoids nasty
implementaiton detailsimplementaiton details GLUT provides support for OpenGLGLUT provides support for OpenGL
Input DevicesInput Devices
API supports logical devicesAPI supports logical devices– Defined by capabilities rather than Defined by capabilities rather than
physical designphysical design Different physical devices may Different physical devices may
provide same capabilitiesprovide same capabilities– Mouse, Trackball, possibly Light PenMouse, Trackball, possibly Light Pen
Types of Input DevicesTypes of Input Devices
Pointing devicePointing device– Mouse, TrackballMouse, Trackball– Data tablet reports position of stylus on Data tablet reports position of stylus on
tablet surfacdtablet surfacd– Light pen reports position of pen on Light pen reports position of pen on
screenscreen– Reports position in imageReports position in image
Keyboard deviceKeyboard device– Character streamCharacter stream
Types of Input Devices (cont)Types of Input Devices (cont)
JoystickJoystick– Reports x-y displacementReports x-y displacement– Usually treated as direction vectorUsually treated as direction vector
Space ballSpace ball– Fixed ball on stickFixed ball on stick– Senses x, y, x Senses x, y, x
pressure as well pressure as well as 3-axis rotational as 3-axis rotational pressurepressure
Logical Input DevicesLogical Input Devices
String deviceString device– Provides character strings as inputProvides character strings as input
Locator DeviceLocator Device– Provides position in world coordinatesProvides position in world coordinates
Pick devicePick device– Returns a reference to an objectReturns a reference to an object– Usually implemented with a locatorUsually implemented with a locator
Logical Input Devices (cont)Logical Input Devices (cont)
Choice deviceChoice device– Selection from a discrete number of Selection from a discrete number of
objectsobjects– Usually impemented with a window Usually impemented with a window
widget: menu, button, etc.widget: menu, button, etc. Dial deviceDial device
– Provides digitized analog inputProvides digitized analog input Stroke deviceStroke device
– Returns array of locationsReturns array of locations– Often the track of a locator deviceOften the track of a locator device
Measure and TriggerMeasure and Trigger
Measure of a device is the data it Measure of a device is the data it provides to the programprovides to the program
Trigger is the action that causes the Trigger is the action that causes the data to be sentdata to be sent
Input ModesInput Modes
Request modeRequest mode– Program requests data from deviceProgram requests data from device– Requires trigger but input may not be Requires trigger but input may not be
accepted by program until a later time accepted by program until a later time of the programmer’s choiceof the programmer’s choice
Sample modeSample mode– Input is immediateInput is immediate– No trigger is neededNo trigger is needed
Input Modes (cont)Input Modes (cont)
Event modeEvent mode– Supports asynchronous interactionSupports asynchronous interaction– Events are queued for event handlerEvents are queued for event handler
Clients and ServersClients and Servers
Servers perform tasks for clientsServers perform tasks for clients– Client requestsClient requests– Server respondsServer responds
A windowed system is a serverA windowed system is a server– Provides display and input services to a Provides display and input services to a
program using the displayprogram using the display
Display ListsDisplay Lists
Display list or display fileDisplay list or display file– Instructions to display processor to generate Instructions to display processor to generate
imageimage– Stored in memoryStored in memory
Immediate modeImmediate mode– Display server generates image and does not Display server generates image and does not
retain commandsretain commands Retained modeRetained mode
– Display list is stored on graphics serverDisplay list is stored on graphics server– Can be used to regenerate imagesCan be used to regenerate images
Definition & ExecutionDefinition & Executionof Display Listsof Display Lists
Generated like geometric objectsGenerated like geometric objects Bounded byBounded by
– glNewList(item, GL_COMPILE)glNewList(item, GL_COMPILE)– glEndList()glEndList()
Imaging commands are generated Imaging commands are generated and sent to display server but not and sent to display server but not displayeddisplayed
Displayed immedaitely if second Displayed immedaitely if second parameter is parameter is GL_COMPILE_AND_EXECUTEGL_COMPILE_AND_EXECUTE
Executing Display ListsExecuting Display Lists
Display list withDisplay list with– glCallList(item)glCallList(item)
Each time list is displayed, current Each time list is displayed, current model-view and projection matrices model-view and projection matrices are applied, possibly changing imageare applied, possibly changing image
Display list is more efficient than Display list is more efficient than regenerating imageregenerating image
Executing Display Lists (cont)Executing Display Lists (cont)
Attributes changed in a display list Attributes changed in a display list alter state and remain in effect after alter state and remain in effect after list is displayedlist is displayed– This may be a problemThis may be a problem
Solution involves using OpenGL Solution involves using OpenGL attribute and matrix stacks. Push attribute and matrix stacks. Push current values before executing list current values before executing list and pop them afterand pop them after
Attribute and Matrix StacksAttribute and Matrix Stacks
Save withSave withglPushAttrib(GL_ALL_ATTRIB_BITS);glPushAttrib(GL_ALL_ATTRIB_BITS);glPushMatrix();glPushMatrix();
Restore withRestore withglPopAttrib();glPopAttrib();glPopMatrix();glPopMatrix();
(skipping sectin 3.4.2)(skipping sectin 3.4.2)
Event-Driven ProgrammingEvent-Driven Programming
Programmer provides functions to be Programmer provides functions to be executed when an event occursexecuted when an event occurs
Functions are registered with system Functions are registered with system and called when event occursand called when event occurs– Implementation may be based onImplementation may be based on
functions with standard names as in Javafunctions with standard names as in Javacallback functions registered with system as callback functions registered with system as
in OpenGLin OpenGLfunction has standard prototype to deliver function has standard prototype to deliver
event dataevent data
Mouse Event CallbackMouse Event Callback
Function name may be freely chosenFunction name may be freely chosen Function prototypeFunction prototype
void mouse(int button, int state,void mouse(int button, int state,
int x, int y)int x, int y) Declared constants for button and Declared constants for button and
state likestate like
GLUT_LEFT_BUTTONGLUT_LEFT_BUTTON
GLUT_DOWNGLUT_DOWN
Mouse Event CallbackMouse Event Callback
Function registrationFunction registration
glutMouseFunc(mouse)glutMouseFunc(mouse)
Adding EventsAdding Events
Example programExample program from section 3.5.1 from section 3.5.1 main() has two added elementsmain() has two added elements
– glutReshapeFunc()glutReshapeFunc()Called when window is reshapedCalled when window is reshaped
– glutMouseFunc()glutMouseFunc()Called when mouse button is pressed or Called when mouse button is pressed or
releasedreleased
Program FunctionsProgram Functions
MouseMouse– Draw a square at the current location Draw a square at the current location
using default parameters when left using default parameters when left button is pressedbutton is pressed
– Exit when middle button is pressedExit when middle button is pressedWhat about windows?What about windows?
InitInit– sets viewsets view– clear to blackclear to black
Program Functions (cont)Program Functions (cont)
drawSquaredrawSquare– Draws fixed size square in random colorDraws fixed size square in random color– Note inversion of y-coordinateNote inversion of y-coordinate
Translates window (mouse) to displayTranslates window (mouse) to display
ReshapeReshape– A window eventA window event
parameters for GLsizei w, hparameters for GLsizei w, h
– Resize view port and clipping to Resize view port and clipping to preserve aspect for square in windowpreserve aspect for square in window
Keyboard EventsKeyboard Events
Triggered when key is pressed onlyTriggered when key is pressed only Returns character and x, y mouse Returns character and x, y mouse
location when key is pressedlocation when key is pressed
Display and Idle CallbacksDisplay and Idle Callbacks
glutDisplayFunc(display)glutDisplayFunc(display)– Called whenever window needs to be Called whenever window needs to be
redisplayedredisplayed glutPostRedisplay()glutPostRedisplay()
– Redisplay only once each iteration of Redisplay only once each iteration of GLUT main loopGLUT main loop
– Avoids unnecessary redisplayAvoids unnecessary redisplay
MenusMenus
GLUT supports pop-up menusGLUT supports pop-up menus Menu creationMenu creation
glutCreateMenu(demo_menu);glutAddMenuEntry("quit",1);glutAddMenuEntry("increase square size", 2);glutAddMenuEntry("decrease square size", 3);glutAttachMenu(GLUT_RIGHT_BUTTON);
Callback function has single int Callback function has single int parameter for menu itemparameter for menu item
GLUT Menus (cont)GLUT Menus (cont)
Also supports hierarchical menusAlso supports hierarchical menussub_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);
PickingPicking
SelectionSelection– Adjust clipping regionAdjust clipping region– Add items in region to Add items in region to hit listhit list
Bounding rectangle or extentBounding rectangle or extent– Mark regionMark region– Add items in marked region to hit listAdd items in marked region to hit list
Use back buffer to display each item Use back buffer to display each item in different colorin different color– Identify selected itemsIdentify selected items
OpenGL Selection ModeOpenGL Selection Mode
Selection mode display allows pickingSelection mode display allows picking– Selected item – hitSelected item – hit– Stored on name stackStored on name stack
Key functionsKey functions– Create array for stackCreate array for stack void glSelectBuffer(GLsizei n, void glSelectBuffer(GLsizei n, // eg 512
GLunint *buff)GLunint *buff)– Initialize name stackInitialize name stack
void glInitNames()void glInitNames()
OpenGL Selection ModeOpenGL Selection Mode
Push name on stackPush name on stack void glPushName(GLunint name)void glPushName(GLunint name) Pop top of stackPop top of stack
void glPopName()void glPopName() Replace top nameReplace top name
void glLoadName(GLunint name)void glLoadName(GLunint name) Must initialize by pushing a useless Must initialize by pushing a useless
value, say 0value, say 0
Selection ModeSelection Mode
Values on stack at the time an item Values on stack at the time an item is drawn determine its nameis drawn determine its name
glLoadName(i);glLoadName(i);
drawFigure(i);drawFigure(i); If stack contains more than one If stack contains more than one
value, name has multiple value, name has multiple components – one for each value on components – one for each value on the stackthe stack
Pick MatrixPick Matrix
Get current mouse location withGet current mouse location with
glGetIntegerv (GL_VIEWPORT,glGetIntegerv (GL_VIEWPORT,
viewport); // vp is GLint[4]viewport); // vp is GLint[4] Set selection rectangle with Set selection rectangle with
gluPickMatrix(x, y, width, height,gluPickMatrix(x, y, width, height,
viewport)viewport)
// x,y,w,h are GLdoubles// x,y,w,h are GLdoubles
Example Pick ProgramExample Pick Program
..\openglbk\picksquare.c..\openglbk\picksquare.c
Simple Paint ProgramSimple Paint Program
see see newpaint.cnewpaint.c
AnimationAnimation
glutIdleFunction() specifies a callback glutIdleFunction() specifies a callback function to use when the main loop is function to use when the main loop is idleidle
The callback can draw an altered The callback can draw an altered image each time it is called and call image each time it is called and call glutPostRedisplay() to display itglutPostRedisplay() to display it
To disble the animation, register To disble the animation, register NULL as the Idle FunctionNULL as the Idle Function
Double BufferingDouble Buffering
When redrawing an image, we want When redrawing an image, we want the new image to be displayed the new image to be displayed quickly enough that the redrawing quickly enough that the redrawing operation will not be visibleoperation will not be visible
Double Buffering creates the new Double Buffering creates the new image in a second buffer and image in a second buffer and displays it only on completion of displays it only on completion of drawingdrawing
Double Buffering (cont)Double Buffering (cont)
Enabled by setting Enabled by setting – GLUT_DOUBLE IN glutInitDisplayMode()GLUT_DOUBLE IN glutInitDisplayMode()
Front buffer is displayedFront buffer is displayed Back buffer is the one into which we Back buffer is the one into which we
drawdraw Swap buffersSwap buffers
– glutSwapBuffers()glutSwapBuffers()
FlickerFlicker
Clearing areas in an image can Clearing areas in an image can produce flickerproduce flicker
Double buffering can help with thisDouble buffering can help with this But we have to repeatedly draw But we have to repeatedly draw
thingsthings Can set the drawing buffer withCan set the drawing buffer with
– glDrawBuffer(which)glDrawBuffer(which)GL_BACK, GL_FRONT_AND_BACKGL_BACK, GL_FRONT_AND_BACK
Logic OperationsLogic Operations
Drawing can be done in copy mode, Drawing can be done in copy mode, also called replacement modealso called replacement mode– pixels are set by drawingpixels are set by drawing
or by performing one of 16 possible or by performing one of 16 possible functions on 2 biitsfunctions on 2 biits
in XOR modein XOR mode– new pixel value is XORed with current new pixel value is XORed with current
pixel valuepixel value
Logic ModesLogic Modes
OpenGL supports all 16 modesOpenGL supports all 16 modes Default is GL_COPYDefault is GL_COPY Enable use of other modes withEnable use of other modes with
– glEnable(GL_COLOR_LOGIC_OP)glEnable(GL_COLOR_LOGIC_OP) Set withSet with
– glLogicOP()glLogicOP() GL_COPY, GL_XOR, …GL_COPY, GL_XOR, …
Redrawing in XOR mode erasesRedrawing in XOR mode erases Can also change color, reverse with all 1’sCan also change color, reverse with all 1’s
top related