Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Illumination and Shading Day 6, 2011 © Jeff Parker.

Similar presentations


Presentation on theme: "1 Illumination and Shading Day 6, 2011 © Jeff Parker."— Presentation transcript:

1 1 Illumination and Shading Day 6, 2011 © Jeff Parker

2 2 Outline Review last collision problem Goal: Realistic images Review lighting in the real world Types of illumination Shading Strategies Shading Algorithms Limitations of shading algorithms Alternatives

3 3 Distance from Point to Line int Ax = p->getX() - c->getCenter()->getX(); int Ay = p->getY() - c->getCenter()->getY(); int dot = Ax*v->getX() + Ay*v->getY(); int Px = dot*v->getX(); int Py = dot*v->getY(); int lenSqr = v->getX()*v->getX() + v->getY()*v->getY();

4 4 Distance from Point to Line // Need to find the normal float normX = Ax - ((float)Px/lenSqr); float normY = Ay - ((float)Py/lenSqr); float distSqr = normX * normX + normY * normY; int radiusSqr = c->getRadius() * c->getRadius(); return (distSqr <= radiusSqr)

5 5 Circle Intersects Line Seg // Dispatch to correct routine bool LineSeg::intersects(Circle *c) { Line *ln = new Line(p, q, 0); if (!ln->intersects(c)) return false; else {// Line intersects: does Line Segment? if (c->contains(p) || c->contains(q)) return true; // Remaining case - do we straddle line?

6 6 Circle Intersects Line Seg int vx = q->getX() - p->getX(); int vy = q->getY() - p->getY(); int cx = c->getCenter()->getX(); int cy = c->getCenter()->getY(); int v1x = cx - p->getX(); int v1y = cy - p->getY(); int v2x = cx - q->getX(); int v2y = cy - q->getY();

7 7 Punch line… int dot1 = (vx * v1x) + (vy * v1y); int dot2 = (vx * v2x) + (vy * v2y); // Are both angles acute? // Are both angles obtuse? return ( dot1 * dot2 < 0 )

8 8 Next Week's problem

9 9 Examples We start by looking at light in some photos What do you see?

10 10 Examples

11 11 Examples

12 12 Examples

13 Luxo Jr Pixar's first movie http://www.youtube.com/watch?v=46mcpqOVN08

14 Spectrum Light is visible electromagnetic radiation

15 15 Observations Light is generated by a source Sun, Light bulb, phosphorescence,… Light travels through space, air, glass, water… Travels in straight line – may bend at boundaries Light strikes object – some wavelengths are absorbed, some are reflected The reflected light travels through air, glass, … Some of the reflected light reaches our eyes

16 16 Lambert's Law Different types of finish Matt vs. glossy Smooth, bumpy, brushed Most surfaces are matt: many man made surfaces are smooth Lambertian – luminance is isotropic Looks the same from every viewpoint Luminance depends on angle of incidence Sunlight is strong in summer, weak in winter

17 17 Snell's law Snell's law decribes how light bends moving from one medium to another

18 18 Fresnel's law Fresnel's law extends Snell's law Refraction is often accompanied by reflection Fresnel also invented the Fresnel lens Only uses Snell's Law

19 19 Milestones Hooke (1665) – Light is rapid vibration (wave) Newton (1666) – Light is a corpuscle (particle) Young (1801) – Double-Slit experiment - wave Maxwell (1860) – Electromagnetic disturbance Einstein (1905) – Photoelectric effect - Light comes in discrete quanta (photons) – 1921 Nobel Prize Quantum Mechanics – Light is both particle and wave

20 20 Wave or Particle? Experimental evidence for the two theories PhenomenonWaveParticle Reflectionyes Refractionyes Interferenceyesno Diffractionyesno Polarizationyesno Photoelectric Effectnoyes

21 21 Human sensitivity The cones sense different wavelengths The original version of the Retinylidene protein is thought to have been tuned for green light

22 22 Spectrum of sources Compare incandescent to sunlight

23 23 Halogen Bulb Fresnell's law extends Snell's law Refraction is often accompanied by reflection

24 24 Blacklight Compare incandescent to sunlight

25 25 Fluorescent Bulb Fresnell's law extends Snell's law Refraction is often accompanied by reflection

