Illumination and Shading Angel, Chapter 5 slides from AW, etc. CSCI 6360/4360.

Post on 12-Jan-2016

222 views 2 download

Tags:

Transcript of Illumination and Shading Angel, Chapter 5 slides from AW, etc. CSCI 6360/4360.

Illumination and ShadingAngel, Chapter 5

slides from AW, etc.

CSCI 6360/4360

Overview

• Photorealism and complexity– Light interactions with a solid

• Rendering equation for illumination– “infinite scattering and absorption of light”– Local vs. global illumination

• Local techniques for shaging– Flat, Gouraud, Phong

• An illumination model -– “describes the inputs, assumptions, and outputs that we will use to calculate

illumination of surface elements”– Light– Reflection characteristics of surfaces

• Diffuse reflection, Lambert’s law, specular reflection– Phong approximation – interpolated vector shading

Angel on Speed for Interactivity

• “… our goal is to create realistic shading effects in as close to real time as possible, rather than trying to model the BRDF as accurately as possible. Hence, we use tricks with a local model to simulate effects that can be global in nature.”

• “Because we cannot solve the full rendering equation, we instead use various tricks in an attempt to obtain realistic renderings, …”

• Good enough … for “fast” (interactive) graphics– But, Moore’s law …– And things change with time

• E.g., now, can easily program any shading model• E.g., now, serious work on ray tracing fast enough for interactivity

Photorealism and Complexity• Recall, from 1st lecture … examples below exhibit range of “realism”

• In general, trade off realism for speed – interactive computer graphics– Wireframe – just the outline – historically interesting– Local illumination models, polygon based

• Flat shading – same illumination value for all of each polygon• Smooth shading (Gouraud and Phong) – different values across polygons

– Global illlumination models• E.g., Raytracing – consider “all” interactions of light with object

Polygons – Flat shading Ray tracingWireframe Polygons - Smooth shading

Lighting and Shading

• Lighting, or illumination – Process of computing intensity and color of a sample point in a

scene as seen by a viewer – Function of geometry of scene (including model, lights and

camera and their spatial relationships) and material properties

• Shading – Process of interpolation of color at points in-between those with

known lighting or illumination, typically vertices of triangles or quads in a mesh

• Flat -- 1 point per polygon • Smooth -- interpolate

– Used in many real time graphics applications (e.g., games) since calculating illumination at a point is usually expensive

• For GPU processing triangles– Lighting is calculated by a vertex shader– Shading is done by a fragment or pixel shader

Ray tracing

PolygonsSmooth shading

PolygonsFlat shading

Illumination Models: Computing Illumination

• Illumination can be computed by:

• Light transport simulation: – Evaluate illumination with enough samples to produce a final image without any

guessing / shading, both for direct and for indirect components – Often used for high quality renderers and movies – Some implementations can run in real time on the GPU, but more complex

lighting models that are difficult to parallelize for GPUs are still run on the CPU – Renders of highest quality can take days for a single frame, even on modern

distributed CPU render farms and/or GPU render farms

• Polygon rendering: – Evaluate illumination at several samples, and shade (using a shading model) in

between to produce pixels in the final image – Often used in real-time applications such as computer games, done in GPU – Lower quality than light transport simulation, but with various additions such as

maps (bump, displacement, environment), can obtain satisfactory results

Rendering EquationGlobal Illumination

• Light travels …– Light strikes A

• Some scattered, some absorbed, …

– Some of scattered light strikes B• Some scattered, some absorbed, …• Some of this scattered light strikes A• And so on …

• Infinite scattering and absorption of light can be described by rendering equation

– Bidirectional reflection distribution function(BRDF)

– Cannot be solved in general– Ray tracing is a special case for perfectly

reflecting surfaces

• Rendering equation is global, includes:– Shadows– Multiple scattering from object to object– … and everything

translucent surface

shadow

multiple reflection

Elements of Global Illumination(summary)

• Global Illumination– Simulating what happens when other objects affect light

