Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 10, 11, and 12 Lighting & Shading

Similar presentations


Presentation on theme: "Lecture 10, 11, and 12 Lighting & Shading"— Presentation transcript:

1 Lecture 10, 11, and 12 Lighting & Shading
CSC4820/6820 Computer Graphics Algorithms Ying Zhu Georgia State University Lecture 10, 11, and 12 Lighting & Shading

2 Outline Color Illumination models Light sources
Global illumination model Local illumination model (our focus) Light sources Reflection model & material properties Polygonal shading

3 Coloring vertices We have learned where to draw a vertex on the final 2D image Now we discuss how to set the color for a vertex Different ways to assign color to a vertex Assign color to vertex directly Let OpenGL calculate the vertex color based on its lighting model Write a vertex shader to do lighting your way Use OpenGL extension or pixel shader to do per-pixel lighting Leave it entirely to texture mapping

4 Color When white light is incident on a surface some wavelengths are absorbed and others are reflected. This gives us the perception of the color of the object. When the human eye “sees” something, it is because the reflected light enters the eye and hits a light detector on the retina. In computer graphics, we usually use three colors, called the primary colors, to produce a range of colors called the color gamut.

5 RGB Color Model In the RGB color model, we use red, green, and blue as the 3 primary colors. There are no real three colors that can be combined to give all possible colors. But a good choice of three colors provides a color gamut that covers most colors.

6 Color Index In color-index mode, a single number (called the color index) is stored for each pixel. Each color index indicates an entry in a table that defines a particular set of R, G, and B values. Such a table is called a color map. Color map is usually controlled by window system, not by OpenGL.

7 Color Mode in OpenGL In OpenGL, you choose to use either RGB mode or color-index mode, but not both. Most of the time we use RGB mode. Color-index is useful in some cases: Porting an application that already uses color-index mode. Color map animation: if the contents of an entry in the color map change, then all pixels of that color index change their color.

8 Color Mode in OpenGL Specify display mode:
glutInitDisplayMode(GLUT_RGB|GLUT_DO UBLE); or glutInitDisplayMode(GLUT_INDEX|GLUT_D OUBLE); Cannot be changed after initialization.

9 Directly set color for vertices
Set current color glColor3f(red, green, blue); // for RGB mode glIndexf(index); // for index mode Example glColor3f(1.0, 0.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f(…); glEnd();

10 Directly set color for vertices
Don’t confuse glColor3*()/glColor4*() with glClearColor() glClearColor specifies the red, green, blue, and alpha values used by glClear to clear the color buffers. This is normally the color for background glColor4*() specifies the red, green, blue, and alpha values for the subsequent drawn vertices This is the color for your objects

11 When to set vertex color directly?
When you know exactly what color to use for each vertex When you don’t care about lighting and realism When you don’t have enough information for lighting calculation E.g. you don’t have the surface normals, etc. Without lighting With lighting

12 Use OpenGL lighting model
Normally we use OpenGL lighting model to calculate color for each vertex While lighting is enabled, you can no longer assign color directly to vertices But you can turn on and off lighting in your program as you wish You can enable lighting for some objects and disable lighting for others First, some background about illumination model

13 Main ideas about light Light is a set of little particles (photons) flying around Each photon has a wavelength and an energy When photons hit things they bounce, losing at least some of their energy. When they lose most of the energy, they are “absorbed”. How to model the way photons bounce? The illumination model

14 Illumination Models Illumination: the transport of photons from light source via direct or indirect paths. Illumination models: how light reflects from surfaces and produces what we perceive as color. In general, light leaves some light source, e.g. a lamp or the sun, is reflected from many surfaces and then finally reflected to our eyes

15 Illumination Models shadow multiple reflection translucent surface

16 Illumination Models Local illumination model: a surface point only receives light particles directly from the light source Relatively simple and fast The shading of any surface is independent from the shading of all other surfaces. Not physically correct, but looks OK OpenGL and Direct3D use only local illumination model.

17 Illumination Models Global illumination model: a surface point receives light after the light rays interact with other objects in the scene. Consider light reflected by other surfaces Physically correct, but very expensive E.g. ray tracing, radiosity.

