Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Graphics Comp 175 Chapter 2

Similar presentations


Presentation on theme: "Computer Graphics Comp 175 Chapter 2"— Presentation transcript:

1 Computer Graphics Comp 175 Chapter 2
Instructor: Dan Hebert

2 Outline What is OpenGL OpenGL Rendering Pipeline
OpenGL Utility Toolkits OpenGL Coding Framework

3 What is OpenGL OpenGL A graphics rendering API
A software interface to graphics hardware A 3D graphics and modeling library OpenGL is A graphics Rendering API. A software interface to graphics hardware. A 3D graphics and modeling library. OpenGL is a library for doing computer graphics. By using it, you can create interactive applications which render high-quality images composed of 3D geometric objects and images.

4 What is OpenGL OpenGL Window independent Operating system independent
Very fast (a standard to be accelerated) Portable OpenGL is windows independent and operating system independent As such, the part of your application which does rendering is platform independent. However, in order for OpenGL to be able to render, it needs a window to draw into. Generally, this is controlled by the windowing system on whatever platform you’re working on. - Very fast, therefore, be used as a standard to be accelerated Portable It uses algorithms carefully developed and optimized by Silicon Graphics, Inc. (SGI).

5 A History of OpenGL Was SGI’s Iris GL – “Open”GL
“Open” standard allowing for wide range hardware platforms OpenGL v1.0 (1992) OpenGL v1.1 (1995) OpenGL v1.2 (latest) Governed by OpenGL Architecture Review Board (ARB) OpenGL is the premier environment for developing portable, interactive 2D and 3D graphics applications. Since its introduction in 1992, OpenGL has become the industry's most widely used and supported 2D and 3D graphics application programming interface (API), bringing thousands of applications to a wide variety of computer platforms. OpenGL fosters innovation and speeds application development by incorporating a broad set of rendering, texture mapping, special effects, and other powerful visualization functions. Developers can leverage the power of OpenGL across all popular desktop and workstation platforms, ensuring wide application deployment.

6 Advantages Most widely adopted graphics standard Stable
Reliable and portable Evolving Scalable Easy to use Industry standard An independent consortium, the OpenGL Architecture Review Board, guides the OpenGL specification. With broad industry support, OpenGL is the only truly open, vendor-neutral, multiplatform graphics standard. Stable OpenGL implementations have been available for more than seven years on a wide variety of platforms. Additions to the specification are well controlled, and proposed updates are announced in time for developers to adopt changes. Backward compatibility requirements ensure that existing applications do not become obsolete. Reliable and portable All OpenGL applications produce consistent visual display results on any OpenGL API-compliant hardware, regardless of operating system or windowing system. Evolving Because of its thorough and forward-looking design, OpenGL allows new hardware innovations to be accessible through the API via the OpenGL extension mechanism. In this way, innovations appear in the API in a timely fashion, letting application developers and hardware vendors incorporate new features into their normal product release cycles. Scalable OpenGL API-based applications can run on systems ranging from consumer electronics to PCs, workstations, and supercomputers. As a result, applications can scale to any class of machine that the developer chooses to target. Easy to use OpenGL is well structured with an intuitive design and logical commands. Efficient OpenGL routines typically result in applications with fewer lines of code than those that make up programs generated using other graphics libraries or packages. In addition, OpenGL drivers encapsulate information about the underlying hardware, freeing the application developer from having to design for specific hardware features. Well-documented Numerous books have been published about OpenGL, and a great deal of sample code is readily available, making information about OpenGL inexpensive and easy to obtain

7 Outline What is OpenGL OpenGL Rendering Pipeline
OpenGL Utility Toolkits OpenGL Coding Framework

8 OpenGL Pipelines There are two paths of data flow
Pixel-based, image primitives pipeline. Geometric, vertex-based primitives pipeline. Texturing combines the two types of primitives together.

9 OpenGL Architecture There are two pipelines of data flow.
The upper pipeline is for pixel-based, image primitives. The lower pipeline is for geometric, vertex-based primitives. Texturing combines the two types of primitives together.

10 + = OpenGL Rendering Rendering Geometric Primitives Frame Buffer
Image Primitives + =

11 How it Works? Draw something… • How to draw… Geometric primitives
points, lines and polygons Image Primitives Images, bitmaps • How to draw… State control colors, materials, light sources, etc. OpenGL has two types of things that it can render: geometric primitives and image primitives. Geometric primitives are points, lines and polygons. Image primitives are bitmaps and graphics images (i.e. the pixels that you might extract from a JPEG image after you’ve read it into your program.) Additionally, OpenGL links image and geometric primitives together using texture mapping.