26 26 Takeaway Different light sources emit different spectra The same scene looks different under different light OpenGL gives you control over your light source's spectrum

27 27 Light Sources As well as direct light, there are many indirect sources This is sometimes called global illumination or ambient light Other points get direct illumination

28 28 Point source Some lights are from a radial point source Light bulb: rays radiate Some sources are directional – all the rays are ~ parallel This is an ideal model – best approximation for distant sources

29 29 Other Light Sources Spot Lights Area light source A 2D area emits light Soft shadows Extended light source Spherical Light source (3D) Soft shadows

30 30 Shadows Shadows are important in creating atmosphere

31 31 Hard and Soft Shadows Hard shadows are created by point sources

32 32 Putting it together The illumination of a scene is made of two parts The light sources Emitted spectrum Geometry (position and direction) Attenuation – decreases with distance Surface Reflectance spectrum Geometry Absorption

33 33 Shading options We will look at alternative forms of shading

34 34 Shading options We will look at alternative forms of shading

35 35 Shading options The Quest for Realism (Jim Blinn, 1980) A brief history of Graphics http://www.youtube.com/watch?v=pbSBUEH0PYo

36 36 Reflectance Models We will break down light into three components Ambient Light Diffuse light – point light source, matt finish Specular – point light source, glossy finish Each component will have three sub-components Red, Green, Blue – 9 values in all

37 37 Diffuse Light: Matt surface A Lambertian surface (e.g. unfinished wood) has the same brightness, whatever the viewer's angle. Not all patches of a matt surface have the same brightness: depends upon position of light source The Diffuse Intensity (I D ) is equal to the cosine of the angle between the Normal vector N and the vector towards the light, L, multiplied by the Intensity of the light, I L. L and N are assumed to be of unit length (normalized)

38 38 Diffuse Light: Matt surface This is a step forward – can tell where the light is But we see the edges of the patches

39 39 Gouraud Henri Gouraud, 1971, PhD University of Utah Idea was to interpolate shading over a polygon Get good results without requiring many small polygons Start with normal vector for each polygon At each vertex, average incident normals to get per-vertex "normal" Interpolate the value over polygon (picture is of Sylvie Gouraud)

40 40 Interpolation

41 41 Specular Reflections Bi-Directional Reflectance Distribution Function (BRDF)

42 42 BRDF sampling Special purpose hardware to sample BRDF

43 43 BRDF sampling Sample values

44 44 Specular Highlights For specular component, we use 4 vectors at each point l From point towards light v From point towards viewer n Normal to the point r Perfect reflector Where light would bounce

45 45 LightPosition

46 46 LightMaterial

47 47 Specular Highlight Phong (U. Utah, 1973) added a specular term Strong as vector v approaches reflected vector r, drops off as they differed (angle phi) I r = Reflected Intensity k s = Absorption coef I = Incoming Intensity alpha = shininess coef 

48 48 Computing Reflector r The angle of reflection must equal the angle of incidence The three vectors should be co-planar

49 49 Shininess Coef Metals have small specular reflection – large alpha (100-200) Plastics have wide specular reflection – smaller alpha (5-10)

50 50 Distance Term Light from distant source is inversely proportional to the distance squared We can add a term of the form 1/(a + bd + cd 2 )

51 51 Light Sources We add together the effects of the three forms of light (Ambient, Diffuse, Specular) over the three colors This gives us 9 terms {d, s, a} x {r, g, b}

52 52 Material Properties Each material can be configured to react distinctly to each type of light, and to each color Gives us 9 absorption coefficients and one shineness coefficient alpha

53 53 Adding it all up For each light source, and for each color component, the Phong model gives the following equation For each color, we add up the contributions from all lights

54 54 Blinn-Phong Jim Blinn proposed alternative to Phong model Approximate the angle phi Uses h, the "halfway" vector midway between l and v The new angle psi is half phi if all vectors are coplanar. Given alpha, we find matching power beta. OpenGL uses Flat or Gouraud with Blinn-Phong shading 

55 55 Why is this any better? If we are using Gouraud shading, the normal n varies as we interpolate over each polygon. As n changes, we must recompute the vector r Given direct light and a distant eye, l and v do not change, or do not change as quickly. We can quickly compute a dot product on the fly as n varies

