【文档说明】计算机图形学computer-graphics课件7.ppt,共(45)页,1.108 MB,由小橙橙上传
转载请保留链接:https://www.ichengzhen.cn/view-77496.html
以下为本文档部分文字说明:
InputandInteractionYuanfengZhouShandongUniversitySoftwareCollege1Objectives•Introducethebasicinputdevices-PhysicalDevices-Logica
lDevices-InputModes•Event-driveninput•Introducedoublebufferingforsmoothanimations•ProgrammingeventinputwithGLUT2ProjectSketchpad•IvanSutherland(M
IT1963)establishedthebasicinteractiveparadigmthatcharacterizesinteractivecomputergraphics:-Userseesanobjectonthedisplay-Userpointsto
(picks)theobjectwithaninputdevice(lightpen,mouse,trackball)-Objectchanges(moves,rotates,morphs)-Repeat3InteractionwithGraphicsSyst
em4ChangeImageReacttoChangeGraphicsSystemUserInputDeviceDisplayGraphicalInput•Devicescanbedescribedeitherby-Physicalprop
erties•Mouse•Keyboard•Trackball(Thinkpad)-Logicalproperties•WhatisreturnedtoprogramviaAPI(ApplicationProgrammingInterface
)–Aposition–Anobjectidentifier•Modes-Howandwheninputisobtained•Requestorevent5LogicalProperties6ApplicationModelA
pplicationProgramGraphicsSystemOutputDevicesInputDevicesAPIFunctionCallsorProtocolDataWM_LBUTTONDOWN#defineON_BN_LBUTTONDOWN(id,memberFxn
)voidCMyProgram::OnLButtonDown(UINTnFlags,CPointpoint){processingcode…CButton::OnLButtonDown(nFlags,point
);}PhysicalDevices7mousetrackballlightpendatatabletjoystickspaceballLogicalDevices•ConsidertheCandC++code-C++:cin>>x;-C:scanf(“%d”,&x);•Whatisth
einputdevice?-Can’ttellfromthecode-Couldbekeyboard,file,outputfromanotherprogram•Thecodeprovideslogicalinput-Anumber(anint)isretur
nedtotheprogramregardlessofthephysicaldevice8GraphicalLogicalDevices•Graphicalinputismorevariedthaninputtostandardprogramswhichisusuallyn
umbers,characters,orbits•TwoolderAPIs(GKS77’,PHIGS90’)definedsixtypesoflogicalinput:-Locator:returnaposition-Pick:returnIDofanobject-
Keyboard:returnstringsofcharacters-Stroke:returnarrayofpositions-Valuator:returnfloatingpointnumber-Choice:returnoneofnitems910XWind
owInput•TheXWindowSystemintroducedaclient-servermodelforanetworkofworkstations-Client:OpenGLprogram-GraphicsServer:bitmapdisplaywithapointingdevic
eandakeyboardDisplayListinOpenGL•Matrixcomputation•Imagedisplay•Light,material•Texture•Polygonalobjectsdisplay11Displ
ayListinOpenGL•voidglNewList(GLuintlist,GLenummode);•mode:GL_COMPILEandGL_COMPILE_AND_EXECUTE•voidglEn
dList(void);•NOTincludedinDisplayList:•glDeleteLists()glIsEnable()•glFeedbackBuffer()glIsList()•glFinish()glPixelStore()•glGenLists
()glRenderMode()•glGet*()glSelectBuffer()12DisplayListinOpenGL•Example:GLuintlistName=1;voidmyinit(void){glNewList(listName,GL_COMPILE);glColo
r3f(1.0,0.0,0.0);glBegin(GL_TRIANGLES);glVertex2f(0.0,0.0);glVertex2f(1.0,0.0);glVertex2f(0.0,1.0);glEnd();glTranslatef(1.5,
0.0,0.0);glEndList();glShadeModel(GL_FLAT);}13voidCALLBACKdisplay(void){GLuinti;glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.0
,1.0,0.0);glPushMatrix();for(i=0;i<5;i++)glCallList(listName);drawLine();glPopMatrix();glFlush();}InputMode•Inputdevicescontai
natriggerwhichcanbeusedtosendasignaltotheoperatingsystem-Buttononmouse-Pressingorreleasingakey•Whentr
iggered,inputdevicesreturninformation(theirmeasure)tothesystem-Mousereturnspositioninformation-KeyboardreturnsASCIIcode14RequestMode•Inp
utprovidedtoprogramonlywhenusertriggersthedevice•Typicalofkeyboardinput-Canerase(backspace),edit,correctuntilenter(retur
n)key(thetrigger)isdepressed151.Programrequestsmeasureofadeviceandblocks.2.Measureprocessmaintainscurrentmeasure.3.Triggerprocesssignalsm
easureprocesstoreturnmeasure.request_locator(device_id,&measure);EventMode•Mostsystemshavemorethanoneinputdevice
,eachofwhichcanbetriggeredatanarbitrarytimebyauser•Eachtriggergeneratesaneventwhosemeasureisputinaneventqueuewhichcanbeexam
inedbytheuserprogram16glutMainLoop();EventTypes•Window:resize,expose,iconify•Mouse:clickoneormorebuttons•Motion:movemouse•Ke
yboard:pressorreleaseakey•Idle:nonevent-Definewhatshouldbedoneifnoothereventisinqueue17Callbacks•Programminginterfaceforevent-driveninput•Defineaca
llbackfunctionforeachtypeofeventthegraphicssystemrecognizes•Thisuser-suppliedfunctionisexecutedwhentheeventoccurs•GLUTexample:glutMouseFunc(m
ymouse)18mousecallbackfunction19GLUTcallbacksGLUTrecognizesasubsetoftheeventsrecognizedbyanyparticularwindowsystem(Windows,X,Macintosh)-glutDisplayF
unc-glutMouseFunc-glutReshapeFunc-glutKeyboardFunc-glutIdleFunc-glutMotionFunc-glutPassiveMotionFuncGLUTEventLoop•Recallth
atthelastlineinmain.cforaprogramusingGLUTmustbeglutMainLoop();whichputstheprograminaninfiniteeventloop•Ineachpassthroughtheeventloop
,GLUT-looksattheeventsinthequeue-foreacheventinthequeue,GLUTexecutestheappropriatecallbackfunctionifoneisdefine
d-ifnocallbackisdefinedfortheevent,theeventisignored20Usingglobals•TheformofallGLUTcallbacksisfixed-void
mydisplay()-voidmymouse(GLintbutton,GLintstate,GLintx,GLinty)•Mustuseglobalstopassinformationtocallbacks21floatt;/*globa
l*/voidmydisplay(){/*drawsomethingthatdependsont}GLUTDisplayEventTrigger:GLUTdeterminesthatthewindowneedstoberedisplayed.Adisplayeventisgeneratedwhe
nthewindowisfirstdrawn.Callbackfunctionform:voiddisplay();Registration:glutDisplayFunc(display);Thedisplaycallbackisexecutedwhene
verGLUTdeterminesthatthewindowshouldberefreshed,forexampleWhenthewindowisfirstopenedWhenthewindowisreshape
dWhenawindowisexposedWhentheuserprogramdecidesitwantstochangethedisplay23Postingredisplays•Manyeventsmayinv
okethedisplaycallbackfunction-Canleadtomultipleexecutionsofthedisplaycallbackonasinglepassthroughtheeventloop
•WecanavoidthisproblembyinsteadusingglutPostRedisplay();whichsetsaflag.•GLUTcheckstoseeiftheflagissetattheendoftheeven
tloop•Ifsetthenthedisplaycallbackfunctionisexecuted24AnimatingaDisplay•Whenweredrawthedisplaythroughthedisplaycallback,weusuallysta
rtbyclearingthewindow-glClear()thendrawthealtereddisplay•Problem:thedrawingofinformationintheframebuf
ferisdecoupledfromthedisplayofitscontents-Graphicssystemsusedualportedmemory•Hencewecanseepartiallydrawndisplay-Seetheprogramsingle_double.
cforanexamplewitharotatingcubeGLUTMouseEventTrigger:Anymousebuttonisdepressedorreleased.Callbackfunctionform:voidmouse_callba
ck_func(intbutton,intstate,intx,inty);Registration:glutMouseFunc(mouse_callback_function);GLUTDefinedMouseConstantsGLUT_LEF
T_BUTTONGLUT_MIDDLE_BUTTONGLUT_RIGHT_BUTTONGLUT_UPGLUT_DOWNSystemswithonlyonemousebuttoncanonlygenerateaGLUT_LEFT_BUTTONcallback.GLUTReshapeEv
entTrigger:ActivewindowisresizedCallbackfunctionform:voidreshape_func(GLsizeiw,GLsizeih);Registration:glutReshapeFunc(reshape_func);GLUTMo
veEventTrigger:Themouseismovedwhileoneormoremousebuttonsarepressed.Callbackfunctionform:voidmotion_func(intx,
inty);Registration:glutMotionFunc(motion_func);GLUTKeyboardEventTrigger:Anykeyisdepressed.Callbackfunctionform:voidkeyboard_functi
on(unsignedcharkey,intx,inty);Registration:glutKeyboardFunc(keyboard_function);OtherDefinedEventsinGLUTglutPassiv
eMotionFuncglutVisibilityFuncglutEntryFuncglutSpecialFuncglutSpaceballMotionFuncglutSpaceballRotateFuncglu
tSpaceballButtonFuncglutButtonBoxFuncglutDialsFuncglutTabletMotionFuncglutTabletButtonFuncglutMenuStatusFuncExample:SimpleSquareDrawingPr
ogram•Openawindow.•Clearittoblack.•Drawaboxatlocationofthemouseeachtimetheleftbuttonisclicked.Colorofboxshouldberandomlyselectedf
romRGBspace.•Clearwindowwhenresized.•Quitwhenrightbuttonisclicked.SquareProgramSourceCodeSlide1/*Thisprogramillustratestheuseofth
eglutlibraryforinterfacingwithaWindowSystem*//*Theprogramopensawindow,clearsittoblack,thendrawsaboxatthelocationofthe
mouseeachtimetheleftbuttonisclicked.TherightbuttonexitstheprogramTheprogramalsoreactscorrectlywhenthewindowismovedorresizedbyclearingthenewwin
dowtoblack*/#include<GL/gl.h>#include<GL/glut.h>/*globals*/GLsizeiwh=500,ww=500;/*initialwindowsize*/GLfloatsize=3.0;/*halfsi
delengthofsquare*/SquareProgramSourceCodeSlide2voiddrawSquare(intx,inty){y=wh-y;glColor3f((char)random()%256,(
char)random()%256,(char)random()%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();}SquareProgramSourceCodeSlide3voidmyReshape(GLsizeiw,GLsizeih){/*adjustclippingbox*/glMat
rixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0);glMatrixMode(GL_MODELVIEW);glLoadIdentity();/*adju
stviewportandclear*/glViewport(0,0,w,h);glClearColor(0.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();/*setglobalsizeforusebydr
awingroutine*/ww=w;wh=h;}SquareProgramSourceCodeSlide4voidmyinit(void){glViewport(0,0,ww,wh);/*Pick2Dc
lippingwindowtomatchsizeofscreenwindowThischoiceavoidshavingtoscaleobjectcoordinateseachtimewindowisresized*/glMatrixMode(GL_PR
OJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)ww,0.0,(GLdouble)wh,-1.0,1.0);/*setclearcolortoblackandclearwindow*/glClearColor(0
.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();/*callbackroutineforreshapeevent*/glutReshapeFunc(myReshape);}SquareProgramSourceCodeSlide
5voidmouse(intbtn,intstate,intx,inty){if(btn==GLUT_RIGHT_BUTTON&state==GLUT_DOWN)exit();}intmain(intargc,char**argv){glutInit(&argc,argv);gl
utInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutCreateWindow("square");myinit();glutReshapeFunc(myReshape);glutMouseFunc(mo
use);glutMotionFunc(drawSquare);glutMainLoop();}Outputof“Square”programImplementingChoice:MenusinGLUT•Foursteps:-Crea
temenu:glutCreateMenu(menu);-Definemenuentries:glutAddMenuEntry-Attachmenutoamousebutton:gluAttachMenu-Definecallbackfunction:voi
dmenu(intid);CreatingaMenuinGLUTintglutCreateMenu(void(*func)(intvalue));Createsanewpop-upmenu.Returnsau
niqueintegeridentifierforthemenu.Takesasargumentapointertoasinglecallbackfunctionthattakesanintegerargument.Theintegerargumentofthecallbackismap
pedtothemenuchoice.Setsthecurrentmenutothenewlycreatedmenu.MenuIdentifierCallbackFunctionChoiceAssociatingaMenuwithaMouseKeyvoidglutAttac
hMenu(intbutton);Associatestheselectedbuttonwiththecurrentmenu.buttonisselectedfromtheGLUTdefinedbuttonconstants:GLUT_LEFT_BUTTON,GLUT_MID
DLE_BUTTON,GLUT_RIGHT_BUTTONAddingEntriestotheMenuvoidglutAddMenuEntry(char*name,intvalue);Stringtoappearinmenuentry.Valuetobepassedtocallbackfuncti
on.Addsamenuentrytothebottomofthecurrentmenu.BuildingaSub-menuvoidglutAddSubMenu(char*name,intmenu);Stringtodisplayinth
emenuitemfromwhichtocascadesub-menu.Identifierofmenutocascadefromthissub-menuitem.DoubleBuffering•Insteadofonecol
orbuffer,weusetwo-FrontBuffer:onethatisdisplayedbutnotwrittento-BackBuffer:onethatiswrittentobutnotdisplayed
•Programthenrequestsadoublebufferinmain.c-glutInitDisplayMode(GL_RGB|GL_DOUBLE)-Attheendofthedisplaycallbackbuffersareswapped
43voidmydisplay(){glClear(GL_COLOR_BUFFER_BIT|….)./*drawgraphicshere*/.glutSwapBuffers()}44Usingtheidlecallback•Th
eidlecallbackisexecutedwhenevertherearenoeventsintheeventqueue-glutIdleFunc(myidle)-Usefulforanimationsvoidmyidle(){/*changesomething*/t+=dtgl
utPostRedisplay();}Voidmydisplay(){glClear();/*drawsomethingthatdependsont*/glutSwapBuffers();}45Usingglobals•TheformofallGL
UTcallbacksisfixed-voidmydisplay()-voidmymouse(GLintbutton,GLintstate,GLintx,GLinty)•Mustuseglobalstopassinformationtocallback
sfloatt;/*global*/voidmydisplay(){/*drawsomethingthatdependsont}