18 Global Illumination Overview
There are several important effects that can not be simulated with a local illumination model: Shadows Refraction and transparency Inter-object reflections A better solution is global illumination. More physically correct and produces more realistic images. Also more computationally expensive than local illumination model.

19 Global Illumination Overview
Main algorithms for global illumination Multi-pass rendering Radiosity (primarily for indoor scenes) Ray tracing This is a brief overview. Details about ray tracing and radiosity will be covered later

20 Multi-pass Rendering Render the same scene multiple times and combining the results. A relatively “cheap” way to fake global illumination. E.g. Quake III engine can do 10 passes on fast systems This is the predominant approach for realistic imagery in real-time applications. Many advanced rendering techniques fall into this category. E.g. shadow, light map, etc.

21 Radiosity Simulate the energy transfer between surface patches at the physical level. The basis of the radiosity rendering algorithm. This is the most accurate method to simulate surface interactions such as between walls inside a building. Very expensive (hours per frame)

22 Ray Tracing Ray tracing is currently the highest quality global illumination algorithm. Many extensions include photon maps (for caustics), sky light, soft shadows, volumetric effects (fog, water) ,etc. Can be very slow (minutes to hours per frame) Real-time ray tracing may be on the way

23 Global Illumination: state-of-the-art
Commercial packages use a combination of multi-pass rendering, radiosity, and ray tracing. Lightwave, Mental Ray, Brazil r/s, etc.

24 Components of Illumination Model
Light sources with following parameters Color Position and direction Directional attenuation Surface properties with following parameters Color (Reflectance Spectrum) Geometry (position, orientation, etc.) Absorption

25 Steps in OpenGL lighting
Now back to local illumination model Steps in OpenGL lighting: Define light sources and select light model Specify light source parameters Enable lighting Enable light sources Specify surface material properties Specify surface normals Not necessarily in these order

26 Steps in OpenGL lighting
We can roughly divide the OpenGL lighting related function calls into three groups: Function calls that turn on/off lighting and light sources Function calls that set light source properties Function calls that set surface material properties How to enable/disable OpenGL lighting? glEnable(GL_LIGHTING) glDisable(GL_LIGHTING)

27 Illumination Models Illumination: the transport of photons from light source via direct or indirect paths. Illumination models: how light reflects from surfaces and produces what we perceive as color. In general, light leaves some light sources, e.g. a lamp or the sun, is reflected from many surfaces and then finally reflected to our eyes

28 Light Sources General light sources are difficult to work with because we must integrate light coming from all points on the source OpenGL uses simple empirical models

29 OpenGL Light Sources Ambient light source (e.g. reflected light)
Same amount of light everywhere in scene No position, no direction, just a constant light value Directional light (e.g. sun) Has a direction but no specific location Point light source (e.g. light bulb) Has a location but light is emitted equally to all directions Spotlight (e.g. headlight) Has a position and light direction is restricted

30 Ambient Light Source Even though an object in a scene is not directly lit, it will still be visible. This is because light is reflected indirectly from nearby objects. Ambient light source models this indirect illumination. Ambient light has no spatial or directional characteristics. The amount of ambient light is a constant for all surfaces in the scene. A very crude way of simulating indirect illumination.

31 Point Light Source The rays emitted from a point light equally to all directions. This is an approximation to a light bulb with Intensity ( ) Position (P) Factors (a, b, c) for light attenuation with distance (d) between P and surface vertex.

32 Directional Light Sources
All of the light rays from a directional light source have a common direction, and no point of origin. Models a point light source at infinity. No attenuation with distance because distance is Commonly used to simulate sunlight.

33 Spot Light Sources Models point light source with direction:
Intensity ( ) Position (P) Direction (D) Factors (a, b, c) for attenuation with distance (d). For normalized vectors D and L, Dot Product

34 Spot Light Sources Spotlights are characterized by a narrow range of angles through which light is emitted Consider spotlight as a light cone with apex at P, direction D, and width defined by an angle Light distribution within the cone is defined by Where approximates the light attenuation along the cone angle