12 OpenGL is Not a Language
It is a Graphics Rendering API Whenever we say that a program is OpenGL-based or OpenGL applications, we mean that it is written in some programming language (such as C/C++) that makes calls to one or more of OpenGL libraries.

13 Window Management OpenGL is window and operating system independent.
OpenGL does not include any functions for window management, user interaction, and file I/O. Host environment is responsible for window management.

14 Outline What is OpenGL OpenGL Rendering Pipeline
OpenGL Utility Toolkits OpenGL Coding Framework

15 Window Management API We need additional libraries to handle window managements. GLX/AGL/WGL glue between OpenGL and windowing systems GLUT AUX OpenGL Utility Toolkits As mentioned, OpenGL is window and operating system independent. To integrate it into various window systems, additional libraries are used to modify a native window into an OpenGL capable window. Every window system has its own unique library and functions to do this. Some examples are: • GLX for the X Windows system, common on Unix platforms • AGL for the Apple Macintosh • WGL for Microsoft Windows Finally to simplify programming and window system dependence, we’ll be using the freeware library, GLUT. GLUT, written by Mark Kilgard, is a public domain window system independent toolkit for making simple OpenGL applications. It simplifies the process of creating windows, working with events in the window system and handling animation.

16 OpenGL API Hierarchy • GL: the “core” library of OpenGL that is platform independent GLX: for the X Windows system, common on Unix platforms • AGL: for the Apple Macintosh • WGL: for Microsoft Windows GLUT, AUX: auxiliary libraries that handle window creation, OS system calls (mouse buttons, movement, keyboard, etc), callbacks. OpenGL also includes a utility library, GLU, to simplify common tasks such as: rendering quadric surfaces (i.e. spheres, cones, cylinders, etc. ), working with NURBS and curves, and concave polygon tessellation. The above diagram illustrates the relationships of the various libraries and window system components. Generally, applications which require more user interface support will use a library designed to support those types of features (i.e. buttons, menu and scroll bars, etc.) such as Motif or the Win32 API. Prototype applications, or one which don’t require all the bells and whistles of a full GUI, may choose to use GLUT instead because of its simplified programming model and window system independence.

17 OpenGL Division of Labor
“core” library of OpenGL that is platform independent. GLU an auxiliary library that handles a variety of graphics accessory functions. GLUT/AUX utility toolkits that handle window managements

18 Libraries and Headers Note Header File Library File Library Name
window managements glut.h glaux.h glut32.lib (PC) -lglut (UNIX) glaux.lib (PC) -lglaux (UNIX) Utility toolkits handles a variety of accessory functions glu.h glu32.lib (PC) -lglu Auxiliary library “core” library gl.h opengl32.lib (PC) -lgl (UNIX) OpenGL Note Header File Library File Library Name All of our discussions today will be presented in the C computer language. For C, there are a few required elements which an application must do: • Header files describe all of the function calls, their parameters and defined constant values to the compiler. OpenGL has header files for GL (the core library), GLU (the utility library), and GLUT (windowing toolkit). Note: glut.h includes gl.h and glu.h. On Microsoft Windows, including only glut.h is recommended to avoid warnings about redefining Windows macros. • Libraries are the operating system dependent implementation of OpenGL on the system you’re using. Each operating system has its own set of libraries. For Unix systems, the OpenGL library is commonly named libGL.so and for Microsoft Windows, it’s named opengl32.lib. All are presented in the C language

19 Outline What is OpenGL OpenGL Rendering Pipeline
OpenGL Utility Toolkits OpenGL Coding Framework

20 Learning OpenGL with GLUT
GLUT is a Window Manager (handles window creation, user interaction, callbacks, etc). Platform Independent. Makes it easy to learn and write OpenGL programs without being distracted by your environment.

21 Environment Setup All of our discussions will be presented in C/C++ language Use GLUT library for window managements Files needed gl.h, glu.h, glut.h opengl32.lib, glu32.lib, glut32.lib

22 Usage Include the necessary header files in your code
#include <GL/gl.h> // “core”, the only thing is required #include <GL/glu.h> // handles accessory functions #include <GL/glut.h> // handles window managements void main( int argc, char **argv ) { ….. } Only the “core” library (opengl32.lib, gl.h) are required Only the “core” library (opengl32.lib, gl.h) are required

23 Usage Link the necessary Libraries to your code Link GL library
Link opengl32.lib (PC), or -lgl (UNIX) Link GLU library Link glu32.lib (PC), or -lglu (UNIX) Link GLUT library Link glut32.lib (PC), or -lglut (UNIX) Only the “core” library (opengl32.lib, gl.h) are required