reaching a surface element• e.g., ray tracing

• Lights and Shadows– Most light comes directly light sources– Light from a source may be blocked by other objects

• In “shadow” from that light source, so darker• All Non – global can’t do shadows

• Inter-Object Reflection– Light strikes other objects, bounces toward surface element– When that light reaches surface element from other surface

elements, brightens surface element (indirect illumination)

• Expensive to Compute– Many objects in scene affect light reaching surface elements

• But, necessary for some applications

translucent surface

shadow

multiple reflection

Global Illumination – Ray Tracing(an often used technique)

• Again, is a global technique, so, image formed from all light reaching view

• Ray tracing (or casting)– Basically, “running things backwards,

constrained by pixels …”– Follow rays from center of projection until they

either are absorbed by objects or go off to infinity

– Can handle global affects• Multiple reflections• Translucent objects

– Slow– Must have whole data base available at all times

• Radiosity (more later)– Energy based approach– Very slow

Light travels from source toobjects, bouncing, reflecting,…

Ray tracing technique – followsFrom cop back to light source

Also, Light Interactions with a Solid

• Will focus on surface properties and light-material interactions

• But, there are other elements in modeling light …– but good enough is good enough…– Below from Watt, “3d Computer Graphics”

Physical Model: BRDF Bidirectional Reflectance Distribution Function

• The “general physically based model”

• A radiometric description

• Actually, Lambertian model used in cg (and which we’ll see later) is a “good enough” approximation

Physical Model: BRDF Bidirectional Reflectance Distribution Function

• Light energy can arrive at any point on a surface from any direction and be reflected and leave from any direction

– For every pair of input and output directions, will be a value that is the fraction of incoming light that is reflected and leave in output direction

• BDRF – Bidirectional reflectance distribution function– Describes reflectance, absorption, and transmission of light at surface of material– In addition to just surface properties

• BDRF is a function of (briefly)– Frequency of light– 2 angles to describe light in– 2 angles to describe light out

Physical Model: BRDF• Light energy can arrive at any point on a surface from any direction

and be reflected and leave from any direction– For every pair of input and output directions, will be a value that is the fraction of

incoming light that is reflected and leave in output direction

• Obtaining BDRF’s empirically

• … and how many points are there to consider???

ShadingLook ahead

• So far, just used OpenGL pipeline for vertices– Polygons have all had constant color, glColor(_)

– Not “realistic” – or computationally complex

• Of course, OpenGL can (efficiently) provide more

realistic images

• Light-material interactions cause each point to have a

different color or shade

• Need to consider :– Light sources, material properties, location of viewer, surface

orientation

• “Lighting”: modeling light sources, surfaces, and their interaction

• “Shading”: how lighting is done with polygon

Light – Material Interactions for CGLook ahead

• Will examine each of these in detail

• Diffuse surface– Matte, dull finish– Light “scattered” in all directions

• Specular surface– Shiny surface– Light reflected (scattered) in narrow range of

directions

• Translucent surface– Light penetrates surface and emerges in another

location on object

“Surface Elements” for Interactive CG(a big idea)

“Surface Elements” for Interactive CG(a big idea)

• A computer graphics issue/orientation:– Consider everything or just “sampling a scene”?

• Again, global view considers all light coming to viewer:– From each point on each surface in scene - object precision– Points are smallest units of scene – Can think of points having no area or infinitesimal area

• i.e., there are an infinite number of visible points. • Of course, computationally intractable

“Surface Elements” for Interactive CG(a big idea)

• A computer graphics issue/orientation:– Consider everything or just “sampling a scene”?

• Again, global view considers all light coming to viewer:– From each point on each surface in scene - object precision– Points are smallest units of scene – Can think of points having no area or infinitesimal area

• i.e., there are an infinite number of visible points. • Of course, computationally intractable

• Alternatively, consider surface elements– Finite number of differential pieces of surface

• E.g., polygon– Figure out how much light comes to viewer from each of these