35 Other Light Sources Area light sources Extended light sources
Light source occupies a 2D area (usually a polygon). Extended light sources Spherical light source Elliptical light source Cylindrical light source Volumetric light source These light sources are not implemented in OpenGL This is where you can use shaders

36 Illumination Models Illumination models: how light reflects from surfaces and produces what we perceive as color. In general, light leaves some light source, e.g. a lamp or the sun, is reflected from many surfaces and then finally reflected to our eyes We have discussed light sources. Now we discuss surface material properties

37 Light-Material Interaction
Light-material interactions cause each point to have a different color or shade. Light that strikes an object is partially absorbed and partially scattered (reflected) The amount reflected determines the color and brightness of the object A surface appears red under white light because the red component of the light is reflected and the rest is absorbed The reflected light is scattered in a manner that depends on the smoothness and orientation of the surface

38 Surface Types The smoother a surface, the more reflected light is concentrated in the direction a perfect mirror would reflected the light A very rough surface scatters light in all directions rough surface smooth surface

39 Phong Reflectance Model
A simple reflectance model proposed by Bui-Thong Phong Can be computed rapidly Not physically correct, but the result looks right. Adopted by OpenGL & Direct3D Has four components Diffuse reflection + Specular reflection + Ambient + Emission Thus each light source (except for ambient light) has separate diffuse, specular, and ambient components

40 Phong Reflectance Model
Defines four vectors vertex to light source vector (light vector l) Vertex to eye vector (view vector v) Vertex normal (n) Light reflection vector (r)

41 OpenGL lighting equation
The final result I is a color component This calculation is performed 3 times for R, G, B respectively Calculate for each light source separately and then add them up Diffuse component Ambient component Specular component Emission Distance Term for point/spotlight

42 Diffuse Reflection Assume surface reflects equally in all directions.
An ideal diffuse surface is a very rough surface: e.g. clay. Ideal diffuse reflectors reflect light according to Lambert’s cosine law.

43 Lambert’s Cosine Law Lambert’s law determines how much of the incoming light energy is reflected. Amount of light reflected is proportional to the vertical component of incoming light. reflected light ~cos qi cos qi = l · n if vectors normalized, where l is light vector, n is normal.

44 Diffuse Component Vector dot product : incoming light diffuse intensity (light intensity at the vertex) : diffuse reflection coefficient. n : vertex’s normal. l : normalized vector from vertex to light source

45 Specular Reflection Most surfaces are neither ideal diffusers nor perfectly specular (ideal refectors). Smooth surfaces show specular highlights due to incoming light being reflected in directions concentrated close to the direction of a perfect reflection. E.g. mirrors, metals Specular Highlight

46 Shininess Coefficient
Specular Component Phong proposed using a term that dropped off as the angle between the viewer and the ideal reflection increased V is vertex-to-eye vector, r is light reflection vector Incoming Light’s specular intensity Shininess Coefficient Specular Coefficient

47 The Shininess Coefficient
Values of between 100 and 200 correspond to metals OpenGL only accept value between 0 and 128 Values between 5 and 10 give surface that look like plastic The larger the value, the closer the eye vector has to be to the perfect reflection vector to see the specular highlight This means higher shininess -90 f 90

48 Blinn & Torrance Variation
Uses the halfway vector h between l and v h Vertex normal

49 Blinn & Torrance Variation
By using the halfway vector h, we do not need to compute the reflection vector r at very vertex. Computing h is a lot cheaper. OpenGL implements the Blinn/Torrance variation.

50 Distance Term The light from a point source that reaches a surface is inversely proportional to the square of the distance between them Phong model adds a factor of the form 1/(a + bd +cd2) to the diffuse and specular components. The constant and linear terms soften the effect of the point source.

51 Ambient Component Ambient light is the result of multiple interactions between (large) light sources and the objects in the environment Amount and color depend on both the color of the light(s) and the material properties of the object A very crude approximation of global illumination. May also define a global ambient light term Reflection Coefficient Intensity of Ambient light

