OpenGL Light

Posted on: May 10, 2018, by :

And just when you thought you were done

Preorder Nowin PDF format for Kindle andget a discount.OpenGL Gems is coming out on April 15th, 2017.The paperback version will be available via thisAmazon page, please bookmark it!

Just as in Beginners OpenGL Tutorial – Introduction to 3D, most common terms behind 3D rendering theory were explained, in the this tutorial we will start with introduction to light.

Defining surface material properties 2

1. Your eyes are mechanisms created to directly perceive or absorb the photons(more about photons in a second) of light and not the objects. And you are, as a programmer, destined to simulate this functionality on the computer screen.

And therefore it wouldnt be convenient to describe everything about light that is currently known. Thats rather a redundant subject, because what were really after is learning how to construct and build some lit 3D shapes for our OpenGL application or video game.

Again, OpenGL has two important functions called glEnable(param) and glDisable(param). While these functions dont enable or disable anything in particular, they are reliant on the parameter passed to them. So in other words, you will be using these functions a lot when programming in OpenGL to turn a particular feature on or off.

All of this is theoretical, of course. We use the term light rays to merely abstract a more complex mechanism.

Im still working on this site.These and other subjects will be covered, as Im planning to write a lot more articles in the month of April (2017). You can bookmark this website and check back sometime soon for new content that will be posted shortly.

Below, is a brief example of OpenGL light commandglLightfvthat enables specular highlight (we will learn about specular light in just a moment) on a light source with ID GL_LIGHT0. By default in OpenGL there are up to 8 light sources identified by ID handles GL_LIGHT0 through GL_LIGHT7.

OpenGL presents the programmer with a set of functions for use in the initialization part of your program to set specific global properties of the program behavior. The visual behavior of the lighting model is specified by the function glLightModel. There are two types of this function. One that uses scalar values as parameters and one for use with vector valued as parameters. Here are the definitions of both functions:

WebGL Initialization Tutorial new webgl init tutorial

For now, simply notice how the ambient component of the hat (or is it part of his head?) is white or grayish. This is its base color. And the diffuse light source is projecting a bright white light onto it, supposedly coming from the sun.

It is a relatively old OpenGL Light tutorial but 10 years later even though OpenGL programming has moved on from glBegin, glVertex and glEnd (Immediate Mode) approach to VBO and GLSL shaders (and now even further to multi-threadedVulkanapplications) the same OpenGL light principles still apply to 3D graphics creation.

In modern OpenGL most of these effects are now done in avertex shaderor afragment shaderprogram, usually written and compiled separately from the main code. We will have to go into that elsewhere in a tutorial on this site, as it is a completely separate discussion.

A flashlight held slightly above the lit by it object can be though of as emitting diffuse light. In the image above a light source casting diffuse light of red color is located on the immediate left side of the object. When diffuse light touches the surface of an object, it scatters and reflects evenly across that surface.

Learn HTML in 14 minutes (YouTube video tutorial)

Just like diffuse light, specular light is a directional type of light. It comes from one particular direction. The difference between the two is that specular light reflects off the surface in a sharp and uniform way. The rendering of specular light relies on the angle between the viewer and the light source.

Lets consider an object which emits an average amount of green color. On the image below emissive light component is applied to the sphere. And as you can see, the result is similar to the effect created by applying ambient light to the same sphere in the example above.

OpenGL doesnt calculate normal vectors for you and this will be mentioned again below when we get to the COMPUTING SURFACE NORMALS section. Let me tell you however, about where and when the normal vector is specified. When you are composing an object, just before you specify one of its consequent vertices with a call to glVertex (as was explained in tutorial 2.5 – Introduction to OpenGL primitives) for light to work properly you also have to specify the normal vector for that vertex with the glNormal command. If you dont specify the normal vector, the normal will contain its default value of (0.0, 0.0, 1.0) at every vertex. This, of course, will work but wont be acceptable in most cases since a mo

In this section I describe what light is in more detail. Specifically, how color is being perceived by the viewer. As discovered in the previous section light is a wave of energy. The most apparent quality of light lies in representing color. Color is tightly connected to the concept of light. Lets see how.

Before we can create a light source, its a good idea to learn the theory behind how light works in general. This OpenGL light tutorial is divided in two section.

