Download presentation
Presentation is loading. Please wait.
1
CSC8820 Advanced Graphics Algorithms
Lecture 3 and 4 OpenGL Overview, Geometry Objects, User Interaction
2
OpenGL Files OpenGL files comes with MS Windows and/or Visual Studio installation Header files gl.h, glu.h Glut.h (needs to be downloaded) Static libraries Opengl32.lib, glu32.lib glut32.lib (needs to be downloaded) DLLs C:\windows\system32 Opengl32.dll, glu32.dll glut32.dll (needs to be downloaded)
3
How to compile OpenGL/GLUT programs?
4
Sample OpenGL programs
Examples from “OpenGL Programming Guide” OpenGL code samples: Simple code samples:
5
A Simple OpenGL Program (1)
#include <GL/glut.h> void display(void) { /* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); /* draw white polygon (rectangle) with corners at * (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) */ glColor3f (1.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3f (0.25, 0.25, 0.0); glVertex3f (0.75, 0.25, 0.0); glVertex3f (0.75, 0.75, 0.0); glVertex3f (0.25, 0.75, 0.0); glEnd();
6
A Simple OpenGL Program (2)
/* start processing buffered OpenGL routines */ glFlush (); } void init (void) { /* select clearing color */ glClearColor (0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
7
A Simple OpenGL Program (3)
/* Declare initial window size, position, and display mode (single buffer and RGBA). Open window with "hello" in its title bar. Call initialization routines. Register callback function to display graphics. Enter main loop and process events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (250, 250); glutInitWindowPosition (100, 100); glutCreateWindow ("hello"); init (); glutDisplayFunc(display); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
8
What is graphics rendering pipeline?
A process of generating a 2D image, given a virtual camera (eye), 3D objects, light sources, textures, etc. The 2D image is a frame of animation. A process for converting coordinates from its local 3D coordinate system to the final 2D window coordinate system. Both OpenGL and Direct3D implement part of the rendering pipeline.
9
Graphics Rendering Pipeline Stages
The rendering pipeline is normally divided into 3 conceptual stages Application Geometry Rasterizer The output of one stage is the input of next stage, thus the name “pipeline” Each stage also contains sub-stages Application Geometry Rasterizer
10
OpenGL pipeline (overview)
11
OpenGL pipeline (overview)
Application Rasterizer Geometry
12
OpenGL pipeline (detailed view)
13
Why use pipeline architecture?
It’s more efficient Think automobile assembly line Explore data parallelism Data parallelism vs. instruction parallelism The pipeline architecture is the fundamental architecture for both 3D graphics software and hardware Think GPU as an image assembly line
14
Application Stage Overview
3D objects are created using modeling tools 3D Studio Max, Maya, etc. 3D objects are positioned in 3D world and organized in a scene graph 3D objects can be moved by transformation Transformation are performed on vertices using different types of transformation matrices 3D transformations are specified in this stage but carried out in the Geometry stage
15
Application Stage Overview
Other tasks in the application stage: Handling user input level of details occlusion culling The result: the 3D geometry objects to be fed to the next stage Points, lines, polygons, etc. 3D geometry objects are eventually broken down to vertices, represented by (x, y, z) coordinates
16
Geometry Stage Overview
Responsible for the majority of per-polygon or per vertex operations Contains several sub-stages Model Transformation View Transformation (often combined with model transformation) Lighting Projection Clipping Screen Mapping
17
Coordinate Systems Multiple Cartesian coordinate systems are used at different stages of the pipeline 3D Model Coordinates (model space) Each model is in its own coordinate system with origin in some point on the model 3D World Coordinates (world space) Unified world coordinate system, with only one origin 3D Eye Coordinates (view space) Camera (eye) is the origin and look straight down Z-axis 2D Screen Coordinates (screen space) 3D coordinates are converted to 2D screen coordinates for display
18
3D Graphics Pipeline Data Flow
Objects in the 3D scene are sequentially transformed through different coordinate systems when proceeding the 3D pipeline.
19
Model Transform Transform the vertices and normals of 3D objects from model space to world space After the transform, all objects exit in the same coordinate system The camera (eye) has a location in world coordinate system and a direction
20
View Transform The camera and all the 3D objects are transformed with the view transform The purpose is to place the camera at the origin and make it look in the direction of Z-axis. Often combined with model transform – model-view transform
21
Projection Transform the view volume into a unit cube with its extreme points at (-1, -1, -1) and (1, 1, 1). The purpose is to simplify clipping. Two projection methods: Orthographic projection When realism is not a concern. Perspective projection When realism counts.
22
Lighting A lighting equation is used to calculate a color at each vertex of the 3D object that is to be affected by lighting. The lighting equations often have little to do with how lights behave in the real world. Per-vertex lighting vs. per-pixel lighting
23
Shading Each 3D object surface is divided into many triangles.
The colors at the vertices of a triangle are interpolated over the triangle. Three shading methods: Flat shading (operate per triangle) Gouraud Shading (operate per vertex) Phong Shading (operate per pixel) Programmable Shaders
24
Clipping Only the primitives wholly or partially inside the view volume need to be passed on to the rasterizer stage. Primitives (line or polygon) that are partially inside the view volume require clipping.
25
Screen Mapping Primitives that survive the clipping are passed on to screen mapping stage. X and Y coordinates of each primitive are transformed to screen coordinates. Z coordinates are not affected and are kept for depth buffer checking.
26
Rasterizer Stage Overview
In this stage, all primitives are converted into pixels in the window. The goal of this stage is to assign correct colors to the pixels. It contains one or all of the following sub-stages: Texture mapping Fog Translucency Test Depth buffering Antialiasing
27
Rasterization
28
Texturing Texture mapping means “attaching” an image onto a 3D object.
Textures are important to bringing realism to a 3D scene. Provide surface details Add scene depth Advance texture mapping Multi-texturing Bump mapping Environment mapping Pixel shader
29
Fog An optional stage but help set the mood
Also helps give a scene an addition sense of depth of field Added realism E.g. allow distant objects to gracefully "fade away" rather than just pop out of the scene
30
Translucency Tests Also called Alpha Test
Used to create effects such as glass, water, see-through views in CAD modeling, and translucent or transparent materials.
31
Depth Buffering Also called Z-buffer algorithm
Used for visibility check When multiple primitives are rendered to a certain pixel, the color of the pixel is the color of the primitive that is closest to the point of view of camera. The only exception is when primitives are transparent. This algorithm allows the primitives to be rendered in any order.
32
Anti-aliasing Alias effect: the jagged or stair-stepped look of diagonal or curved lines in computer graphics. Anti-aliasing algorithms sample, or examine and evaluate, the colors and shades of pixels adjoining curved or diagonal lines to present smoother looking line.
33
Display Finally, the final 2D image is generated and rendered to frame buffer and displayed on screen. Double-buffer technique may be used to reduce flashing Front buffer for display, back buffer for rendering next frame. A long trip down the graphics rendering pipeline If application runs at 60 frame/second, this whole process will repeat every 17 ms.
34
Summary The 3D graphics pipeline is the underlying tool for graphics rendering. Three major stages: Application Geometry Rasterizer
35
Readings “ExtremeTech 3D Pipeline Tutorial” at
36
Overview of OpenGL An open standard specification defining a cross platform API for writing 2D or 3D computer graphics applications Defines over 250 function calls Competes with Direct3D Managed by an industry consortium (Khronos Group)
37
Notable OpenGL games Doom 3 Half-Life Quake Call of Duty Second Life
Spore Unreal Tournament
38
Notable OpenGL applications
Blender Adobe Photoshop Adobe After Effects Adobe Premiere
39
OpenGL pipeline
40
Purposes of OpenGL Hide the complexities of interfacing with different 3D graphics hardware Hide the differing capabilities of hardware platforms, by requiring that all implementations support the full OpenGL feature set
41
OpenGL OpenGL's basic operation is to accept primitives such as points, lines and polygons, and convert them into pixels. OpenGL is a low-level, procedural API, requiring the programmer to dictate the exact steps required to render a scene. Requires programmers to have a good knowledge of the graphics pipeline,
42
OpenGL Books Red Book: OpenGL Programming Guide
Blue Book: OpenGl Reference Manual Orange Book: OpenGL Shading Language
43
OpenGL Files OpenGL files comes with MS Windows and/or Visual Studio installation Header files gl.h, glu.h Glut.h (needs to be downloaded) Static libraries Opengl32.lib, glu32.lib glut32.lib (needs to be downloaded) DLLs C:\windows\system32 Opengl32.dll, glu32.dll glut32.dll (needs to be downloaded)
44
How to compile OpenGL/GLUT programs?
45
Sample OpenGL programs
Examples from “OpenGL Programming Guide” OpenGL code samples: Simple code samples:
46
A Simple OpenGL Program (1)
#include <GL/glut.h> void display(void) { /* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); /* draw white polygon (rectangle) with corners at * (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) */ glColor3f (1.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3f (0.25, 0.25, 0.0); glVertex3f (0.75, 0.25, 0.0); glVertex3f (0.75, 0.75, 0.0); glVertex3f (0.25, 0.75, 0.0); glEnd();
47
A Simple OpenGL Program (2)
/* start processing buffered OpenGL routines */ glFlush (); } void init (void) { /* select clearing color */ glClearColor (0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
48
A Simple OpenGL Program (3)
/* Declare initial window size, position, and display mode (single buffer and RGBA). Open window with "hello" in its title bar. Call initialization routines. Register callback function to display graphics. Enter main loop and process events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (250, 250); glutInitWindowPosition (100, 100); glutCreateWindow ("hello"); init (); glutDisplayFunc(display); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
49
OpenGL Functions Overview (1)
Primitives: object creation glBegin(), glEnd(); A glBegin()-glEnd() pair encloses an object definition. OpenGL functions called between glBegin() and glEnd() define the object glVertex*(), glColor*(), glNormal*(), glMaterial*(), glCallList(), glCallLists(), glRect*(), gluSphere(), gluCylinder() Attributes glClearColor() and glClear() specify the color to be used when color buffers are cleared and to actually clear the buffer, respectively. Attributes (all are modal) control how primitives are displayed: glPolygonMode(), glPointSize(), glLineStipple(), glLineWidth()
50
Overview of OpenGL Functions (2)
Display lists glNewList(), glEndList(), glGenLists(), glListBase() Display lists are collections of graphics functions. You create them, name them, and "execute" them. You define objects in between glNewList() and glEndList(). Modeling transformations glScale*(), glTranslate*(), glRotate*() Before invoking any matrix manipulating function, you normally call glLoadIdentity(). Remember that glRotate() rotates about the origin so in order to rotate an object you usually must make sure that it is positioned at the origin.
51
OpenGL Functions Overview (3)
Viewing gluLookAt() The viewing transformation must precede modelling transformations in the code: you must first position the camera, then the objects. Projection gluOrtho2D(), glOrtho(), gluPerspective(), glViewport() Call glMatrixMode( GL_PROJECTION) before you change projection parameters with any of the three functions above, then call glMatrixMode( GL_MODELVIEW). When the projection has been applied (whether simple discarding of z or a perspective division) we obtain normalized device coordinates. Finally these are mapped to (a portion of) the screen window. This mapping is specified with
52
OpenGL Functions Overview (4)
States glEnable(), glDisable() Almost everyting in OpenGL is modal, i.e. settings remain in effect until changed (this is true, not only of state variables we set with glEnable(), but also of normals, material properties, and colours). Realism; light and shading glLight*(), glLightModel*(), glMaterial*(), glShadeModel() You must enable (with glEnable()) both lighting and the light sources you want to use.
53
OpenGL Functions Overview (5)
Hierarchical Models glPushAttrib(), glPopAttrib(), glPushMatrix(), glPopMatrix() In order to build hierarchical models we need ways of storing and restoring attributes and matrices. Display lists often start by pushing and ends by popping. 2D Texture & pixels glTexImage2D(), glBindTexture(), glTexCoord2*(), glRasterPos*(), glBitmap(), glDrawPixels() Texturing must be enabled explicitly.
54
GLUT Functions Overview (1)
Input and other callback functions OpenGL programs execute in event mode, i.e. loops forever while awaiting user input. We write callback functions to be invoked as a result of user interaction. GLUT automatically calls the functions if we have registered them. glutDisplayFunc(), glutMouseFunc(), glutMotionFunc(), glutReshapeFunc(), glutKeyboardFunc(), glutIdleFunc(), glutPostRedisplay()
55
GLUT Functions Overview (2)
Control Functions Control functions are functions that interface with the windowing system. You (usually) call them from your main() function. glutInit(), glutInitDisplayMode(), glutInitWindowSize(), glutCreateWindow(), glutMainLoop()
56
How to learn OpenGL? Read OpenGL Programming Guide
Read sample programs! There are tons of OpenGL programs online: Read tutorials Write programs
57
How to learn OpenGL? Bookmark the OpenGL manual pages
You need this more than anything else Bookmark the GLUT manual page If you are really serious about learning OpenGL, read OpenGL specification
58
Other OpenGL Resources
OpenGL tutor Tutorial programs that demonstrate basic OpenGL functionality by allowing the user to modify the parameters of a function and see the effect on the scene OpenGL FAQ & Troubleshooting Guide A good OpenGL tutorial
59
Outline Graphics primitives in OpenGL
Input devices and user interaction GLUT Programming event-driven input Animating interactive programs
60
Coordinate systems Each point and vector is defined in reference to a coordinate system Once we fix the origin of the coordinate system, we can represent all points unambiguously The same point may have different 3D coordinates in different coordinate systems Remember that part of the job of 3D graphics pipeline is to convert vertices from model space to 2D window space Each vertex with go through several coordinate systems along the pipeline
61
Coordinate systems A 3D coordinate system is defined by its three base vectors (x, y, and z axis) Get familiar with OpenGL’s coordinate system
62
Graphics primitives In computer graphics, we work with 3D models (geometry objects) 3D objects are described by their surfaces Can be thought of as being hollow Complex 3D objects either are composed of or can be approximated by flat convex polygons Curved surfaces are approximated by flat polygons Polygons can be specified through a set of 3D vertices
63
Graphics primitives The basic graphics primitives are points, lines, and polygons A polygon can be defined by an ordered set of vertices Graphics hardware is optimized for processing points and flat polygons Complex objects are eventually divided into triangular polygons (a process called tessellation) Because triangular polygons are always flat
64
Graphics primitives The basic geometric primitives can be described using three fundamental types: Scalars, points, and vectors Point: a location in the 3D space E.g. vertex, pixel Scalars: real numbers E.g. distance between two points Vector: direction or directed line segment No fixed position in 3D space E.g. surface normal, light direction, camera direction
65
Graphics Primitives In OpenGL, all geometry is specified by stating which type of object and then giving the vertices that define it glBegin(…), glEnd() glVertex[34][fdv] Three or four components (regular or homogeneous) Float, double or vector (eg float[3])
66
Graphics primitives in OpenGL
Example: triangle glBegin(GL_POLYGON); glVertex2f(0.0, 0.0); glVertex2f(0.0, 3.0); glVertex2f(3.0, 3.0); glVertex2f(4.0, 1.5); glVertex2f(3.0, 0.0); glEnd(); Other options: glBegin(GL_POINTS), glBegin(GL_LINES), glBegin(GL_POLYGONS), glBegin(GL_QUADS), etc.
67
Graphics Primitives in OpenGL
68
Graphics primitives in OpenGL
How to represent points and vector in OpenGL? Use array. Example GLfloat normals[][3] = {{0.0, 0.0, -1.0}, {0.0, 1.0, 0.0}, {-1.0, 0.0, 0.0}}; GLfloat light0_pos[4] = {0.9, 0.9, 2.25, 0.0};
69
Vertex Arrays and Display Lists
How to display large numbers of polygons efficiently? Vertex arrays (“Red Book”, Chapter 2) Display lists (“Red Book”, Chapter 7)
70
Vertex Arrays Why use vertex arrays?
Performance concern: OpenGL requires many function calls to render geometric primitives Redundant processing of vertices: many vertices are shared between adjacent polygons Vertex arrays allow you to specify lots of vertex-related data with just a few arrays Use few OpenGL function calls E.g. 20 vertices in a 20 sided polygon: one array and one function call
71
Vertex Arrays There are 3 steps to use vertex arrays
Activate up to 8 arrays Each storing a different type of data: coordinates, normals, colors, texture coordinates, etc. glEnableClientState(…) Specifying data for the arrays Specify a pointer E.g. glVertexPointer(…), glTexCoordPointer(…), etc.
72
Vertex Arrays Draw geometry with the data
Can obtain data from a single array element, from an ordered list of array elements, or from a sequence of array elements E.g. glArrayElement(), glDrawElements(), glDrawArrays(), etc.
73
Vertex Arrays “Red Book”, Example 2-10 glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glColorPointer(3, GL_FLOAT, 0, colors); glVertexPointer(2, GL_INT, 0, vertices); glBegin(GL_TRIANGLES); glArrayElement(2); glArrayElement(3); glArrayElement(5); glEnd();
74
Display Lists Originally developed to take advantage of X Window’s client/server model Still useful on PC May improve performance of your OpenGL program A display list stores a group of OpenGL commands so that they can be used repeatedly just by calling the display list name. Display lists are usually optimized and store on graphics card
75
Immediate vs. Retained mode
“Immediate mode” rendering 3D primitives are rendered immediately when they are specified, without storing in a data structure Immediate mode is the default mode in OpenGL Sufficient for small programs “Retained” mode rendering 3D objects are stored in a data structure (e.g. display list) and rendered later Lots of opportunities for performance optimization Display list is a simple form of retained rendering Large scale 3D applications use scene graph
76
Why display lists are efficient?
When you create a display list, the OpenGL commands within are "precompiled“, optimized by graphics driver, and usually stored in the graphics card memory Can reuse the pre-calculated result rather than perform the same operations (e.g. matrix multiplications) repeatedly Get data from graphics memory instead of main memory (similar idea to Texture Object) Therefore, the execution of a display list is generally faster than the execution of the commands contained in it. E.g. A simple application with roughly 36,000 polygons, no texturing or lighting, running on a PIII at 450 Mhz and a GeForce with 32MB DDR: 153 fps (with DL) vs 55 fps (without DL)
77
Display List Example GLuint listName = glGenLists(1); // get a new name glNewList(listName, GL_COMPILE); // generate list glTranslatef(1.5, 0.0, 0.0); glColor3f(1.0, 0.0, 1.0); glBegin(GL_TRIANGLES); glVertex3f(0.0, 0.0, 0.0); … glEnd(); glEndList(); glCallList(listName); // draw one
78
When to use display list?
Encapsulate sequences of transformations (matrix operations) If the transformations don’t change from frame to frame Raster bitmaps and images (e.g. fonts) Lights, materials properties, and lighting models Put material definitions in display lists See teapots.c for example
79
Display list } 3 matrix multiplications per frame Display() { …
glTranslatef(…); glRotatef(…); Draw_something(); } 3 matrix multiplications per frame Init() { glNewList(1, GL_COMPILE); glTranslatef(…); glRotatef(…); Draw_something(); glEndlist(); } Display() { glCallList(1); … 1 matrix multiplication per frame
80
When not to use display lists?
For texture images, use texture objects instead of display lists Very small lists may not perform well since there are some overhead when executing a list It may not be worth it to use display lists for objects with less than several hundreds of polygons.
81
When not to use display lists?
Remember you cannot change the parameters in a display list once it’s created and its content cannot be read Only use the OpenGL calls with constant parameters in the display list If you use a variable in a display list, then the value at the time of creation is stored. Subsequent changes to that variable won’t affect display list E.g. if you want to use keyboard to translate an object, don’t put that glTranslatef() in display list
82
Vertex Arrays vs. Display Lists
Use vertex arrays if the properties of your geometry primitives will be changed at run time E.g. the color or texture may change from frame to frame Use display lists if the properties of your geometry primitives will NOT be changed at run time You may still move the geometry primitives defined in display lists
83
Vertex Arrays vs. Display Lists
Use vertex arrays for dynamic objects Use display lists of static objects Read the following code examples at list.c, torus.c, teapots.c
84
How to develop GUI for 3D applications?
Many game companies develop their own GUI library on Windows Relatively few people use .NET For cross platform GUI GLUT (for very simple GUI), FLTK ( Qt GTK WxWidgets ( open source, cross-platform GUI API Crazy Eddie’s GUI System ( Designed for games, works great with OGRE
85
Examples from Crazy Eddie’s GUI
86
GLUT window management
GLUT provides some window management functions: glutCreateWindow, glutDestroyWindow glutPostRedisplay glutSwapBuffers glutPositionWindow, glutReshapeWindow glutFullScreen glutShowWindow, glutHideWindow, etc. See for details
87
GLUT menu management GLUT provides simple menu management functions
glutCreateMenu glutSetMenu, glutGetMenu glutDestroyMenu glutAddMenuEntry glutAddSubMenu glutAttachMenu, glutDetachMenu, etc. See for details
88
GLUT Menu Example 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);
89
How to read from input devices?
Keyboard/mouse: use GLUT, DirectX, X Window, etc. Joystick: DirectX, X Window Unconventional input devices: write program that directly talks to device drivers, or use commercial tools
90
Input Modes Input devices contain a trigger which can be used to send a signal to the operating system Button on mouse Pressing or releasing a key When triggered, input devices return information (their measure) to the system Mouse returns position information Keyboard returns ASCII code
91
Request Mode Input provided to program only when user triggers the device Typical of keyboard input Can erase (backspace), edit, correct until enter (return) key (the trigger) is depressed
92
Event Mode Most systems have more than one input device, each of which can be triggered at an arbitrary time by a user Each trigger generates an event whose measure is put in an event queue which can be examined by the user program
93
Event Types Window: resize, expose, iconify
Mouse: click one or more buttons Motion: move mouse Keyboard: press or release a key Idle: nonevent Define what should be done if no other event is in queue
94
Callbacks Programming interface for event-driven input
Define a callback function for each type of event the graphics system recognizes This user-supplied function is executed when the event occurs GLUT example: glutMouseFunc(mymouse) mouse callback function
95
GLUT callbacks GLUT recognizes a subset of the events recognized by any particular window system (Windows, X Window, Macintosh) Can register callback functions to handle those events glutDisplayFunc glutMouseFunc glutReshapeFunc glutKeyFunc glutIdleFunc glutMotionFunc, glutPassiveMotionFunc See for details
96
GLUT Event Loop glutMainLoop();
Remember that the last line in main.c for a program using GLUT must be glutMainLoop(); which puts the program in an infinite event loop In each pass through the event loop, GLUT looks at the events in the queue for each event in the queue, GLUT executes the appropriate callback function if one is defined if no callback is defined for the event, the event is ignored
97
The display callback The display callback is executed whenever GLUT determines that the window should be refreshed, for example When the window is first opened When the window is reshaped When a window is exposed When the user program decides it wants to change the display In main.c glutDisplayFunc(mydisplay) identifies the function to be executed Every GLUT program must have a display callback
98
Posting redisplays Many events may invoke the display callback function Can lead to multiple executions of the display callback on a single pass through the event loop We can avoid this problem by instead using glutPostRedisplay(); which sets a flag. GLUT checks to see if the flag is set at the end of the event loop If set then the display callback function is executed
99
Animation = Redraw + Swap
When we redraw the display through the display callback, we usually start by clearing the window with glClear()and then draw the next frame Instead of one color buffer, we use two Front Buffer: one that is displayed but not written to Back Buffer: one that is written to but not altered
100
Animation = Redraw + Swap
Program then requests a double buffer in main.c glutInitDisplayMode(GL_RGB | GL_DOUBLE) At the end of the display callback buffers are swapped void mydisplay() { glClear() /* draw graphics here */ glutSwapBuffers() }
101
Use idle callback for animation
The idle callback is executed whenever there are no events in the event queue glutIdleFunc(myidle) Useful for automatic animations. For example: void myidle() { /* change something */ t += dt glutPostRedisplay(); } Void mydisplay() { glClear(); /* draw something that depends on t */ glutSwapBuffers();
102
Use idle callback for animation
void main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(320,320); glutCreateWindow(""); glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutReshapeFunc(changeSize); glEnable(GL_DEPTH_TEST); glutMainLoop(); }
103
Use idle callback for animation
// A triangle is automatically rotated void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(angle,0.0,1.0,0.0); glBegin(GL_TRIANGLES); glVertex3f(-0.5,-0.5,0.0); glVertex3f(0.5,0.0,0.0); glVertex3f(0.0,0.5,0.0); glEnd(); glPopMatrix(); glutSwapBuffers(); // Increase the angle for the next frame angle++; } See for details.
104
A Simple OpenGL Program (1)
#include <GL/glut.h> void display(void) { /* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); /* draw white polygon (rectangle) with corners at * (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) */ glColor3f (1.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3f (0.25, 0.25, 0.0); glVertex3f (0.75, 0.25, 0.0); glVertex3f (0.75, 0.75, 0.0); glVertex3f (0.25, 0.75, 0.0); glEnd();
105
A Simple OpenGL Program (2)
/* start processing buffered OpenGL routines */ glFlush (); } void init (void) { /* select clearing color */ glClearColor (0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
106
A Simple OpenGL Program (3)
/* Declare initial window size, position, and display mode (single buffer and RGBA). Open window with "hello" in its title bar. Call initialization routines. Register callback function to display graphics. Enter main loop and process events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (250, 250); glutInitWindowPosition (100, 100); glutCreateWindow ("hello"); init (); glutDisplayFunc(display); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
107
Readings OpenGL Programming Guide OpenGL Programming Guide v1.1
Chapter 2 and 7 OpenGL Programming Guide v1.1
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.