24 OpenGL Data Types To make it easier to port OpenGL code from one platform to another, OpenGL defines its own data types that map to normal C data types. To make it easier to port OpenGL code from one platform to another, OpenGL defines its own data types. These data types map to normal C data types that you can use instead. To simplify platform independence for OpenGL programs, a complete set of data types are defined. Use them to simplify transferring your programs to other operating systems. GLshort A[10]; short A[10]; GLdouble B; double B;

25 OpenGL Data Types As C Type Representation OpenGL Data Type
unsigned char 8-bit unsigned integer GLubyte, GLboolean double 64-bit float GLdouble float 32-bit float GLfloat long 32-bit integer GLint, GLsizei short 16-bit integer GLshort unsigned long 32-bit unsigned integer GLunit, GLenum, GLbitfield unsigned short 16-bit unsigned short GLushort signed char 8-bit integer GLbyte As C Type Representation OpenGL Data Type

26 OpenGL Function Naming
OpenGL functions all follow a naming convention that tells you which library the function is from, and how many and what type of arguments that the function takes. <Library prefix><Root command><Argument count><Argument type>

27 OpenGL Function Naming
glColor3f(…) gl library Root command, # of arguments, type of arguments gl means OpenGL glu means GLU glut means GLUT f: the argument is float type i: the argument is integer type v: the argument requires a vector

28 Basic GLUT Coding Framework
Configure GL and GLUT stuff Open window, Display mode, …… Initialize OpenGL state background color, light, View positions, …… Register callback functions Render, Interaction (keyboard, mouse), …… Event processing loop glutMainLoop() Here’s the basic structure that we’ll be using in our applications. This is generally what you’d do in your own OpenGL applications. The steps are: 1) Choose the type of window that you need for your application and initialize it. 2) Initialize any OpenGL state that you don’t need to change every frame of your program. This might include things like the background color, light positions and texture maps. 3) Register the callback functions that you’ll need. Callbacks are routines you write that GLUT calls when a certain sequence of events occurs, like the window needing to be refreshed, or the user moving the mouse. The most important callback function is the one to render your scene, which we’ll discuss in a few slides. 4) Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.

