Upload
harold-fears
View
214
Download
1
Embed Size (px)
Citation preview
Questions about Graphics Pipeline
1. What is graphics pipeline?
2. What coordinate systems and transformations are involved in graphics pipeline?
3. What is graphics primitive?
Give three examples of possible primitives.
CP411 Computer Graphics 1
CP411 Computer Graphics 2
1. OpenGL architecture– How OpenGL work– Exam the OpenGL implementation
2. OpenGL and interactive graphics– Mouse pointing– Menu– Keyboard
3. Graphics storage– Bitmap– Compressed storage
Lecture 4
CP411 Computer Graphics 3
• Execution sequenceglutMainLoop() picks up a <window creation> event from the queue, creates the
window, and calls display(). When the button of the window is clicked, a <stop> event is inserted in the queue. When this event is processed, the execution terminates
main()
start
glutMainLoop()
init(); glutDisplayFunc(lineSegment);
glutInit();
Event Queue
Functions that specify a new window
lineSegment()
Clicking button
stop
CP411 Computer Graphics 4
• glutMainLoop() is the function that drives the major operations in all our graphics programs. The function iterates indefinitely. In each iteration, it checks whether there are any events in a queue. If yes, it removes and processes the first event. It terminates the execution of the program when a <stop> event is processed.
• Events include windows event, and that of input devices, and drawing
Event QueueExtract an event
Process the eventEvent insertion:Window creation, moving, maximizing, closing, etc.
CP411 Computer Graphics 5
2. OpenGL event register functions
• OpenGL program is an even driven type of program• Events are registered by register functions
glutDisplayFunc (lineSegment);glutReshapeFunc(reshape)glutMouseFunc(MouseButton);// register the mouseglutMotionFunc(MouseMotion);glutKeyboardFunc(curveDrawing);glutSpecialFunc(specialKey);…
• Some event register function corresponds to a special procedure which has certain arguments for getting parameters from the event
CP411 Computer Graphics 6
What happens after the program starts?
1. main: find GL visual and create window 2. initialize GL states (e.g. viewing, color, lighting) 3. initialize display lists 4. loop
1. check for events (and process them) 2. if window event (window moved, exposed, etc.) 3. modify viewport, if needed 4. redraw 5. else if mouse or keyboard 6. do something, e.g., change states and redraw 7. redraw:
• clear screen (to background color) • change state(s), if needed • render some graphics • change more states • render some more graphics • swap buffers
CP411 Computer Graphics 7
3. What happens when a render function is invoked?
• This is when a core OpenGL program starts. • OpenGL program works like statement machine, it does the
graphic pipeline according the current states setting
• State variables specify information such as line width, line stipple pattern, color, shading method, polygon culling, etc . . .
• Each state variable has a default value. The values of the state variables, whether set by default or by the programmer, remain in effect until changed.
• "On" and "Off" State Variables glEnable(GLenum capability) and glDisable(GLenum capability)
CP411 Computer Graphics 8
• Mode State Variables– Mode state variables require commands specific to
the state variable being accessed in order to change its value. One example of this is the command to set the shading mode state variable, GL_SHADE_MODEL.
glShadeModel(GLenum mode) where mode is either GL_SMOOTH for smooth shading or GL_FLAT for flat shading, the default
• Value State Variables– Value state variables require commands specific to
the state variable being accessed in order to change it value.
CP411 Computer Graphics 9
– ColorglColor3f (1.0, 0.0, 0.0);
– Point Size– To control the size of a rendered point use the
command glPointSize(GLfloat size)
– Line Width To control the width of lines use the command
glLineWidth(GLfloat width)
– Stippled LinesTo make stippled (dotted or dashed) lines, the stipple
pattern must be defined using the command glLineStipple(GLint factor, GLushort pattern)
CP411 Computer Graphics 10
4. openGL matrix stack• Matrix is used for transformations from MC to DC
• The openGL matrix stack is a powerful construct. A stack is a last-in-first out structure. – The commands for this are glPushMatrix() and glPopMatrix().
Every point that is drawn will be mulitipled by whatever is on the matrix stack
– Command glLoadIdentity() initializes matrix stack by putting the identity matrix into the current top of the stack
– glMatrixMode() specifies which matrix stack is being altered
– glTranslate and glRotate also place matrices on stack that cause translations and rotations
CP411 Computer Graphics 11
Matrix Manipulation
• Each of these postmultiplies the current matrix– E.g., if current matrix is C, then C=CS– The current matrix is either the modelview matrix or the projection matrix, or a texture matrix
– Set these with glMatrixMode()glMatrixMode(GL_MODELVIEW);glMatrixMode(GL_PROJECTION);
CP411 Computer Graphics 12
Modeling Transforms
• OpenGL provides several commands for performing modeling transforms:– glTranslate{fd}(x, y, z)
• Creates a matrix T that transforms an object by translating (moving) it by the specified x, y, and z values
– glRotate{fd}(angle, x, y, z)• Creates a matrix R that transforms an object by rotating it
counterclockwise angle degrees about the vector {x, y, z}– glScale{fd}(x, y, z)
• Creates a matrix S that scales an object by the specified factors in the x, y, and z directions
CP411 Computer Graphics 13
• OpenGL basically just renders vertices– Vertices can be grouped to form polygons– Polygons can be grouped to form shapes (solids)
• Each glVertex rendered by OpenGL is transformed by the top matrix on the MODELVIEW matrix stack– As we saw before, a matrix corresponding to a CCW rotation of
90 degrees could be put on the stack
• Every vertex rendered by an OpenGL camera is also multiplied by the top matrix on the PROJECTION matrix– The projection matrix controls such effects as:
• Field of view• Perspective vs. Orthographic• Clipping planes• Viewing frustum
CP411 Computer Graphics 14
5. OpenGL routines to draw primitivesvoid lineSegment (void){ glClear (GL_COLOR_BUFFER_BIT);
// Clear display window.
glColor3f (0.0, 0.0, 1.0);// Set line segment color to red.
glBegin (GL_LINES);
glVertex2i (180, 15); // Specify line-segment geometry. glVertex2i (10, 145); glEnd ( );
glFlush ( ); // Clean buffers, make the processing routines fast
}
CP411 Computer Graphics 15
• Function names indicate argument type and number– Functions ending with f take floats– Functions ending with i take ints– Functions ending with b take bytes– Functions ending with ub take unsigned bytes– Functions that end with v take an array.– Examples
glColor3f() takes 3 floats
glColor4fv() takes an array of 4 floats
CP411 Computer Graphics 16
Specifying Geometry• Simple case first: object vertices already in world
coordinates• Geometry in OpenGL consists of a list of vertices in
between calls to glBegin() and glEnd()A simple example: telling GL to render a triangle
glBegin (GL_POLYGON); glVertex2i (80, 10); glVertex2i (30, 100); glVertex2i (120, 50); glEnd ( );
– Usage: glBegin(geomtype) where geomtype is:points, lines, polygons, triangles, quadrilaterals, etc...
CP411 Computer Graphics 17
void display() {
glClear( GL_COLOR_BUFFER_BIT); // Clear the frame buffer
glColor3f( 0.0, 1.0, 0.0); // Set current color to green
glBegin( GL_POLYGON); // Draw the triangle glVertex2f( -0.7, -0.7);
glVertex2f( 0.7, -0.7); glVertex2f( 0, 0.7); glEnd();
glFlush(); // Force to display the new drawings immediately}
CP411 Computer Graphics 18
Triangle Strips
• An OpenGL triangle strip primitive reduces this redundancy by sharing vertices:glBegin(GL_TRIANGLE_STRIP);
glVertex3fv(v0);glVertex3fv(v1);glVertex3fv(v2);glVertex3fv(v3);glVertex3fv(v4);glVertex3fv(v5);
glEnd();
• Drawing rectangle
glRecti(40, 40, 260, 130);// draw a rectangle with filled color
How to draw a rectangle with out fill color?Just outline
v0v2
v1v3
v4
v5
CP411 Computer Graphics 19
Draw a filled circle#include <math.h> const float DEG2RAD = 3.14159/180; void drawCircle(float radius, float x, float y){ glBegin(GL_LINE_LOOP); for (int i=0; i < 360; i++) { float degInRad = i*DEG2RAD; glVertex2f(x+cos(degInRad)*radius, y+sin(degInRad)*radius); } glEnd
}
CP411 Computer Graphics 20
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
// Set display-window color to white.
glMatrixMode (GL_PROJECTION);
// Set transformation mode
glLoadIdentity(); // set current matrix to identity
gluOrtho2D (0.0, 100.0, 0.0, 150.0); // Set projection parameters.
}
• Usually, we need another function, init(), that specifies permanent features of the drawings. This function is invoked only once in the beginning.
CP411 Computer Graphics, graphics file formats 21
Graphics File Formats
• Two methods of representing images:– Geometric representation => vector file format– Raster representation => raster file format
• Examples of vector file formats– ps (postscript), eps, pdf– SVG (Scalable Vector Graphics) has been introduced for the
Internet. This promises to make web sites better, as images can then be scaled to suit various screen resolutions.
• Examples of raster file format– Bitmap, GIF, JPG, PNG
PostScript
• known for its use as a page description language in the electronic and desktop publishing areas.– a dynamically typed concatenative programming language – created by John Warnock and Charles Geschke in 1982.
• Example of ps file%!PS
%% Example 1
newpath
100 200 moveto
200 250 lineto
100 300 lineto
2 setlinewidth
stroke
showpage
CP411 Computer Graphics, graphics file formats 22
The graphics
Example of SVG<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="100" y="90" width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"/>
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="1" fill="red"/>
<circle cx="100" cy="230" r="40" style="fill:rgb(0,255,0);stroke-width:1;stroke:rgb(0,0,0)"/>
</svg>
Save the above as test.xml and open it by Firefox
CP411 Computer Graphics, graphics file formats 23
CP411 Computer Graphics, graphics file formats 24
BitmapBitmap format is historic but still commonly
used. .bmp
A BMP file consists of either 3 or 4 parts as shown in the diagram on the right.
– The first part is a header– This is followed by a information section– If the image is indexed colour then the
palette follows
• Data structureBITMAPFILEHEADER bmfh;BITMAPINFOHEADER bmih;RGBQUAD aColors[];BYTE aBitmapBits[];
CP411 Computer Graphics, graphics file formats 25
The BITMAPFILEHEADER:
start size name stdvalue purpose1 2 bfType 19778 must always be set to 'BM' to declae3 4 bfSize ?? specifies the size of the file in bytes.7 2 bfReserved1 0 must always be set to zero.9 2 bfReserved2 0 must always be set to zero.11 4 bfOffBits 1078 offset from beginning of the file to
data
CP411 Computer Graphics, graphics file formats 26
The BITMAPINFOHEADERstart size name stdvalue purpose15 4 biSize 40 specifies the size of the
INFOHEADER19 4 biWidth 100 specifies the width in pixels.23 4 biHeight 100 specifies the height in pixels.27 2 biPlanes 1 specifies the number of planes29 2 biBitCount 8 specifies the number of bits per
pixel.31 4 biCompression 0 Specifies the type of compression35 4 biSizeImage 0
Specifies he size of the image data, in bytes. If there is no compression, it is valid to set this member to zero.
39 4 biXPelsPerMeter 0 specifies the the horizontal pixels per meter on the designated targer device, usually set to zero.
43 4 biYPelsPerMeter 0 specifies the the vertical pixels per meter on the designated targer device, usually set to zero.
47 4 biClrUsed 0 specifies the number of colors used in the bitmap, if set to zero the number of colors is calculated using the biBitCount member.
51 4 biClrImportant 0 specifies the number of color that are 'important' for the bitmap, if set to zero, all colors are important.
CP411 Computer Graphics, graphics file formats 27
The RGBQUAD array
start size name stdvalue purpose
1 1 rgbBlue - specifies the blue part of the color.
2 1 rgbGreen - specifies the green part of the color.
3 1 rgbRed - specifies the red part of the color.
4 1 rgbReserved - must always be set to zero.
CP411 Computer Graphics, graphics file formats 28
Pixel data
• Pixel data is stored in byte one row after another in stream fashion
• A pixel data can be byte if color palette is used, or three bytes in RGB or BGR order.
• The number bytes in each line of the file should be divided by 4
CP411 Computer Graphics, graphics file formats 29
File header implementation
typedef struct {
unsigned short int type; /* Magic identifier */
unsigned int size; /* File size in bytes */
unsigned short int reserved1, reserved2;
unsigned int offset; /* Offset to image data, bytes */
} HEADER;
CP411 Computer Graphics, graphics file formats 30
Infoheader implementation
typedef struct {
unsigned int size; /* Header size in bytes */
int width,height; /* Width and height of image */
unsigned short int planes; /* Number of colour planes */
unsigned short int bits; /* Bits per pixel */
unsigned int compression; /* Compression type */
unsigned int imagesize; /* Image size in bytes */
int xresolution, yresolution; /* Pixels per meter */
unsigned int ncolours; /* Number of colours */
unsigned int importantcolours; /* Important colours */
} INFOHEADER;
See examples for read and save bitmap with OpenGL
CP411 Computer Graphics, graphics file formats 31
Graphics compression techniques• Run Length Encoding
if there are the same in of some length, then express it as “run length x color value” E.g. RED:GREEN:GREEN:GREEN:GREEN:BLUE -> RED:4xGREEN:BLUE)
• Compress by token– If the same pattern appear many times, then use an
abbreviation for the pattern. – E.g.
(RED:AMBER:GREEN:RED:AMBER:GREEN) -> (LIGHTS:LIGHTS)
where LIGHTS represents RED:AMBER:GREEN
• More efficient coding– Coding Hoffman code: use short code for frequent symbols
CP411 Computer Graphics, graphics file formats 32
Compress rate
• Compress rate = (original file size – compressed file size) / original file size
• Lossless compression– Original bitmap can be recovered
• Lossy compression– Original bitmap can not be recovered
CP411 Computer Graphics, graphics file formats 33
Lossless compressed graphic file formats
• GIF (Graphics Interchange format)– up to 256 colors– uses a token type compression algorithm developed
by Lempel-Ziv-Welch (LZW) patented.– Lossless– Good for headings, buttons, borders, simple diagrams
• PNG (Portable Network Graphics)– it can be used to replace both the GIF and JPG file formats.
– lossless compression
CP411 Computer Graphics, graphics file formats 34
Lossy compression
• Color expression reduction– Change 24 bit color to 16 bit color or 8 bit color
• Mathematical compression– Modern image compression techniques are much more
mathematically intensive, they generally divide the image into small blocks (usually 8 x 8 pixels), then save only as much as is "visually" necessary, by cosin transformation convert from value domain to frequency domain
– Example: JPEG
JPEG (Joint Photographic Experts Group)• The main idea: Use Cosine transformation transfer
each image block into frequency domain, then apply a filter to make high frequency components zero, followed by Hoffman coding to compress.
• Read http://en.wikipedia.org/wiki/JPEG for detail• Lossy, high compression rate
CP411 Computer Graphics, graphics file formats 35
Example testing
1. SVG example in slide 23
2. Examples in Ch.3, Ch.4.
3. Examples in Ch.5, Ch.20 interactive graphics
Try to understand how OpenGL works.
CP411 Computer Graphics 36