glEnable(intcap); This function has many uses. It can enable many features of OpenGL; the feature you want to enable is specified in the flag cap. In the base code, within InitOpenGL we use this command to enable all kinds of things.

So, I assume no previous knowledge whatsoever about light and what it is. So lets begin our journey from the dark into the light by going through a very brief lecture about the nature of light..

So I will only put emphasis on the most important ideas that will help us understand light and light-programming better as it relates to programming with OpenGL. This means that we need to think of light in abstract form (ambient, specular and diffuse) to simplify the process.

File System Logging (Error Logs, Notifications)

The two types of defining light properties

The lighting model of OpenGL is based on the Gourad Shading implementation. A specific color is assigned to each of the vertices in a polygon. This color is calculated according to the objects material properties and surrounding light sources. Then the colors at each of the 3 vertices are taken and interpolated across the whole polygon.

The lighting model is set up with a call to glLightModel and I describe this a bit later.

This is done by calling glEnable(GL_LIGHTn); where n is the index number of the color you are enabling, ranging from 0 to 7 because OpenGL lets you specify a maximum of eight light sources.

There isnt a great necessity for this model reader in particular. You can try to define your own polygon with straight OpenGL code or use your own 3D model loader. I just figured people who are learning about light may fall into the same category as ones who may be also interested in learning how to make a model loader. Sooner or later, you will need to be able to load 3D models into your OpenGL application.

Creating a Direct Input Application

Light is the most important idea behind visual representation of anything that a human being can visually perceive. The idea of perception of light lies in the fact that what you can see isnt based on the objects that you are viewing but on the rays of light cast from a light source and reflected from those objects. Its important to note that your eyes dont directly see objects as there is no physical correlation between your eyes and those objects.

After this call, all of the polygons will be smoothly shaded by using the Gourad-shading technique and according to the nearby light sources and polygons material properties.

The visible light is contained within the wavelengths ranging from 390 nanometers to 720 nanometers in length. At 390 nanometers the color is violet. A wavelength of 720 nanometers represents the red color. Everything in between is considered the visible light and the range itself is called the spectrum:

Defining surface material properties 1

There are two ways that light could be thought of as. There is a theory of light particles described by PHOTONS. And there is a theory of light being a WAVE of energy. In ancient Greece the light was thought of as a stream of particles which travel in a straight line and bounce off a wall in a way that any other physical objects do. The fact that light couldnt be seen was based on the idea that the light particles are too small for the eye to see, traveled too fast for the eye to notice them or that the eye was just seeing through them.

As far as light programming goes, we are only concerned with understanding values within the color spectrum range unless were programming some sort of an ultraviolet or infra red color wavelength simulation (which in fact we are not).

glDisable(intcap); This function disables whatever properties were previously set with glEnable. glShadeModel(int mode); Selects the polygon shading model. mode is the flag representing the shading mode. This flag can be set to either GL_FLAT or GL_SMOOTH.

Object material colors can be imitated by adjusting all 3 components of the light we have just discussed. In addition, graphics programmers combine them with other techniques such as texture mapping, bump mapping (same as normal mapping,) environment mapping (this is when texture of the object is calculated in real time, as a reflection of surroundings represented by a sphere or a cube, commonly for creating highly reflective surfaces such as mirrors, or car bodies) that will add even more detail to the objects surface.

This tutorial was originally titledThe OpenGL Light Biblewhich I wrote when I was learning about how the light source and lighting systems work in OpenGL.

Toads head is made out of mushroom. So it is not very reflective. But Marios hat is probably plastic. You can catch a glimpse of the specular highlight on it. Here, this light is not very shiny, and barely visible, but it is indeed there. The shininess of the highlight can be dependent on objects material properties. In order to create a hyper-realistic graphics Nintendo designers decided not to overdo the effect of the specular highlight here, by making it too intense, and dim it down instead:

Light there was indeed but how do we program it in OpenGL? First, let me recite a couple of previously explained functions. I take this straight from the OpenGL tutorial – 2 -Creating an OpenGL Window. But this time I will show you how these functions are used in light programming.

We have just learned that from the point of the camera (the viewer of the scene) specular light creates a highlighted area on the surface of the viewed object known as specular highlight or specular reflection. The intensity of the specular reflection is dependent on the material the object is made of and the strength of the light source which contains the specular light component.

2. A ray of light travels in a straight line.