pieces of surface– Often, relatively few (vs. infinite) is enough

• Reduction of computation through use of surface elements is at core of tractable/interactive cg

Surface Elements and Illumination, 1Tangent Plane Approximation for Objects

• Tangent Plane Approximation for Objects– Most surfaces are curved: not flat– Surface element is area on that surface

• Imagine breaking up into very small pieces • Each of those pieces is still curved,

– but if we make the pieces small enough,

– then we can make them arbitrarily close to being flat

– Can approximate this small area with a tiny flat area

• Surface Normals– Each surface element lies in a plane.– To describe plane, need a point and a normal– Area around each of these vertices is a surface element

where we calculate “illumination”

• Illumination … (next slide)

Surface Elements and Illumination, 2

• So, we have:– Tangent plane (polygonal) approximation for objects

– And surface normals (and vertex normals, too)

• For illumination:– Again, light rays coming from rest of scene

strike surface element and head out in different directions

– Light that goes in direction of viewer from that surface element

• If viewer moves, light will change

– This is “illumination” of that surface element– Will see model, used for shading, for cg later

In Sum: Local vs. Global Rendering

• “Correct” illumination requires a global calculation involving all objects and light sources

– Recall “rendering equation”• infinite scattering and absorption of light

– Incompatible with pipeline model which shades each polygon independently (local rendering)

• However, in computer graphics, especially real time graphics, happy if things “look right”

– Exist many techniques for approximating global effects

– Will see several

Light-Material Interaction

Light-Material Interaction, 1

• Light that strikes an object is partially absorbed and partially scattered (reflected)

• Amount and wavelength of light reflected determines brightness and color of object

– E.g., surface appears red under white light because the red component of light is reflected and rest is absorbed

– Can specify both light and surface colors

Livingstone, “Vision and Art”

Light-Material Interaction, 2

• Diffuse surfaces– Rough (flat, matte) surface scatters

light in all directions– Appear same from different viewing

angles

• Specular surfaces– Smoother surfaces, more reflected

light is concentrated in direction a perfect mirror would reflected the light

– Light emerges at single angle– … to varying degrees– Phong shading will model

• Reflected light is scattered in a manner that depends on the smoothness and orientation of surface to light source

Light Sources

• General light sources are difficult to work with because must integrate light coming from all points on the source,

– E.g., light bulb not a point, or even a sphere

• Use “simple” light sources

• Point source– Model with position and color– Distant source = infinite distance away (parallel)

• Spotlight– Restrict light from ideal point source, as a cone

• Ambient light– A real convenience – recall, “rendering equation” – but real nice– Same amount of light everywhere in scene– Can model (in a good enough way) contribution of many sources and reflecting

surfaces

Overview: Local Rendering Techniques

Overview: Local Rendering Techniques

• Will consider– Illumination (light) models focusing on following elements:

• Ambient• Diffuse• Attenuation• Specular Reflection

– Interpolated shading models:• Flat, Gouraud, Phong, modified/interpolated Phong (Blinn-Phong)

About (Local) Polygon Mesh Shading(it’s all in how many polygons there are)

• Angel example of approximation of a sphere…

• Recall, any surface can be illuminated (in principle) by:

1. calculating surface normal at each visible point and

2. applying illumination model

… but, recall surface model of cg!

• And, again, where efficiency is consideration, e.g., for interactivity (vs. photorealism) approximations in lighting are used

– Approximation in lighting is fine, because polygons used to model objects are themselves approximations!

– And just as a circle can be considered as being made of “an infinite number of line segments”, …

• so, it’s all in how many polygons there are!

About (Local) Polygon Mesh Shading(interpolation)

• Interpolation of illumination values is widely used for speed– And can be applied using any illumination model

• Will see three methods - each treats a single polygon independently of others (non-global)

– Constant (flat)– Gouraud (intensity interpolation)– Interpolated Phong (normal-vector interpolation)

• Each uses interpolation differently

Mesh Shading