56 56 Compare Phong vs Blinn-Phong

57 Example 57 teapots.c from The Redbook Single light variety of material parameters

58 Example 58 material.c from The Redbook Single light variety of material parameters See next page…

59 59 * The spheres in the first row have materials with no ambient reflection. * The second row has materials with significant ambient reflection. * The third row has materials with colored ambient reflection. * The first column has materials with blue, diffuse reflection only. * The second column has blue diffuse reflection, as well as specular * reflection with a low shininess exponent. * The third column has blue diffuse reflection, as well as specular * reflection with a high shininess exponent (a more concentrated highlight). * The fourth column has materials which also include an emissive component. * glTranslatef() is used to move spheres to their appropriate locations.

60 60 Lighting Rules 1.Must specify lights: position and properties: glLight() 2.Must specify (unit) normal vectors for each face, unless using shapes where OpenGL supplies them 3.If you resize the model, renormalize with call to glEnable(GL_NORMALIZE) 4.Call glShadeModel(GL_SMOOTH) (the default) 5.Call glEnable(GL_LIGHTING) and also enable each light. 6.Must specify material properties: glMaterial()

61 Light // Initialize shader lighting parameters point4 light_position( 0.0, 0.0, -1.0, 0.0 ); color4 light_ambient( 0.2, 0.2, 0.2, 1.0 ); color4 light_diffuse( 1.0, 1.0, 1.0, 1.0 ); color4 light_specular( 1.0, 1.0, 1.0, 1.0 ); color4 material_ambient( 1.0, 0.0, 1.0, 1.0 ); color4 material_diffuse( 1.0, 0.8, 0.0, 1.0 ); color4 material_specular( 1.0, 0.8, 0.0, 1.0 ); float material_shininess = 100.0; 61

62 Light color4 ambient_product = light_ambient * material_ambient; color4 diffuse_product = light_diffuse * material_diffuse; color4 specular_product = light_specular * material_specular; glUniform4fv( glGetUniformLocation(program, "AmbientProduct"), 1, ambient_product ); glUniform4fv( glGetUniformLocation(program, "DiffuseProduct"), 1, diffuse_product ); glUniform4fv( glGetUniformLocation(program, "SpecularProduct"), 1, specular_product ); 62

63 Light glUniform4fv( glGetUniformLocation(program, "LightPosition"), 1, light_position ); glUniform1f( glGetUniformLocation(program, "Shininess"), material_shininess ); // Retrieve transformation uniform var locations ModelView = glGetUniformLocation( program, "ModelView" ); Projection = glGetUniformLocation( program, "Projection" ); glEnable( GL_DEPTH_TEST ); glShadeModel(GL_FLAT); glClearColor( 1.0, 1.0, 1.0, 1.0 ); 63

64 GL_FLAT vs GL_SMOOTH 64

65 Vertex Shader attribute vec4 vPosition; attribute vec3 vNormal; varying vec4 color; uniform vec4 AmbientProduct, DiffuseProduct, SpecularProduct; uniform mat4 ModelView; uniform mat4 Projection; uniform vec4 LightPosition; uniform float Shininess; 65