This is normally done during the initialization part of your OpenGL application. Its important to note that the default global ambient light intensity is R=0.2, G=0.2, B=0.2, Alpha=1.0.

If the above sphere wasnt emitting a light of green color, it would have appeared red in color. However, a green component of emissive light is applied to it. When the light sources rays of light hit the spheres surface, the source and destination colors merge together producing a yellowish surface. As you know mixing green and red produce yellow.

I created a separate sister site just for WebGL tutorials.

So the light rays commonly originate from an energy source such as the sun or a lamp in your room. Its important to note that theoretically a ray of light travels in a straight line and by the time you visually perceive an object, it is the rays of light reflected or scattered off that object that your eyes absorb. From now on you will have to think of light in terms of theoretical rays as described in this tutorial and not as just something invisible that makes objects brighter. This becomes more important when you start programming your own 3D light graphics engine, as opposed to using the predefined set of OpenGL light-modeling functions.

There is a lot more going on in Mario Kart 8 graphics engine, visible on this screenshot. But were not ready to go there yet. For now, lets move on to the next type of light, the specular light, or also sometimes known asspecular highlight.

In graphics programming, and perhaps other crafts which deal with representation of light, a few abstract terms which describe specific effects that light can produce on a surface of an object have emerged. These abstract types of light are described in the following section. Their terminology is crucial to a graphics programmer. Keep in mind that this is by far not the complete set of effects that light in general can produce, especially within the confines of modern OpenGL Shader Language (GLSL), and here will serves as a mere basics tutorial. I do believe, however that thorough understanding is achieved by knowing these basic principles, and knowing them well.

Specular reflection (or specular highlight) is displayed here in addition to the Ambient and Diffuse layers of light. You can observe how the objects 3D representation is greatly augmented by specular light properties. Its as if we can feel the material the object is made from. This could be a balloon, something plastic, with a smooth surface. The smoother the object is, the more defined this specular highlight will be.

A 3D sphere lit by AMBIENT LIGHT only; appears to look 2D. Ambient light is the average volume of light that is created by emission of light from all of the light sources surrounding (or located inside of) the lit area.

To describe light in an OpenGL application you need to perform the following two steps: set the lighting and the shading models. But first, you have to enable the lighting system on the whole:glEnable(GL_LIGHTING);

The way OpenGL shades polygons to simulate light and how light properties are assigned to light sources and materials is explained in the following part of this tutorial.

The following terms describe different types of light that you must know when programming a 3D application which requires a light source. It is important to understand what effect each of these types of light create on the surface of rendered 3D objects.

Ambient lightalone cannot communicate the complete representation of an object set in 3D space because all vertices are evenly lit by the same color and the object appears to be 2-dimensional as seen in the image above. Although the object displayed is actually a 3D sphere, it appears to be flat on the screen, when lit only by ambient light.

It would be very time consuming to calculate the real mechanics of light and the way it works in nature so, this common set of light types was generally adopted by OpenGL: AMBIENT LIGHT, DIFFUSE LIGHT and SPECULAR LIGHT.

The light that can be seen by the human eye is in general a mixture of all kinds of different lights scattered and reflected against the surroundings with different material properties. All physical matter is made up of atoms. The mechanics of reflection of photons off physical matter depends on various things such as the kind of atoms, the amount of each kind and the arrangement of atoms in the object that the photons are being reflected off. Some photons are reflected and some are absorbed. When photons are absorbed they are usually converted to heat. The defining factors of the visual quality of a material lie within this matter absorption-and-reflection concept. The color that the material reflects is observed as that materials color. Also, the more light the material reflects the more shiny it will appear to the viewer.

So, as an example of specifying a lighting model and for the sake of enabling the global ambient light model for the whole scene, a call to the glLightModelfv function is made. The specified parameters are GLOBAL_AMBIENT_LIGHT_MODEL, which tells OpenGL that we want a global ambient light model set; and global_ambient, which is the color of the global ambient light being set:

Okay, now… OpenGL uses Gourad-shading while in theory, shading can be handled in one of two ways. In the traditional Gourad-shading technique the illumination is computed exactly at the vertices and the values are interpolated across the polygon. In Phong-shading technique, the normal vectors are given at each vertex, and the system interpolates these vectors in the interior of the polygon. Then this interpolated normal vector is used in the lighting equation. Phong-shading produces more realistic images, but takes considerably mode time to compute for the reason that 3 normals are used per polygon, as opposed to just 1.