• Also, have not said much, but data structures and implementation of meshes and other elements, but in practice a critical elements

Flat/Constant Shading, About• Single illumination value per polygon

– Illumination model evaluated just once for each polygon • 1 value for all polygon, Which is as fast as it gets!

– As “sampling” value of illumination equation (at just 1 point)– Right is flat vs. smooth (Gouraud) shading

• If polygon mesh is an approximation to curved surface, – faceted look is a problem, especially at siloette – Also, facets exaggerated by mach band affect (more later)

• For fast, can (and do) store normal with each surface– Or can, of course, compute from vertices

• But, interestingly, approach is valid, if:– Light source is at infinity (is constant on polygon)– Viewer is at infinity (is constant on polygon)– Polygon represents actual surface being modeled (is not an

approximation)!

Flat/Constant Shading, Light Source

• In cg, lighting, often don’t account for angle of rays (as noted)

• Approach is valid, if …– Light source is at infinity (is constant on polygon)– Viewer is at infinity (is constant on polygon)– Polygon represents actual surface being modeled (is not an

approximation)

• Consider point light sources at right:– (Li = angle of ray with surface)

– Close to surface: L1 <> L2 <> L3

– Farther from surface: L1 <> L2 <> L3, but closer ----------------------

– At “infinity” can consider L1 = L2 = L3! • so and are constant on polygon

But, … Mach Banding

• May or may not be apparent here at intersection of surfaces (white “line”)

Mach Banding (Chevreul illusion)

Mach BandingA pragmatic challenge for cg rooted in human physiology

• Mach banding– Exaggerated differences in perceived

intensities • At adjacent edges of differing

gintensities– Non-intuitive and striking

• An “illusion” in sense that perception not veridical (true)

• In fact, physiological cause– Actual and perceived intensities due to

cellular bilateral inhibition• sensation (response of retinal cells)

depends on how cell neighbors are stimulated

• Eye’s photoreceptors responds to light

– according to intensity of light falling on it minus the activation of its neighbors

– Great for human edge detection– A challenge for computer graphics

Ernst Mach

Mach Bands and Receptor Fields

• Point where uniform area meets luminance ramp, bright band is perceived – Another way, appear where abrupt change in 1st derivative of brightness profile– Particularly a problem for uniformly shaded polygons in computer graphics

• Hence, various methods of smoothing are applied

• … any number of “unintended” things can happen with perception

Simultaneous Brightness Contrastperception …

• Gray patch on a dark background looks lighter than the same patch on a light background

Simultaneous Brightness Contrastperception

• Background removed! • (honest, no change in foreground)

Gouraud Shading, About

Gouraud Shading, About• Recall, for flat/constant shading, single illumination value per polygon

• Gouraud (or smooth, or interpolated intensity) shading overcomes problem of discontinuity at edge exacerbated by Mach banding

– “Smooths” where polygons meet– H. Gouraud, "Continuous shading of curved surfaces,"

IEEE Transactions on Computers, 20(6):623–628, 1971.

• Linearly interpolate intensity along scan lines– Eliminates intensity discontinuities at polygon edges– Still have gradient discontinuities,

• So mach banding is improved, but not eliminated– Must differentiate desired creases from tessellation artifacts

• (edges of a cube vs. edges on tesselated sphere)

Gouraud Shading, About• To find illumination intensity, need intensity of

illumination and angle of reflection– Flat shading uses 1 angle– Gouraud estimates – …. Interpolates– Across entire surface

1. Use polygon surface normals to calculate “approximation” to vertex normals (top fig.)

– Average of surrounding polygons’ normals– Since neighboring polygons sharing vertices and edges

are approximations to smoothly curved surfaces – So, won’t have greatly differing surface normals

• Approximation is reasonable one

2. Interpolate intensity along polygon edges (mid fig.)

3. Interpolate along scan lines (bottom fig.)– i.e,, find:

• Ia, as interpolated value between I1 and I2• Ib, as interpolated value between I1 and I3• Ip, as interpolated value between Ia and Ib