52 Putting it all together
The final result I is a color component This calculation is performed 3 times for R, G, B respectively Calculate for each light source (except for ambinet) separately and then add them up Diffuse component Ambient component Specular component Distance Term for point/spot light

53 Multiple Light Sources
Add reflectance components from multiple light sources (repeat for each color components R/G/B)

54 OpenGL lighting Steps in OpenGL lighting:
Define light sources and select light model Specify light source parameters Enable lighting Enable light sources Specify surface material properties Specify surface normals Not necessarily in these order

55 OpenGL lighting We can roughly divide the OpenGL lighting related function calls into three groups: Function calls that turn on/off lighting and light sources Function calls that set light source properties Function calls that set surface material properties

56 Enable/disable lighting in OpenGL
Lighting is disabled by default How to enable/disable OpenGL lighting? glEnable(GL_LIGHTING) glDisable(GL_LIGHTING) Equivalent to turning on/off power

57 OpenGL light sources Internally OpenGL defines several light sources (identified by GL_LIGHT0, GL_LIGHT1, etc.) At least 8 Find out exact number by float num_lights = 0; glGetFloatv(GL_MAX_LIGHTS, &num_lights) To use a light source, you need to configure it and turn it on For example: glEnable(GL_LIGHT2) glDisable(GL_LIGHT2) Equivalent to turning on/off individual light switch

58 Configure OpenGL light sources
Each light source has a number of parameters, each has a initial value You can modify each parameter by calling: void glLightfv( GLenum light, GLenum pname, const GLfloat *params ) light: specify which light source (e.g. GL_LIGHT0) Pname: specify parameter name (e.g. GL_AMBIENT, etc.) Params: specify parameter value

59 Configure OpenGL light sources
Light source parameters: GL_AMBIENT GL_DIFFUSE GL_SPECULAR GL_POSITION GL_SPOT_DIRECTION GL_SPOT_EXPONENT GL_SPOT_CUTOFF GL_CONSTANT_ATTENUATION GL_LINEAR_ATTENUTATION GL_QUADRATIC_ATTENUATION

60 What does glLight*() do?
Directly or indirectly set various parameters in the lighting equation GL_DIFFUSE GL_AMBIENT GL_CONSTANT_ATTENUATION (a), GL_LINEAR_ATTENUATION (b), GL_QUADRATIC_ATTENUATION (c)

61 What does glLight*() do?
Directly or indirectly set various parameters in the lighting equation GL_POSITION, GL_SPOT_DIRECTION GL_SPOT_EXPONENT GL_SPOT_CUTOFF GL_SPECULAR,

62 Example: Configure a point light source
GL float diffuse0[]={1.0, 0.0, 0.0, 1.0}; GL float ambient0[]={1.0, 0.0, 0.0, 1.0}; GL float specular0[]={1.0, 0.0, 0.0, 1.0}; Glfloat light0_pos[]={1.0, 2.0, 3,0, 1.0}; glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightv(GL_LIGHT0, GL_POSITION, light0_pos); glLightv(GL_LIGHT0, GL_AMBIENT, ambient0); glLightv(GL_LIGHT0, GL_DIFFUSE, diffuse0); glLightv(GL_LIGHT0, GL_SPECULAR, specular0);

63 Specify light position or direction
The source colors are specified in RGBA The position is given in homogeneous coordinates If w =1.0, we are specifying a point light source If w =0.0, we are specifying a directional light source Glfloat light0_pos[]={1.0, 2.0, 3,0, 1.0}; // position Glfloat light1_dir[]={1.0, 2.0, 3,0, 0.0}; // direction

64 Specify Attenuation The coefficients in the distance terms are by default a=1.0 (constant terms), b=c=0.0 (linear and quadratic terms). Change by a= 0.80; glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, a); b = 0.2; glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, b); c = 0.2; glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, C);

65 Configure spotlights f Use glLightv() to set
Direction GL_SPOT_DIRECTION Cutoff GL_SPOT_CUTOFF: maximum spread angle of spot light source Attenuation along spread angle is proportional to Larger spot exponent means a more focused spot light. f -q q GL_SPOT_EXPONENT