29 A Sample Program void main (int argc, char **argv) {
glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutCreateWindow (“My First Program"); myinit (); glutDisplayFunc ( display ); glutReshapeFunc ( resize ); glutKeyboardFunc ( key ); glutMainLoop (); } Here’s an example of the main part of a GLUT based OpenGL application. This is the model that we’ll use for most of our programs in the course. The glutInitDisplayMode() and glutCreateWindow() functions compose the window configuration step. We then call the myinit() routine, which contains our one-time initialization. Here we initialize any OpenGL state and other program variables that we might need to use during our program that remain constant throughout the program’s execution. Next, we register the callback routines that we’re going to use during our program. Finally, we enter the event processing loop, which interprets events and calls our respective callback routines.

30 Initializing and Creating Window
void main (int argc, char **argv) { glutInit (&argc, argv); // GLUT initialization glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // display model glutInitWindowSize (500, 500); // window size glutCreateWindow (“My First Program"); // create window …… } glutInit(…) initializes the GLUT library. Should be called before any other GLUT routine. glutInitDisplayMode(…) specifies display mode (RGB, RGBA, color-index), and display buffer (single or double) glutInitWindowSize(…) specifies window size. glutCreateWindow(…) create window

31 GLUT Initializing Functions
Standard GLUT initialization glutInit (int argc, char ** argv) Display model glutInitDisplayMode (unsigned int mode) Window size and position glutInitWindowSize (int width, int height) glutInitWindowPosition(int x, int y) Create window glutCreateWindow (char *name); glutInit(…) initializes the GLUT library. Should be called before any other GLUT routine. glutInitDisplayMode(…) specifies display mode (RGB, RGBA, color-index), and display buffer (single or double) glutInitWindowSize(…) specifies window size. glutCreateWindow(…) create window

32 Initializing OpenGL State
Set up whatever state you’re going to use void myinit(void) { glClearColor(1.0, 1.0, 1.0, 1.0); // background color glColor3f(1.0, 0.0, 0.0); // line color glMatrixMode(GL_PROJECTION); // following set up viewing glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); } Set up whatever state you’re going to use Here’s the internals of the initialization routine, myinit(). Over the course, you’ll learn what each of the above OpenGL calls do.

33 Callback Functions Callback Function
Routine to call when something happens. e.g. window resize, redraw, user input, etc. GLUT uses a callback mechanism to do its event processing. GLUT uses a callback mechanism to do its event processing. Callbacks simplify event processing for the application developer. As compared to more traditional event driven programming, where the author must receive and process each event, and call whatever actions are necessary, callbacks simplify the process by defining what actions are supported, and automatically handling the user events. All the author must do is fill in what should happen when.

34 GLUT Callback Functions
Contents of window need to be refreshed glutDisplayFunc() Window is resized or moved glutReshapeFunc() Key action glutKeyboardFunc() Mouse button action glutMouseFunc() Mouse moves while a button is pressed glutMotionFunc() Mouse moves regardless of mouse button state glutPassiveMouseFunc() Called when nothing else is going on glutIdleFunc() GLUT supports many different callback actions, including: • glutDisplayFunc() - called when pixels in the window need to be refreshed. • glutReshapeFunc() - called when the window changes size • glutKeyboardFunc() - called when a key is struck on the keyboard • glutMouseFunc() - called when the user presses a mouse button on the mouse • glutMotionFunc() - called when the user moves the mouse while a mouse button is pressed • glutPassiveMouseFunc() - called when the mouse is moved regardless of mouse button state • glutIdleFunc() - a callback function called when nothing else is going on. Very useful for animations.

35 Register GLUT Callback Functions
void main (int argc, char **argv) { …… glutDisplayFunc ( display ); // display callback glutReshapeFunc ( resize ); // window resize callback glutKeyboardFunc ( key ); // keyboard callback } • glutDisplayFunc() - called when pixels in the window need to be refreshed. • glutReshapeFunc() - called when the window changes size • glutKeyboardFunc() - called when a key is struck on the keyboard

36 Rendering Callback It’s here that all OpenGL rendering is done
void display( void ) { typedef GLfloat point2[2]; point2 vertices[3]={{0.0, 0.0}, {250.0, 500.0}, {500.0, 0.0}}; int i, j, k; int rand(); glClear(GL_COLOR_BUFFER_BIT); for( k=0; k<5000; k++) …… } One of the most important callbacks is the glutDisplayFunc() callback. This callback is called when the window needs to be refreshed. It’s here that you’d do all of your OpenGL rendering.

37 Window Resize Callback
It’s called when the window is resized or moved void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); …… display(); } One of the most important callbacks is the glutDisplayFunc() callback. This callback is called when the window needs to be refreshed. It’s here that you’d do all of your OpenGL rendering.

38 Keyboard Input Callback
It’s called when a key is struck on the keyboard void key( char mkey, int x, int y ) { switch( mkey ) case ‘q’ : exit( EXIT_SUCCESS ); break; …… } Above is a simple example of a user input callback. In this case, the routine was registered to receive keyboard input. GLUT supports user input through a number of devices including the keyboard, mouse, dial and button boxes and spaceballs.

39 Event Process Loop This is where your application receives events, and schedules when callback functions are called void main (int argc, char **argv) { …… glutMainLoop(); } Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.

40 Demonstration glutmech1 teapot1 gears

41 Graphics Programming OpenGL API

42 Outline OpenGL API Geometric Primitives Color Model
Managing OpenGL’s State Transformations

43 Graphics System User Program Graphics System I/O Device Graphics API
Function calls Output User Program Graphics System I/O Device Data Input Graphics API

44 Graphics API Primitive functions Attribute functions Viewing functions
Transformation functions Input functions Control functions

45 OpenGL Division GL “core” library of OpenGL that is platform independent. GLU an auxiliary library that handles a variety of graphics accessory functions. GLUT utility toolkit that handles window management

46 OpenGL Graphics Functions
Primitives A point, line, polygon, bitmap, or image. Transformation Rotation, size, perspective in 3D coordinate space. Color mode RGB, RGBA, Color index. Materials lighting and shading Accurately compute the color of any point given the material properties. Buffering Double buffering, Z-buffering, Accumulation buffer. Texture mapping ……

47 Outline OpenGL API Geometric Primitives Color Model
Managing OpenGL’s State Transformations

48 Vertex Vertex (point): a location in the space.
Use vertices to define the geometric objects that are recognized by graphics system. 2D could be treated as the subset of 3D with z = 0 (x, y) (x, y, z) P = x y z

49 OpenGL Geometric Primitives
All geometric primitives are specified by vertices GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_QUADS GL_TRIANGLES GL_POLYGON GL_TRIANGLE_FAN

50 Geometry Commands glEnd (void) glVertex*(…)
glBegin(GLenum type) marks the beginning of a vertex-data list that describes a geometric primitives. glEnd (void) marks the end of a vertex-data list. glVertex*(…) specifies vertex for describing a geometric object.

51 OpenGL Geometric Primitives
GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_POLYGON GL_TRANGLES GL_QUADS GL_TRANGLE_STRIP GL_QUAD_STRIP GL_TRANGLE_FAN OpenGL organizes vertices into primitives based upon which type is passed into glBegin(). The possible types are: GL_POINTS GL_LINE_STRIP GL_LINES GL_LINE_LOOP GL_POLYGON GL_TRIANGLE_STRIP GL_TRIANGLES GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP

52 OpenGL Function Naming

53 Specifying Geometric Primitives
glBegin( type ); glVertex*(…); …… glEnd(); OpenGL organizes vertices into primitives based upon which type is passed into glBegin(). The possible types are: GL_POINTS GL_LINE_STRIP GL_LINES GL_LINE_LOOP GL_POLYGON GL_TRIANGLE_STRIP GL_TRIANGLES GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP type determines how vertices are combined

54 Example void drawSquare (GLfloat *color) { glColor3fv ( color );
glBegin(GL_POLYGON); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glVertex2f ( 1.1, 1.1 ); glVertex2f ( 0.0, 1.0 ); glEnd(); } The drawSquare(…) routine causes OpenGL to render a single square in a single color. The square is planar, since the z value is automatically set to 0.0 by glVertex2f().

55 Demonstration (code) Principles of rendering geometry
look at Chapter2 and shapes tutor GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_POLYGON GL_QUADS GL_TRIANGLES GL_TRIANGLE_FAN

56 Problems for Chapter 2 program
Move point to 400, 400 and make larger Make line go from bottom right to upper left Double size of triangle and change to green Add two more points to polygon and change to red Change quad to a square

57 Demonstration (look at drawing primitives code)

58 Problems Draw a checkerboard Draw a house
4x4 squares Alternating green and red squares Each square is 50x50 pixels Draw a house 1 door 2 windows 1 floor Use Chpt2Simple in MyProjects for Visual C++ workspace

59 Primitives and Attributes
Draw something… Geometric primitives points, lines and polygons • How to draw… Attributes colors, lighting, shading, texturing, etc. OpenGL has two types of things that it can render: geometric primitives and image primitives. Geometric primitives are points, lines and polygons. Image primitives are bitmaps and graphics images (i.e. the pixels that you might extract from a JPEG image after you’ve read it into your program.) Additionally, OpenGL links image and geometric primitives together using texture mapping.

60 Other Simple OpenGL Attributes
glClearColor(1.0, 1.0, 1.0, 1.0); Sets background color to white Fourth argument is transparency; 0.0 is opaque Sets a state variable glPointSize(2.0); Sets point size to be 2 pixels wide Note that this is not a device-independent attribute glLinewidth (2.0); glLineStipple(Glint factor, Glushort pattern);

61 Attributes An attribute is any property that determines how a geometric primitives is to be rendered. Each time, OpenGL processes a vertex, it uses data stored in its internal attribute tables to determine how the vertex should be transformed, rendered or any of OpenGL’s other modes.

62 Example glPointSize(3.0); glShadeModel(GL_SMOOTH); glBegin(GL_LINE);
glColor4f(1.0, 1.0, 1.0, 1.0); glVertex2f(5.0, 5.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(25.0, 5.0); glEnd();

63 Outline OpenGL API Geometric Primitives Color Model
Managing OpenGL’s State Transformations

64 OpenGL Color Model There are two color models in OpenGL
RGB Color (True Color) Indexed Color (Color map) The type of window color model is requested from the windowing system. OpenGL has no command to control. Every OpenGL implementation must support rendering in both RGBA mode, ( sometimes described as TrueColor mode ) and color index ( or colormap ) mode. For RGBA rendering, vertex colors are specified using the glColor*() call. For color index rendering, the vertex’s index is specified with glIndex*(). The type of window color model is requested from the windowing system. Using GLUT, the glutInitDisplayMode() call is used to specify either an RGBA window ( using GLUT_RGBA ), or a color indexed window ( using GLUT_INDEX ).

65 RGB Color R, G, B components are stored for each pixel.
With RGB mode, each pixel’s color is independent of each other.

66 RGB Color Red Green Blue

67 How Many Colors? Color number = For example: 4-bit color = 16 colors
= million colors

68 How Much Memory? Buffer size = width * height *color depth
For example: If width = 640, height = 480, color depth = 24 bits Buffer size = 640 * 480 * 24 = 921,600 bytes If width = 640, height = 480, color depth = 32 bits Buffer size = 640 * 480 * 32 = 1,228,800 bytes

69 Alpha Component Alpha value A value indicating the pixels opacity
Zero usually represents totally transparent (invisible) and the maximum value represents completely opaque. Alpha buffer Hold the alpha value for every pixel Alpha values are commonly represented in 8 bits, in which case transparent to opaque ranges from 0 to 255.

70 RGB Color Commands glClearColor(r, g, b, a) glutInitDisplayMode(mode)
glColor*(…) specifies vertex colors. glClearColor(r, g, b, a) sets current color for cleaning color buffer. glutInitDisplayMode(mode) specify either an RGBA window (GLUT_RGBA ), or a color indexed window (GLUT_INDEX ).

71 Example glutInitDisplayMode (GLUT_RGBA);
glClearColor(1.0, 1.0, 1.0, 1.0); void drawLine (GLfloat *color) { glColor3fv ( color ); glBegin(GL_LINE); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glEnd(); }

72 Indexed Color Historically, color-index mode was important because it required less memory Use Color-map (lookup table) With color-index mode, each pixel with same index stored in its bit-planes shares the same color-map location

73 Color Lookup Table Index … 187 Blue 123 120 Green Red 1 … 253 254 255
Blue 123 120 Green Red 1 253 254 255 8 bits 8 bits 8 bits

74 RGBA vs. Color Index Mode
Color index model Index 187 B 123 120 G R 1 2 254 255 RGBA model 255 8 bits 8 bits 8 bits

75 Color Index Commands glClearIndex(Glfloat index)
glIndex*(…) specifies vertex colors glClearIndex(Glfloat index) sets current color for cleaning color buffer. glutSetColor(int color, GLfloat r, GLfloat g, GLfloat b ) sets the entries in a color table for window.

76 Shading Model Red Green Blue (0, 0, 0) Black (255, 255, 255) White
(128, 128, 128) Gray

77 Shading Model A triangle in RGB color space Smooth shading in OpenGL
Red Green Blue A triangle in RGB color space Smooth shading in OpenGL

78 Shading Model Commands
glShadeModel(mode) set the shading mode. The mode parameter can be GL_SMOOTH (the default) or GL_FLAT. Flat shading: the color of one particular vertex of an independent primitive is duplicated across all the primitive’s vertices to render that primitive. Smooth shading: the color at each vertex is treated individually. The colors of interior pixels are interpolated.

79 Demonstration (look at code)
Principles of specifying colors - programs\cube

80 Problem Change the cube program to render using a flat shading model
glShadeModel (GL_FLAT)

81 Outline OpenGL API Geometric Primitives Color Model
Managing OpenGL’s State Transformations

82 OpenGL’s State Machine
In OpenGL, all rendering attributes are encapsulated in the OpenGL State rendering styles color shading lighting texture mapping Each time OpenGL processes a vertex, it uses data stored in its internal state tables to determine how the vertex should be transformed, lit, textured or any of OpenGL’s other modes.

83 OpenGL’s State Management
Setting Vertex Attributes glPointSize(...) point size glLineWidth(…) line width glColor*(…) color glNormal*(…) normal glTexCoord*(…) texturing Controlling State Functions glEnable(…) glDisable(…) Attributes Setting OpenGL state usually includes modifying the rendering attribute, such as loading a texture map, or setting the line width. Also for some state changes, setting the OpenGL state also enables that feature ( like setting the point size or line width ). Other features need to be turned on. This is done using glEnable(), and passing the token for the feature, like GL_LIGHTING or GL_POLYGON_STIPPLE.

84 Controlling State Functions
OpenGL has many states and state variables can be changed to control rendering. Ex. GL_LIGHTING GL_DEPTH_TEST GL_SHADE_MODEL GL_LINE_STIPPLE ……

85 Controlling State Functions
By default, most of the states are initially inactive. These states can be turn on/off by using: glEnable (Glenum state) turn on a state. glDisable (Glenum state) turn off a state.

86 Example glEnable(GL_LIGHTING); glShadeModel(GL_SMOOTH);
glBegin(GL_LINE); glColor3f(1.0, 1.0, 1.0); glVertex2f(5.0, 5.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(25.0, 5.0); glEnd(); glDisable(GL_LIGHTING);

87 Outline OpenGL API Geometric Primitives Color Model
Managing OpenGL’s State Transformations

88 Transformations Transformations make possible the projection of 3D objects onto 2D screen. The graphics transformation process is analogous to taking a photograph with a camera. Every transformation can be thought of as changing the representation of a vertex from one coordinate system to another. Transformations are used both by the applications programmer to move and orient objects (either statically or dynamically) and by OpenGL to implement the viewing pipeline. Three transformations (model-view, perspective, texture) are part of the state. Their matrices can be set by application programs but the operations are carried out within the viewing pipeline.

89 Synthetic Camera Model
This model has become know as the synthetic camera model. Note that both the objects to be viewed and the camera are three-dimensional while the resulting image is two dimensional.

90 Camera Analogy The graphics transformation process is analogous to taking a photograph with a camera. Note that human vision and a camera lens have cone-shaped viewing volumes. OpenGL (and almost all computer graphics APIs) describe a pyramid-shaped viewing volume. Therefore, the computer will “see” differently from the natural viewpoints, especially along the edges of viewing volumes. This is particularly pronounced for wide-angle “fish-eye” camera lenses.

91 Transformations and Camera Analogy
Viewing transformation positioning and aiming camera in the world. Modeling transformation Position and moving the model Projection transformation adjust the lens of the camera Viewport transformation enlarge or reduce the physical photograph

92 Coordinate Transformation
Every graphics transformation can be thought of as changing the representation of a vertex from one coordinate system to another. Every transformation can be thought of as changing the representation of a vertex from one coordinate system to another.

93 Transformations and Coordinate Systems
Viewing transformation specify camera (camera coordinates) Modeling transformation specify geometry (world coordinates) Projection transformation project (window coordinates) Viewport transformation map to screen (screen coordinates) Every transformation can be thought of as changing the representation of a vertex from one coordinate system or frame to another. Thus, initially vertices are specified in world or application coordinates. However, to view them, OpenGL must convert these representations to ones in the reference system of the camera. This change of representations is described by a transformation matrix (the model-view matrix). Similarly, the projection matrix converts from camera coordinates to window coordinates.

94 Transformation in OpenGL
Transformations are specified by matrix operations. Desired transformation can be obtained by a sequence of simple transformations that can be concatenated together. Transformation matrix is usually represented by 4x4 matrix. Provides matrix stacks for each type of supported matrix to store matrices. More on this in Chpt 4 (rotation, translation, scaling) OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices. Matrix stacks are used because it is more efficient to save and restore matrices than to calculate and multiply new matrices. Popping a matrix stack can be said to “jump back” to a previous location or orientation.

95 OpenGL Transformation Pipeline
OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices. Matrix stacks are used because it is more efficient to save and restore matrices than to calculate and multiply new matrices. Popping a matrix stack can be said to “jump back” to a previous location or orientation. The depth of matrix stacks are implementation-dependent, but the Modelview matrix stack is guaranteed to be at least 32 matrices deep, and the Projection matrix stack is guaranteed to be at least 2 matrices deep. The material-to-color, flat-shading, and clipping calculations take place after the Modelview matrix calculations, but before the Projection matrix. The polygon culling and rendering mode operations take place after the Viewport operations. There is also a texture matrix stack, which is outside the scope of this course. It is an advanced texture mapping topic.

96 Viewing Viewing Volume Projection (Orthographic or Parallel)
Viewpoint Transformation

97 Define Coordinate System
+X +Z +Y In the default position, the camera is at the origin, looking down the negative z-axis In the default position, the camera is at the origin, looking down the negative z-axis If you get this wrong, you may see nothing in your image.

98 OpenGL and Windows Screen
Positive X Y Windows Screen Mapping (50, 50) (0, 0) Positive X Y OpenGL Screen Mapping (50, 50) (0, 0) Remember: the Y coordinates of OpenGL screen is the opposite of Windows screen. But same as in the XWindows system.

99 Viewing Volume Near-plane Far-plane Viewing volume

100 Orthographic Projection
Vertexes of an object are projected towards infinity Points projected outside view volume are clipped out Distance does not change the apparent size of an object Vertexes of an object are projected towards infinity Points projected outside view volume are clipped out Distance does not change the apparent size of an object Clipped out Image

101 Orthographic Viewing Volume
Clipped out top left right Default orthographic viewing volume is a 2x2x2 cube, with the original in the center. In term of the our 2D plane, the bottom-left corner is at (-1.0, -1.0), and the upper-right corner is at (1.0, 1.0). Bottom Near-plane Far-plane Viewing rectangle Viewing volume

102 Orthographic Projection Commands
glOrtho( left, right, bottom, top, zNear, zFar ) Creates a matrix for an orthographic viewing volume and multiplies the current matrix by it. gluOrtho2D( left, right, bottom, top ) Creates a matrix for projecting 2D coordinates onto the screen and multiplies the current matrix by it. For glOrtho(), the viewing volume is shaped like a rectangular parallelepiped (a box). Vertexes of an object are “projected” towards infinity. Distance does not change the apparent size of an object. Orthographic projection is used for drafting and design (such as blueprints). calls glOrtho with z values near zero

103 General-Purpose Transformation Commands
glMatrixMode(mode) Specified what transformation matrix is modified. mode: GL_MODELVIEW GL_PROJECTION glLoadMatrix*() replaces the matrix on the top of the current matrix stack. glMultMatrix*(), post-multiples the matrix on the top of the current matrix stack. The matrix argument is a column-major 4 x 4 double or single precision floating point matrix.

104 General-Purpose Transformation Commands
glLoadIdentity( void ) Set the currently modifiable matrix to the 4x4 identity matrix.

105 Orthographic Projection Example
glMatrixMode(GL_PROJECTION) glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); This sequence defines a 500x500 viewing rectangle with the lower-left corner of the rectangle at the origin of the 2D system. It then switches the matrix mode back to model-view mode. It is a good idea, in complex programs, always to return to a given matrix mode, in this case mode-view mode, to avoid problems caused by your losing track of which matrix mode the program is in at a given time. This example defines a 500x500 viewing rectangle with the lower-left corner of the rectangle at the origin of the 2D system.

106 Viewpoint Viewpoint the region within the window that will be used for drawing the clipping area. by default, it is set to the entire rectangle of the window that is opened. Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window. Viewpoint the region within the window that will be used for drawing the clipping area. by default, it is set to the entire rectangle of the window that is opened. Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window.

107 Viewpoint Transformation
h w h w glViewport() clips the vertex or raster position. For geometric primitives, a new vertex may be created. For raster primitives, the raster position is completely clipped. A viewpoint is defined as the same size as the window A viewpoint is defined as half the size of the window

108 Aspect Ratio The Aspect Ratio of a rectangle is the ratio of the rectangle’s width to its height: e.g. Aspect Ratio = width/height Viewport aspect ratio should be same as projection transformation, or resulting image may be distorted.

109 Viewpoint Commands glViewport( x, y, width, height ) Define a pixel rectangle in the window into which the final image is mapped. (x, y) specifies the lower-left corner of the viewport. (width, height) specifies the size of the viewport rectangle.

110 Put Things Together Geometry Commands State Control Commands
glBegin, glEnd, glVertex State Control Commands glutInitDisplayMode, glEnable, glDisable, glColor, Orthographic Projection Commands glOrtho, gluOrtho2D, glMatrixMode, glLoadIdentity Viewpoint Commands glViewport What we learn today Geometry Commands glBegin, glEnd, glVertex State Control Commands glutInitDisplayMode, glEnable, glDisable, glColor, Orthographic Projection Commands glOrtho, gluOrtho2D, glMatrixMode, glLoadIdentity Viewpoint Commands glViewport

111 Demonstration (look at code)

112 Sierpinski Gasket Source Code: Slide 1
#include <glut.h> void myinit(void) { /* attributes */ glClearColor(1.0, 1.0, 1.0, 0.0); /* white background */ glColor3f(1.0, 0.0, 0.0); /* draw in red */ /* set up viewing */ /* 500 x 500 window with origin lower left */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); }

113 Sierpinski Gasket Source Code: Slide 2
void display( void ) { /* define a point data type */ typedef GLfloat point2[2]; point2 vertices[3]={{0.0,0.0},{250.0,500.0},{500.0,0.0}}; /* A triangle */ int i, j, k; long rand(); /* standard random number generator */ point2 p ={100.0,100.0}; /* An srbitrary initial point */ glClear(GL_COLOR_BUFFER_BIT); /*clear the window */

114 Sierpinski Gasket Source Code: Slide 3
/* computes and plots 5000 new points */ for( k=0; k<5000; k++) { j=rand()%3; /* pick a vertex at random */ /* Compute point halfway between vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.0; p[1] = (p[1]+vertices[j][1])/2.0; /* plot new point */ glBegin(GL_POINTS); glVertex2fv(p); glEnd(); } glFlush(); /* clear buffers */

115 Sierpinski Gasket Source Code: Slide 4
void main(int argc, char** argv) { /* Standard GLUT initialization */ glutInit(&argc,argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); /* default, not needed */ glutInitWindowSize(500,500); /* 500 x 500 pixel window */ glutInitWindowPosition(0,0); /* place window top left on display */ glutCreateWindow("Sierpinski Gasket"); /* window title */ glutDisplayFunc(display); /* display callback invoked when window opened */ myinit(); /* set attributes */ glutMainLoop(); /* enter event loop */ }

116 Homework Assignment Draw a 2-dimensional object containing at least one of each of the OpenGL Geometric Primitives discussed in this chapter GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_POLYGON GL_TRANGLES GL_QUADS GL_TRANGLE_STRIP GL_QUAD_STRIP GL_TRANGLE_FAN Make the 2-dimensional object interesting Instructions will be on web in a few days Due February 7 at start of class


Download ppt "Computer Graphics Comp 175 Chapter 2"

Similar presentations


Ads by Google