– formulaically, next slide

Gouraud Shading, Formulaically(supplementary)

• What goes in shader - straightforward

• 3: interpolate along scan lines– e.g., find:

• Ia, as interpolated value between I1 and I2• Ib, as interpolated value between I1 and I3• Ip, as interpolated value between Ia and Ib

– i.e., formulaically:

or

Gouraud Shading (more supplementary)

• Can also interpolate color– Though less straightforward

• Summary: Interpolating intensity – Gouraud shading– Gouraud versus constant shading– integrates nicely with scan line

algorithm:• constant along polygon edge:

What Gouraud Shading Misses

• Misses specular highlights in specular objects – because interpolates vertex colors instead of vertex

normals– interpolating normal comes closer to what actual

normal of surface being “polygonally” approximated would be

• Illumination model following, and its implementation in Phong shading, does handle

• Below:– Flat/constant, Gouraud/interpolated intensity, Phong

Illumination Model, Describing Light, 1

Illumination Model, Describing Light, 1Setting the stage for cg models

• Will be looking at model of illumination for cg• And will end up with shading models

– Why are things relatively brighter or darker depending on orientation to light source and viewer?

• Start with light …

• Units of light• (light incident on a surface and exiting from a surface is

measured in specific terms defined later)– for now, consider the ratio:

Light exiting surface toward the viewer Light incident on surface from light

• Another way to conceptualize– Quick take (note diff angle, theta, at right for the two

views):• Just not as much “light” (energy) per surface area

unit – for non “straight on” light• dA “shorter” (less) on left, than right• And can describe quantitatively

Describing Light, 2Recap

• Factors in computing “light exiting surface” (how bright):

– Physical properties of the surface (material)– Geometric relationship of surface

• With respect to viewer• With respect to lights

– Light incident on the surface (color and intensity of lights in the scene)

– Polarization, fluorescence, phosphorescence, …• Which we won’t consider

• Difficult to define some of these inputs• So, clearly, and approximation, which is ok

– Not sure what all categories of physical properties are …,

• and the affect of physical properties on light is not totally understood

– Polarization of light, fluorescene, phosphorescene difficult to keep track of

– Light exiting surface toward viewer– Light incident on surface from lights

A Simple Illumination Model

• One of first models of illumination that “looked good” and could be calculated efficiently

– A (relatively) simple, non-physical, non-global (local) illumination model– Describes some observable reflection characteristics of surfaces– Came out of work done at the University of Utah in the early 1970’s– Still used today, as it is easy to do in software and can be optimized in hardware

• Later, will put all together with normal interpolation for efficiency

• Components of the simple model:– Reflection characteristics of surfaces

• Diffuse Reflection• Ambient Reflection• Specular Reflection

• Model not physically-based, and does not attempt to accurately calculate global illumination

– Does attempt to simulate some of important observable effects of common light interactions

– Can be computed quickly and efficiently

Reflection Characteristics of Surfaces

Diffuse Reflection (1/7)

• Diffuse Reflection– Diffuse (Lambertian) reflection

• typical of dull, matte surfaces – e.g. carpet, chalk plastic

• independent of viewer position• dependent on light source position

– (in this case a point source, again a non-physical abstraction)

• Vecs L, N used to determine reflection– Value from Lambert’s cosine law … next slide

• Lambert’s cosine law:– Specifies how much energy/light reflects toward some

point– Computational form used in equation for illumination

model

• Will build model through successive slides

• Now, have intensity (I) calculated from:– Intensity from point source– Diffuse reflection, or absoption, coefficient (arbitrary!)– With cos-theta calculated using normalized vectors N

and L• For computational efficiency

• Again:

Reflection Characteristics of Surfaces

Lambert’s Law (2/7)

Reflection Characteristics of Surfaces

Energy Density Falloff (3/7)• Less light as things are farther away

from light source

• Reflection - Energy Density Falloff– Should also model inverse square law

energy density falloff