JavaScript Games – Drawing Sprites on Canvas

The shading model is set up with a call to glShadeModel and can be either set to SMOOTH or FLAT model. The SMOOTH shading model specifies the use of Gourad-shaded polygons to describe light while the FLAT shading model specifies the use of single-colored polygons. For this reason the objects shaded using the FLAT model look less realistic, however this mode is less computationally expensive. Were not going to use the FLAT model at all as its not very visually impressive when it comes to rendering something rather realistic-looking, but you can still experiment with it at your own will. Setting a shading model will be described below.

EMISSIVE LIGHT is differentiated from the rest, and is the type of light which is being emitted by an object, whereas the other three types of light are usually used to describe a light source. Lets take a detailed look at each of these types of light:

In the beginning I will explain what light is and what basic types of light there are in OpenGL (Ambient, Diffuse and Specular.) Toward the end, a more technical, OpenGL-specific text is presented. The complete source code for this tutorial is included as a demonstration of a simple, flat, non-textured 3D model affected by a light source. For this purpose I will use the previously explained [*.m] (a very simple 3D model I explain in another tutorial on this site) format file model-loading code, which I suggest you look at. Its a great way to load and preview entire models instead of hard-coding new polygons all the time.

To conclude, it is observed that the light can behave as both: a wave and also as packets of energy particles: PHOTONS. There is no solid explanation of the more complex underlying structure of how light works, as of yet.

To demonstrate how both AMBIENT and DIFFUSE lights work together to create a more-realistic looking object, imagine a 3D sphere with a dark red ambient light spread over it:

With no additional light sources around, an objects color to which only emissive light component is applied has the same visual quality as an object with only ambient light applied to it. However, the mechanics of how any additional diffuse or specular light reacts with the surface of the same object with only emissive light applied to it is different.

Rats, WebGL Hit a Snag [YouTube] Chrome rats bug fixed.

How Does CSS work? YouTube Tutorial

These terms were created because certain effects that light produces on the objects needed to be described in order to distill the complex mathematical calculations of light. However, this doesnt mean that these exact types of light actually exist in nature, we just think of them as an abstraction of the effects that light can produce when cast on different materials. These effects are more than sufficient for creating incredibly realistic computer graphics.

Combining ambient with diffuse light sources is the same principle at work lighting 3D characters in Mario Kart 8. Try to ignore the red polka dot texture, we will cover texture mapping elsewhere in a tutorial on this site.

Each different color is simply energy which can be represented by a wavelength. Whats important to note is that color is only a wavelength visible to the eye. A wavelength is measured by the distance between the peaks of the energy wave. Consider this image.

The final shading formula explained

In addition to specifying the ambient light amount to a light source or a material, it is possible to set the GLOBAL amount of the ambient light which will be cast on all rendered objects. This method of lighting is called the Global Ambient Light and in itself is considered a lighting model.

OpenGL does a lot of work for us. Just doing this, and later enabling GL lighting with another function we are not ready to discuss yet, will make it possible for us to make shiny spots on your 3D objects.

OpenGL Gemsis the authorative guide on OpenGL programming published by Learning Curve /Education for software developers!This book in 3D C++ programming series clearly, and in easy to follow language, explains fundamental principles used behind programming 3D games using the OpenGL cross-platform framework.

A 3D sphere reflecting green emissive light. The effect is similar to ambient light until additional sources of light are introduced into the scene.

Como Resolver O Erro GPS Signal Not Found do Pokemon Go

As you already know, a light source can have all of the three components assigned to it which are the ambient light, the diffuse light and the specular light components. Lets see what happens when we apply a light source to the above scene. The light source we are applying has the following properties: red ambient light, red diffuse light and white specular light.

How is this related to light programming? glEnable is used to enable lighting on the whole when you pass GL_LIGHTING parameter to it. gEnable is also responsible for enabling a particular light source in your 3D scene.

In the late 1600s it was proposed that the light was actually a wave of energy and didnt travel exactly in a straight line being a stream of particles. By 1807 the theory of light waves was confirmed with an experiment that demonstrated that the light, passed through a narrow slit radiates additional light outward on the other side of the slit. So it was proven that the light has to travel in a form of a wave in order to spread itself that way, and not in a straight line. It is important to note that a beam of light radiates outward at all times.