66 Lighting calculation for spotlight
The initial value of beta is 0 If you don’t have spotlight in your scene, by default the lighting equation is

67 Global Ambient Light Ambient light depends on color of light sources
A red light in a white room will cause a red ambient term that disappears when the light is turned off OpenGL allows a global ambient term that is often helpful glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient)

68 Configure OpenGL light sources
glLight*() does not explicitly set light source types (ambient, directional, point, spotlight) The type of light source is implied from the parameters Ambient light source if only GL_AMBIENT is specified Directional light source if position is (x, y, z, 0) Point light source if position is (x, y, z, 1) Spotlight source if GL_SPOT_DIRECTION, GL_SPOT_CUTOFF, GL_SPOT_EXPONENT are specified

69 How to move (animate) light sources?
Consider light sources as geometric objects whose positions or directions are affected by the model- view matrix You can transform light source just as other 3D objects Call OpenGL transformation functions first Then call glLightfv (GL_LIGHT0, GL_POSITION, position);

70 Animating light source
This is taken from movelight.c ( void display(void) { GLfloat position[] = { 0.0, 0.0, 1.5, 1.0 }; // initial point light position glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix (); gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glRotated ((GLdouble) spin, 1.0, 0.0, 0.0); // rotate light source glLightfv (GL_LIGHT0, GL_POSITION, position); // a point light source at (0, 0, 1.5) glPopMatrix(); glutSolidTorus (0.275, 0.85, 8, 15); glPopMatrix (); glFlush (); }

71 Surface material properties
In addition to light sources, surface material properties are another important part of the lighting equation OpenGL let you set up the following surface properties for vertices Normal Ambient coefficient Diffuse coefficient Specular coefficient Shininess Emission term

72 Surface material properties
The following circled parts are related to surface material properties Shininess Emission term Normal Ambient coeff. Specular coeff. Diffuse coeff.

73 Normals Set by glNormal*()
In order to use lighting, you need to specify normal for each vertex Set by glNormal*() glNormal3f(x, y, z); glNormal3fv(p); Usually we want to set the normal to have unit length to simplify the vector operations. But vector length can be affected by transformations Note the scale does not preserved length glEnable(GL_NORMALIZE) allows for autonormalization at a performance penalty

74 Dot Product The dot product can be defined for two vectors X and Y by
where is the angle between the vectors and is the norm. It follows immediately that if X is perpendicular to Y.

75 Cross Product The cross product of the two vectors a and b is denoted by a×b (in longhand some mathematicians write a^b to avoid confusion with the letter x); it is defined as: where θ is the measure of the angle between a and b (between 0 and 180 degrees, or between 0 and π if measured in radian), and n is a unit vector perpendicular to both a and b.

76 How to Calculate Cross Product in your program

77 How to Calculate Triangle Normals?
p2 Plane n ·(p - p0 ) = 0 p n = (p2 - p0 ) ×(p1 - p0 ) p1 p0 Cross Product n p1 normalize n  n/ |n| p Note that right-hand rule determines the direction of the normal p2 p0 n

78 How to Calculate Vertex Normals?
For polygonal models, Gouraud proposed that vertex normal be the average of polygon normals around this vertex

79 Normals OpenGL won’t automatically calculate triangle or vertex normals for you You have to explicitly specify normal by calling glNormal*() for each vertex Either the 3D model file contains normal information, or you have to write code to calculate normals Special case: when you call glutSolidTeapot(), etc., internally GLUT library calculates the normal for each vertex

80 How to set material properties in OpenGL?
Material properties are set by glMaterial*(GLenum face, GLenum pname, const GLfloat *params ) Face: specifies which face the material parameter is defined for (e.g. GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK ) Pname: Specifies the material parameter (e.g. GL_DIFFUSE) Params: specifies the material parameter value

81 Front and Back Faces The default is shade only front faces which works correct for convex objects If we set two sided lighting, OpenGL will shaded both sides of a surface Each side can have its own properties which are set by using GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK in glMaterial*() back faces not visible back faces visible

82 Configuring material parameters
In glMaterial*(), you can set following parameters GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_EMISSION, GL_SHININESS GLfloat ambient[] = {0.2, 0.2, 0.2, 1.0}; GLfloat diffuse[] = {1.0, 0.8, 0.0, 1.0}; GLfloat specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat shine = 100.0 glMaterialf(GL_FRONT, GL_AMBIENT, ambient); glMaterialf(GL_FRONT, GL_DIFFUSE, diffuse); glMaterialf(GL_FRONT, GL_SPECULAR, specular); glMaterialf(GL_FRONT, GL_SHININESS, shine);

83 Configuring material parameters using glMaterial*() and glNormal*()
GL_SHININESS GL_EMISSION GL_AMBIENT GL_SPECULAR GL_DIFFUSE

84 Emissive Term We can simulate a light source in OpenGL by giving a material an emissive component This color is unaffected by any sources or transformations GLfloat emission[] = 0.0, 0.3, 0.3, 1.0); glMaterialf(GL_FRONT, GL_EMISSION, emission);

85 Transparency Material properties are specified as RGBA values
The A(lpha) value can be used to make the surface translucent The default is that all surfaces are opaque regardless of A Later we will enable blending and use this feature

86 The lighting process Suppose you have 1 ambient light, 1 directional light, 2 point lights, and 1 spot light in your scene You have set parameters for light sources and surface materials The color for a lighted vertex is calculated in following steps (not necessarily in these order) First calculate for global ambient light source

87 The lighting process (Note that each light source (except for ambient light) has a separate ambient, diffuse, and specular component.) Calculate for directional light source Calculate for point light sources Calculate for each point light and add them up

88 The lighting process Calculate for spotlight source
This is one color component for a lighted vertex Do this for Red, Green, and Blue respectively Note that different light sources can be turned on or off for different objects This means different objects may have different light source combinations, e.g. apply spotlight only to certain objects

89 Phong Illumination Examples
Examples of Phong illumination with different parameters.

90 How does lighting fit into the 3D pipeline?
In OpenGL pipeline, lighting and coloring happens after model-view transformation and before projection transformation Lighting and coloring

91 Polygonal Shading In a typical graphics program, most polygons are filled polygons. We’ve discussed how to calculate color for each vertex. How about those pixels inside the polygon and on the edge? Shading: the process of assigning a color to pixels of a polygon

92 Polygonal Shading Strictly speaking, shading is part of the rasterizer stage Performed during scan conversion and before texture mapping Shading methods: Flat shading Gouraud shading Phong shading (don’t confused with Phong illumination model)

93 Flat Shading For each triangle, obtain color for one vertex through lighting calculation or direct color assignment Then assign every pixel in the triangle with this same color Inexpensive to compute. Appropriate for objects with flat faces. Less pleasant for smooth surfaces. glShadeModel(GL_FLAT) See glShadeModel() man page for details on which vertex is picked (for color calculation) for each triangle

94 Gouraud Shading Three steps
Programmer specifies normal at each polygon (triangle) vertex. OpenGL calculates color at each polygon vertex based on (local) illumination model. OpenGL interpolatse color in polygon interior. More expensive to calculate but generate much better images than flat shading. Supported in OpenGL glShadeModel(GL_SMOOTH)

95 Gouraud Shading For a line, the vertex colors are linearly interpolated along the pixels between the two end vertices. E.g. a line has 5 pixels, and the end point colors are (0,0,0) and (0,0,1), then, after the interpolation, the 5 pixel colors will be (0,0,0), (0,0,1/4), (0,0,2/4), (0,0,3/4), and (0,0,1). Each RGB component is interpolated separately For a polygon, OpenGL first interpolates along the edges, and then along the horizontal scan- lines during scan-conversion.

96 Gouraud shading How to interpolate colors?

97 Gouraud shading vs. flat shading

98 Gouraud shading Main problem with Gouraud shading:
when a specular highlight occurs near the center of a large triangle, it will usually be missed entirely. The result of Gouraud (smooth) shading largely depends on the tessellation density Works well with high polygons density (lots of small polygons) Doesn’t work well with low polygon density (a few large polygons) This problem is fixed by Phong shading

99 Phong Shading Three steps Significantly more expensive
Calculate normal at each polygon vertex Interpolate normals in polygon interior Calculate color at each point using local illumination model based on interpolated normal. Significantly more expensive Not supported in OpenGL But can be implemented using shaders although still not very convenient

100 Phong shading How to interpolate normals?

101 Gouraud vs. Phong shading
If the polygon mesh approximates surfaces with a high curvatures, Phong shading may look smooth while Gouraud shading may show edges Phong shading requires much more work than Gouraud shading You can do that in shader but not very convenient Both need data structures to represent meshes so we can obtain vertex normals

102 Phong vs. Gouraud shading

103 Per-vertex vs. per-pixel lighting
Gouraud shading is a per-vertex lighting model Only use lighting equation on vertices, then interpolate for pixels Only specify normals for vertices Phong shading is a per-pixel lighting model Use lighting equation on every pixel Calculate normal for each pixel Much more realistic Ray tracing and radiosity are also per-pixel lighting models

104 Per-pixel lighting Bump mapping is another, more popular per-pixel lighting technique Specify a normal map which stores normal information for each pixel Calculate lighting for each pixel

105 Bump mapping Can be implemented in a pixel shader
Runs on GPU, very fast Much more realistic, much more details regardless of the polygon size Recent games use more and more bump mapping Per-pixel lighting is the future

106 OpenGL Example /* light.c
* This program demonstrates the use of the OpenGL lighting * model. A sphere is drawn using a grey material characteristic. * A single light source illuminates the object. */ #include <GL/glut.h> /* Initialize material property, light source, lighting model, * and depth buffer.*/ void init(void) { // define surface material parameter values GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 50.0 }; // define a (directional) light source parameter GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };

107 OpenGL Example (2) glClearColor (0.0, 0.0, 0.0, 0.0); // set background color glShadeModel (GL_SMOOTH); // enable Gouraud shading // set surface material parameters glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); // set light source parameters glLightfv(GL_LIGHT0, GL_POSITION, light_position); // turn on lighting and light source glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); }

108 OpenGL Example (3) void display(void) {
// draw background color and clear depth buffer glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw object, normals are calculated/specified by // GLUT library glutSolidSphere (1.0, 20, 16); glFlush (); }

109 OpenGL Example (4) void reshape (int w, int h) {
glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w, 1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0); else glOrtho (-1.5*(GLfloat)w/(GLfloat)h, 1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); }

110 OpenGL Example (5) void keyboard(unsigned char key, int x, int y) {
switch (key) { case 27: exit(0); break; }

111 OpenGL Example (6) int main(int argc, char** argv) {
glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); init (); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; }

112 What does the lighting equation look like?
The default parameters for GL_LIGHT0 are (see glLight*() man page): Ambient: (0, 0, 0, 1), Diffuse: (1, 1, 1, 1), and Specular: (1, 1, 1, 1) The default surface material parameters are (read glMaterial*() man page): Ambient: (0.2, 0.2, 0.2, 1.0) and Diffuse: (0.8, 0.8, 0.8, 1.0) The program sets surface specular parameter to (1, 1, 1, 1) and shininess to 50 Vertex normal (n) is set by GLUT, l and h can be calculated from vertex position and light source position Specular Ambient Diffuse

113 Summary How to assign color to vertices?
Global illumination model Local illumination model (Phong illumination model) How to assign color to pixels? Flat, Gouraud, and Phong shading Per-vertex vs. per-pixel lighting We are not done with color yet The result of shading may be combined with the result of texture mapping

114 References Study light position and light material tutorial from Study the programs Light.c, teapots.c, and movelight.c from s/redbook/

115 Readings “OpenGL Programming Guide”: chapter 5
Next lecture: clipping and scan conversion


Download ppt "Lecture 10, 11, and 12 Lighting & Shading"

Similar presentations


Ads by Google