• But, inverse of distance squared along often creates harsh effects

– Can make surfaces with equal differ in appearance important if two surfaces overlap

– Do not often see objects illuminated by point lights

• Can instead use formula at right– Experimentally-defined constants, c1, c2

• Heuristic

– Still, inverse of distance squared is main effect

Reflection Characteristics of Surfaces

Ambient Reflection (4/7)

• Ambient Reflection

• Diffuse surfaces reflect light

• Some light goes to eye, some to scene– Light bounces off of other objects and

eventually reaches this surface element – This is expensive to keep track of accurately – Instead, we use another heuristic

• Ambient reflection– Independent of object and viewer position– Again, a constant – “experimentally determined”– Exists in most environments

• some light hits surface from all directions • Approx. indirect lighting/global illumination

– A total convenience• but images without some form of ambient lighting

look stark, they have too much contrast– Light Intensity = Ambient + Attenuation*Diffuse

Reflection Characteristics of Surfaces

Color (5/7)

• Colored Lights and Surfaces

• Write separate equation for each component of color model

– Lambda - wavelength– Represent an object’s diffuse color by one

value for each color component• E.g., in RGB• Are reflected in proportion to, e.g., for

the red component

• Wavelength dependent equation– Evaluating the illumination equation at only 3

points in the spectrum is wrong, but often yields acceptable results

– To avoid restricting ourselves to one color sampling space (more later), indicate wavelength dependence with (lambda)

Reflection Characteristics of Surfaces

Specular Reflection (6/7)

• Specular Reflection

• Directed reflection from shiny surfaces– Typical of bright, shiny surfaces, e.g. metals– Color of specular componentsdepends on material and how it scatters light energy

• in plastics: color of point source, in metal: color of metal• in others: combine color of light and material color

– Dependent on light source position and viewer position– Early model by Phong neglected effect of material color on specular highlight

• Made all surfaces look plastic– For perfect reflector, see light iff– For real reflector, reflected light falls off as increases– Below, “shiny spot” size differs with angle if view (alpha)

Reflection Characteristics of Surfaces

Specular Reflection (7a/7)• Phong Approximation

– Again, non-physical, but works– Deals with differential “glossiness” in a

computationally efficient manner

• Below shows increasing n, left to right– “Tightness” of specular highlight– n in formula below (k, etc., next slide)

Reflection Characteristics of Surfaces

Specular Reflection (7b/7)

• Yet again, constant, k, for specular component

• Vectors R and V express viewing angle and so amount of illumination

• n is exponent to which viewing angle raised

– Measure of how “tight”/small specular highlight is

Putting it all together:

A Simple Illumination Model• Non-Physical Lighting Equation

– Energy from a single light reflected by a single surface element

• For multiple point lights, simply sum contributions

• An easy-to-evaluate equation that gives useful results

– It is used in most graphics systems,

• but it has no basis in theory and does not model reflections correctly!

Interpolated Vector Shading/ModelIncreasing Efficiency of Model

• Calculating normal at each point is computationally expensive

• Can interpolate normal– As interpolated vertices with Gouraud

shading

• Interpolated Vector Model (next slide):– Rather than recalculate normal at each at

each step, interpolate normal for calculation

– Much more computationally efficient

• Bui Tuong Phong, "Illumination for Computer Generated Images," Comm. ACM, Vol 18(6):311-317, June 1975

Interpolated Vector Shading/ModelIncreasing Efficiency of Model

• Normal vector interpolation– interpolate N rather than I– especially important with specular

reflection– computationally expensive at each

pixel to recompute• must normalize, requiring

expensive square root

• Looks much better than Gouraud and done in commodity hardware

– OpenGL default

• Bui Tuong Phong, "Illumination for Computer Generated Images," Comm. ACM, Vol 18(6):311-317, June 1975

Phong Shading - Summary

• Simple model (not physically based)

• Splits illumination at a surface into three components – Ambient – Non-specific constant global lighting (hack) – Diffuse – Color of object under normal conditions using Lambert’s model – Specular – Highlights on shiny objects (hack)