Now, by positioning a diffuse light source on the left side of the sphere, we get the following result:

We can only guess how Nintendo graphics programmers actually generated this effect. I am sure they used shaders, rather than some OpenGL command such as glBegin, glEnd and glVertex (thats the old way of doing things.) But these are the building blocks of light representation on a 3D object, regardless of the API, or technique, the same principles apply.

The theory of light was developed further by Albert Einstein in 1905. He described the photoelectric effect. This theory described activity of the ultraviolet light hitting a surface, emitting electrons off that surface. This behavior was supported by an explanation that light was made up of a stream of energy packets called PHOTONS.

When working with light in OpenGL we are dealing with abstract representation of light rather than a perfect, correct model of light in the real world. That level of realism is desirable, but given computational limits of home computers and consoles light must be approximated. In the future, we will have real time ray-tracing graphics, but were not there yet. Until then, we need to approximate light using abstract models.

The segment of the wavelengths between 390nm and 720nm is called the color spectrum. The wavelengths outside the color spectrum are not visible by the eye. Below 390nm (the wavelength of the violet color) the ultraviolet wavelengths are located. Above 720nm infrared wavelengths can be found. The prefix ultra means: beyond, on the other side of; the prefix infra stands for inferior to or beneath. …hence the names.

Let there be light, and there was light.While we as mere mortals cannot speak light into existence, we can observe its certain properties and use them to create computer graphics.

If you want to know and understand what light represents in nature, you will read this section. If you want to program light in OpenGL you will read the following one. But if you want to be an educated human being and programmer, Im terribly sorry but I think youre going to have to read both.

Notice how the sphere now appears to be 3D, rather than a flat circle. By combining the base ambient light and then shining light from a diffuse light source onto an object, we achieve a much more realistic illusion. In order to demonstrate how this technique is used to create realistic images, lets take a look at a screenshot of Toad, the character from Mario Kart 8:

Normal vector calculations are crucial for an acceptable lighting result.

The second point however, is not entirely correct, but can be correct at the same time — lets discover the theory of light a bit further to understand what is meant by this statement. A side note on what is known about the light by scientists will help

You are seeing the standardOpenGL Lightmodel on this screenshot diagram consisting of 3 abstract components: Ambient Light, Diffuse Light (color of the light source) and specular highlight (the shiny, glossy reflection spot).

When sun rays pass through the window of a room they hit the walls and are reflected and scattered into all different directions which averagely brightens up the whole room. This visual quality is described by ambient light.

But first, lets think about what light is. And return to code a bit later to put this new knowledge into practice. Lets expand our understanding of how light works in nature and later apply it to 3D programming with OpenGL using API calls available to us.

Diffuse light represents a directional light cast by a light source. Diffuse light can be described as the light that has a position in space and comes from a single direction.

Light is important and so you will be able to understand the basics of it after reading this tutorial, whether youre learning about it from GLSL vantage point, or if you are looking for any beginner information about how light works in OpenGL.

After setting up global ambient light the next step is usually setting up the shading model. This is done by calling glShadeModel. As was described previously, were going to use the smooth shading model in this tutorial and all consequent additions to the OpenGL base code. So, finally, to set it up we make the following call:

In either case, the computed color of a vertex is the result of lighting, if lighting is enabled, or it is the current color at the time the vertex was specified, if lighting is disabled.

A diffuse light of red color is cast onto a black object defining its 3D shape.

To become good at something such as programming its not enough to just know certain functions and know when to call them. Thorough knowledge is required. So be patient my friend, as we move forward.

So from this, the two rules to understand are:

The specular light component of the light source is white. The center of the specular reflection is white in the center, however as it spreads off it merges with the green and red colors, augmenting on yellow (which is green + red). Again, note that if there were no emissive light applied to the sphere, it would have appeared like the sphere shown under the section SPECULAR LIGHT above, all in red with a white specular reflection.

Emissive light is a little different than any other previously explained light components. The emissive light component is responsible for the objects materials property to reflect or absorb light. When applied to an objects material, emissive light acts to simulate the light that is reflected off the object.

GL_SMOOTH shading is the default shading model, causes the computed colors of vertices to be interpolated as the primitive is rasterized, assigning different colors to each resulting pixel fragment. GL_FLAT shading selects the computed color of just one vertex and assigns it to all the pixel fragments generated by rasterizing a single primitive.

Leave a Reply