66 Vertex Shader void main() { // Transform vertex position into eye coord vec3 pos = (ModelView * vPosition).xyz; vec3 L = normalize( LightPosition.xyz - pos ); vec3 E = normalize( -pos ); vec3 H = normalize( L + E ); // Transform vertex normal into eye coordinates vec3 N = normalize( ModelView*vec4(vNormal, 0.0) ).xyz;

67 Vertex Shader // Compute terms in the illumination equation vec4 ambient = AmbientProduct; float Kd = max( dot(L, N), 0.0 ); vec4 diffuse = Kd*DiffuseProduct; float Ks = pow( max(dot(N, H), 0.0), Shininess ); vec4 specular = Ks * SpecularProduct; if( dot(L, N) < 0.0 ) specular = vec4(0.0, 0.0, 0.0, 1.0);

68 Vertex Shader - combine vec4 ambient = AmbientProduct; vec4 diffuse = Kd*DiffuseProduct; vec4 specular = Ks * SpecularProduct; if( dot(L, N) < 0.0 ) specular = vec4(0.0, 0.0, 0.0, 1.0); gl_Position = Projection * ModelView * vPosition; color = ambient + diffuse + specular; color.a = 1.0;

69 Sam Buss' Light Torus 69

70 Light Torus Press "W" to increase the number wraps. Press "w" to decrease the number wraps. Press "N" to increase the number of segments per wrap. Press "n" to decrease the number of segments per wrap. Press "q" to toggle between quadrangles and triangles. CONTROLLING THE ANIMATION: Press the "a" key to toggle the animation off and on. Press the "s" key to perform a single step of the animation. The left and right arrow keys controls the rate of rotation around the y-axis. The up and down arrow keys increase and decrease the rate of rotation around the x-axis. In order to reverse rotational direction you must zero or reset the torus ("0" or "r"). Press the "r" key to reset the torus back to initial position, with no rotation. Press "0" (zero) to zero the rotation rates.

71 71 Light Torus CONTROLLING LIGHTS Press '1' or '2' to toggle the first or second light off and on. Press 'f' to toggle between flat and smooth shading. Press 'l' to toggle local modes on and off (local viewer and positional light, or non-local viewer and directional light). COMMANDS SHOWING OPENGL FEATURES: Pressing "p" toggles between wireframe and polygon mode. Pressing "f" key toggles between flat and smooth shading.

72 Light Color 72

73 Local and infinite 73

74 74 Lighting Rules 1.Must specify lights: position and properties: glLight() 2.Must specify (unit) normal vectors for each face, unless using shapes where OpenGL supplies them 3.If you resize the model, renormalize with call to glEnable(GL_NORMALIZE) 4.Call glShadeModel(GL_SMOOTH) (the default) 5.Call glEnable(GL_LIGHTING) and also enable each light. 6.Must specify material properties: glMaterial()

75 Light Properties // Lighting values float ambientLight[4] = {0.6, 0.6, 0.6, 1.0}; float Lt0amb[4] = {0.8, 0.8, 0.16, 1.0}; float Lt0diff[4] = {1.0, 1.0, 0.2, 1.0}; float Lt0spec[4] = {1.0, 1.0, 0.2, 1.0}; float Lt0pos[4] = {1.7*4.0, 0.0, 0.0, 1.0}; // 4 = MajorRadius + MinorRadius float Lt1amb[4] = {0.0, 0.0, 0.5, 1.0}; float Lt1diff[4] = {0.0, 0.0, 0.5, 1.0}; float Lt1spec[4] = {0.0, 0.0, 1.0, 1.0}; float Lt1pos[4] = {0.0, 1.2*4.0, 0.0, 1.0}; 75

76 Light Properties // Material values float Noemit[4] = {0.0, 0.0, 0.0, 1.0}; float Matspec[4] = {1.0, 1.0, 1.0, 1.0}; float Matnonspec[4] = {0.4, 0.05, 0.4, 1.0}; float Matshiny = 16.0; 76

77 Turning on void initRendering() { glEnable( GL_DEPTH_TEST ); glEnable(GL_LIGHTING);// Enable lighting calculations glEnable(GL_LIGHT0);// Turn on lights 0 and 1 glEnable(GL_LIGHT1); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);// Ambient light // Light 0 (Position is set in updateScene) glLightfv(GL_LIGHT0, GL_AMBIENT, Lt0amb); glLightfv(GL_LIGHT0, GL_DIFFUSE, Lt0diff); glLightfv(GL_LIGHT0, GL_SPECULAR, Lt0spec); // Light 1 (Position is set in updateScene) glLightfv(GL_LIGHT1, GL_AMBIENT, Lt1amb); glLightfv(GL_LIGHT1, GL_DIFFUSE, Lt1diff); glLightfv(GL_LIGHT1, GL_SPECULAR, Lt1spec); }

78 Local vs Directional // Toggle from local to global (directional) mode void LocalToggle() { LocalMode = !LocalMode; if ( LocalMode ) Lt0pos[3] = Lt1pos[3] = 1.0; else Lt0pos[3] = Lt1pos[3] = 0.0; } void updateScene( void ) {... glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode);

79 Turn on lights void updateScene( void ) { int i,j; // Clear the redering window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glShadeModel( shadeModel );// Set the shading to flat or smooth. glPolygonMode(GL_FRONT_AND_BACK, polygonMode); // "wire" or "solid" glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode); // Set up lights if ( Light0Flag==1 || Light1Flag==1 ) { // Emissive spheres have no other color. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Noemit); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Noemit); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0); }

80 Turn on or off lights 1, 2 if ( Light0Flag==1 ) { glPushMatrix(); glTranslatef(Lt0pos[0], Lt0pos[1], Lt0pos[2]); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Lt0spec); glutSolidSphere(0.2,5,5); glPopMatrix(); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, Lt0pos); } else { glDisable(GL_LIGHT0); } if ( Light1Flag==1 ) { glPushMatrix(); glTranslatef(Lt1pos[0], Lt1pos[1], Lt1pos[2]);...

81 Update Torus attributes // Torus Materials glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Matnonspec); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Matspec); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Matshiny); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit); glPushMatrix();// Save to use again next time. // Update the orientation of the torus, if the animation is running. if ( runMode ) { RotY += RotIncrementY; if ( fabs(RotY)>360.0 ) { RotY -= 360.0*((int)(RotY/360.0)); } RotX += RotIncrementX; if ( fabs(RotX)>360.0 ) { RotX -= 360.0*((int)(RotX/360.0)); }

82 Draw the Torus // Set the orientation. glRotatef( RotX, 1.0, 0.0, 0.0); glRotatef( RotY, 0.0, 1.0, 0.0); // Draw the torus glColor3f( 1.0, 0.5, 1.0 ); glBegin( QuadMode==1 ? GL_QUAD_STRIP : GL_TRIANGLE_STRIP ); for (i=0; i<NumWraps; i++ ) { for (j=0; j<NumPerWrap; j++) { putVert(i,j); putVert(i+1,j); } putVert(0,0); putVert(1,0); glEnd();

83 digression - PutVertex /* issue vertex command for segment number j of wrap number i. */ void putVert(int i, int j) { float wrapFrac = (j%NumPerWrap)/(float)NumPerWrap; float phi = PI2*wrapFrac; // angle within cross section // angle of cross section float theta = PI2*(i%NumWraps+wrapFrac)/(float)NumWraps; float sinphi = sin(phi); float cosphi = cos(phi); float sintheta = sin(theta); float costheta = cos(theta); float y = MinorRadius*sinphi; float r = MajorRadius + MinorRadius*cosphi; float x = sintheta*r; float z = costheta*r; glNormal3f(sintheta*cosphi, sinphi, costheta*cosphi); glVertex3f(x,y,z); }

84 Draw the Reference Pyramid // Draw the reference pyramid glTranslatef( -MajorRadius-MinorRadius-0.3, 0.0, 0.0); glScalef( 0.2f, 0.2f, 0.2f ); glColor3f( 1.0f, 1.0f, 0.0f ); glBegin(GL_TRIANGLE_STRIP); glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 ); glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 ); glVertex3f( 1.0, 0.0, 0.0); glVertex3f( 0.0, sqrt(2.0), 0.0); glVertex3f( -0.5, 0.0, sqrt(3.0)*0.5 ); glVertex3f( -0.5, 0.0, -sqrt(3.0)*0.5 ); glEnd(); glPopMatrix(); // Restore to original matrix as set in resizeWindow() // Flush the pipeline, swap the buffers glFlush(); glutSwapBuffers(); }

85 Homework Add shading to your 3D world Looking ahead – plan your projects Future directions: Should I move one of these topics up? Clipping and Besenham Buffers and Stencil Texture Mapping Ray Tracing Animation and Particle Systems Curves and surfaces 85

86 Conclusion Lighting is difficult There are techniques that model reality The implementations often simplify reality to achieve speed We have looked at the most common model Purely local: for example, does not create shadows, refraction, reflections, caustics, … For other effects, need fancier shaders or Ray Tracing 86

87 Sample Programs Nate Robins lightmaterial, lightposition Sam Buss LightTorus Redbook teapots material colormat movelight 87


Download ppt "1 Illumination and Shading Day 6, 2011 © Jeff Parker."

Similar presentations


Ads by Google