• Proportional to so a larger results in a more concentrated highlight and 𝑹⋅𝐕𝛼 𝛼glossier object

Demo Program

• Calculates Phong shading at each point on sphere

OpenGL Shading Functions

OpenGL Shading Functions

• Polygonal shading– Flat– Smooth– Gouraud

• Steps in OpenGL shading1. Enable shading and select model

2. Specify normals

3. Specify material properties

4. Specify lights

Normals

• Normal – vector perpendicular to a surface– Recall, typically set by application program for each vertex or polygon– Likely, not mess with in most cases, fyi, and for data structure construction

• In OpenGL the normal vector is part of the state

• Set by glNormal*()– glNormal3f(x, y, z);– glNormal3fv(p);

• Usually want to set the normal to have unit length so cosine calculations are correct

– Length can be affected by transformations– Note that scaling does not preserved length– glEnable(GL_NORMALIZE) allows for autonormalization at a performance

penalty

Normal for TriangleFyi

plane n ·(p - p0 ) = 0

n = (p2 - p0 ) ×(p1 - p0 )

normalize n n/ |n|p0

p

1

p

2

n

p

Note that right-hand rule determines outward face

Enabling Shading

• Shading calculations are enabled by:– glEnable(GL_LIGHTING)– Once lighting is enabled, glColor() ignored

• Must enable each light source individually– glEnable(GL_LIGHTi) i=0,1…..

• Can choose light model parameters:– glLightModeli(parameter, GL_TRUE)

• GL_LIGHT_MODEL_LOCAL_VIEWER – do not use simplifying distant viewer assumption in calculation

• GL_LIGHT_MODEL_TWO_SIDED – shades both sides of polygons independently

Defining a Point Light Source• For each light source, can set an RGBA (A for alpha channel)

– For diffuse, specular, and ambient components, and – For the position– Code below from Angel, other ways to do it (of course)

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);

Distance and Direction

• Note that position is given in homogeneous coordinates– If w =1.0, specifying a finite location– If w =0.0, specifying a parallel source with the given direction vector

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};

Spotlights

• Use glLightv to set • E.g., from before glLightv(GL_LIGHT0, GL_POSITION, light0_pos);

– Direction GL_SPOT_DIRECTION– Cutoff GL_SPOT_CUTOFF– Attenuation GL_SPOT_EXPONENT

• Proportional to cosaf

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 also allows a global ambient term that is often helpful for testing

– glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient)

Moving Light Sources

• Light sources are geometric objects whose positions or directions are affected by the model-view matrix

• Depending on where the position (direction) setting function is, can:– Move the light source(s) with the object(s)– Fix the object(s) and move the light source(s)– Fix the light source(s) and move the object(s)– Move the light source(s) and object(s) independently

Material Properties

• Material properties are also part of the OpenGL state and match the terms in the modified Phong model

• Set by glMaterialv()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);

Front and Back Faces

• Default is to shade only front faces, which works correctly for convex objects

• If we set two sided lighting, OpenGL will shade 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 glMaterialf

back faces not visible back faces visible

Emissive Term

• Can simulate a light source in OpenGL by giving a material an emissive component

• Component is unaffected by any sources or transformations– GLfloat emission[] = 0.0, 0.3, 0.3, 1.0);– glMaterialf(GL_FRONT, GL_EMISSION, emission);

Transparency

• Material properties are specified as RGBA values

• The A value can be used to make the surface translucent

• The default is that all surfaces are opaque regardless of A

• Much more later on blending using this feature

Efficiency

• Because material properties are part of the state, if change materials for many surfaces, can affect performance

• Angel: Can make code cleaner by defining a material structure and setting all materials during initialization

typedef struct materialStruct {

GLfloat ambient[4];

GLfloat diffuse[4];

GLfloat specular[4];

GLfloat shineness;

} MaterialStruct;

• We can then select a material by a pointer

End

• .