Thursday, May 5, 2016

Sampler.Objects

[State]
    To Be Continued......

[Concept]
    Sampler.Objects..OpenGL

[URL]
...
http://www.sinanc.org/blog/?p=215


[Contents]
...

[Questions Original]

...
Sampler objects first introduced with OpenGL 3.3. This OpenGL object separates sampler state from texture data 
Textures are represented by texture objects in OpenGL and programmers use actual texture images via texture objects. Texture objects are not C++ classes or such. They are just names. Before OpenGL 3.3 you have to do following things to use a texture in your program: 
  1. // In your Init() or wherever you initialize  
  2. // named object that represents a texture  
  3. GLuint texture = 0;  
  4. //Create  texture object  
  5. glGenTextures(1 , &texture);  
  At This stage you have texture object.  Perhaps now you want to load an image from disk and use it as a texture: 


  1. // In your Init() or where ever you initalize  
  2. // Select texture object to associate with image data  
  3.  glBindTexture(GL_TEXTURE_2D , texture);  
  4. //Upload data to GPU  
  5.  glTexImage2D(.... , data);   
  6. // Switch to default texture object  
  7. glBindTexture(GL_TEXTURE_2D , 0);  
  We are done with our texture object (we changed its state) and return to default texture object.  Lets decide how our texture data is sampled: 


  1. // In your Init() or wherever you initialize  
  2. // Select texture object  
  3. glBindTexture(GL_TEXTURE_2D , texture);  
  4. // Set sampler state  
  5. glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_LINEAR);  
  6. glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR);  
  7. glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_WRAP_S , GL_CLAMP_TO_EDGE);  
  8. glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_WRAP_T , GL_CLAMP_TO_EDGE);  
  9. // Switch to default texture object  
  10. glBindTexture(GL_TEXTURE_2D , 0);  
  11. // -----------------------------------------------------------  
  12. // then in your render loop  
  13. glActiveTexture(GL_TEXTURE0);  
  14. glBindTexture(GL_TEXTURE_2D , texture);  
  15. glUniform1i(samplerId , 0);  
  16. DrawSomething( );  
So as you see texture and operations performed on it are coupled. What if you want to use same texture with a different sampling state? Options are: 

  • Load same texture image from disk to GPU again. Associate image with different texture object and set new sampling state. This method duplicates data and wastes precious video memory.

  • Do bind – edit state – bind in your render loop. This may hurt performance.

These problems can be solved by using sampler objects.
...
[Sampler.Objects]
...
Lets look at sampler objects usage.
First you define and create a sampler object:

//  In your Init() or where ever you initalize
GLuint sampler = 0;
glGenSamplers(1 , &sampler);

Then set sampling parameters:

//  In your Init() or where ever you initalize
glSamplerParameteri(sampler , GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler , GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler , GL_TEXTURE_MIN_FILTER , GL_LINEAR);
glSamplerParameteri(sampler , GL_TEXTURE_MAG_FILTER , GL_LINEAR);

As you see there is no binding.
This is an example of direct state access in OpenGL.
Although there is no binding mechanism for changing sampler state, sampler objects must be bound to a texture unit.

...
[]


[]
...

...
[]


[]
...

...
[]


[]
...

...
[]

Monday, May 2, 2016

Lighting, diffuse, ambient, specular

[State]

  •     To Be Continued...

[Conception]

...
  •     Lighting
...

[ Content ]

[ Types of Light Sources ]

[ Directional Light ]

...
Directional light is a light that has a direction, but doesn't have a position, i.e. it's rays are travelling through the scene in a specified direction, but they are not coming from single source. Such light is sun for example - it illuminates everything around, but it's too far from the scene, so its rays are practically parallel and affect every place of scene equally. Depending on the phase of a day, the rays direction from sun change.


[ ambient intensity ]
What's that?  
In real world, if you have a lamp that illuminates dark room, even objects that aren't illuminated directly, but are let's say behind other objects are slightly illuminated.  
This is because light gets scattered all over the place.  
Of course, to simulate this would be a horror, but approximating it with simple constant - ambient intensity is enough for this tutorial (I wanted to simulate rays in shaders, but then I took an arrow to the knee ). It says how much will objects be lit by that light no matter the direction they're facing or their position. In this tutorial I set it to 0.2. So the ambient contribution to final color is ambientLightColor*ambientIntensity.
Fragment Shader...
                      struct SimpleDirectionalLight
                      {
                           vec3    vColor;
                           vec3    vDirection;
                           float    fAmbientIntensity;
                      };
...

[ Point Light ]

...
Point light comes from a single source, like a light bulb. It radiates to all directions, and also has an attenuation - the further object it illuminates, the less light reaches there. This type of light source has a greater computational complexity, but it's still pretty fast and easy to implement
...

[ Spot Light ]

...
Spotlight is most difficult from these. It emits a cone of light, with inner cone that has more intense light than outer cone. Only things inside the cone gets illuminated. The most common example is the flashlight. This one is computationally most expensive, and will be implemented later
...
www.mbsoftworks.sk

[ Normal Vecor ]

Before we proceed, we must learn about normal vectors. Normal vector of a polygon is a vector that is perpendicular to the plane in which polygon lies - forms 90 degrees angle with it. In our case, polygon will always be triangle, because it consists of 3 points and three points, if not colinear, define a plane, whereas 4 points don't have to lie on a same plane neccessary. This vector simply tells us, which direction the polygon is facing. I wrote an article about it very long ago and I edited it when writing this tutorial, so if you are looking for a bit more explanation of normal vectors and vectors generally, and how are they calculated, take a look there right now - click here. So if we have a normal vector and know the direction the triangle is facing, we can start with its illumination. We will implement directional light in this tutorial. So let's get into it.
[ Diffuse Intensity ]


Another type of light contribution to final color is diffuse.  
This one does depend on direction between normal and light. And that's the variable fDiffuseIntensity in fragment shader - how much additional light will get applied to final color.  
If normal and light direction are parallel and facing opposite directions, for example normal is (1, 0, 0) and light direction is (-1, 0, 0), then that face should be lit as much with that light as possible. And that's why diffuse intesity is calculated with -vLightDirection- the opposite vector.  
In our example, dot product return would return -1.0 and this is cosine of angle between these vectors. Converting to actual angle will result in 180.0 degrees. 
But when facing opposite directions, we want the object to be lit, so that diffuse component should be 1.0 instead. Reverting light direction will alter results of dot product, which will be 1.0 now, and we are good (angle is 0 degrees). Notice, that if angle is between 90 and 180 degrees, diffuse contribution is 0.0, because the dot product returns negative value, and we clamp it to 0.0 with max function, because we don't want to suck out the light from the place, even though we directly don't illuminate it:


Let's examine these shaders to understand directional lights. Look at the vertex shader. 
There is a new matrix called normal matrix.  
What exactly is this?  
Well, when we transform objects into eye-space coordinates (rotate whole universe ), we also need to transform normals somehow, so they will face the right direction. We simply need to work in same space with vertex coordinates and normals as well.  
When using translation, there's no need to change normals - we're just moving our objects around, directions of normals stay the same.  
When using rotations, we need to rotate normals as well, and when scaling objects, another problem may arise, because it involves changing lengths of normals. In uniform scales (i.e. we scale by the same amount along X, Y and Z axis), this doesn't cause any problems, because it acts like scalar multiplication of vector - we just changed its length, but preserved directions. But in non-uniform scales, the new normal isn't perpendicular - say we scaled the polygon by (1, 2, 1), the new normal won't correspond the polygon. This picture will show more than thousand words:
So we must find a way how to transform this normals depending on the previous transformations and we want to find some nice way to do it. 
It turns out, that the proper way to transform normals is to take transpose of the inverse matrix of transformations performed locally on object. Transpose of matrix is matrix flipped around its diagonal and inverse matrix of A is such matrix B, that A*B = B*A = I, where I is identity matrix
...

[Standard Diffuse Lighting]

...
Diffuse lighting refers to a particular kind of light/surface interaction, where the light from the light source reflects from the surface at many angles, instead of as a perfect mirror.
alfonse.bitbucket.org
An ideal diffuse material will reflect light evenly in all directions, as shown in the picture above. No actual surfaces are ideal diffuse materials, but this is a good starting point and looks pretty decent.
For this tutorial, we will be using the Lambertian reflectance model of diffuse lighting. It represents the ideal case shown above, where light is reflected in all directions equally. The equation for this lighting model is quite simple:
Equation 9.1. Diffuse Lighting Equation
The cosine of the angle of incidence is used because it represents the perfect hemisphere of light that would be reflected. When the angle of incidence is 0°, the cosine of this angle will be 1.0. The lighting will be at its brightest. When the angle of incidence is 90°, the cosine of this angle will be 0.0, so the lighting will be 0. Values less than 0 are clamped to 0.

[Surface Orientation][Gouraud Shading][Directional Light Source][Normals and Space]

...
Normals have many properties that positions do. Normals are vector directions, so like position vectors, they exist in a certain coordinate system. It is usually a good idea to have the normals for your vertices be in the same coordinate system as the positions in those vertices. 
So that means model space. 
This also means that normals must be transformed from model space to another space. 
That other space needs to be the same space that the lighting direction is in; otherwise, the two vectors cannot be compared. One might think that world space is a fine choice. After all, the light direction is already defined in world space. 
You certainly could use world space to do lighting. However, for our purposes, we will use camera space. The reason for this is partially illustrative: in later tutorials, we are going to do lighting in some rather unusual spaces. By using camera space, it gets us in the habit of transforming both our light direction and the surface normals into different spaces. 
We will talk more in later sections about exactly how we transform the normal. For now, we will just transform it with the regular transformation matrix.
...

[Drawing with Lighting]

...
The full lighting model for computing the diffuse reflectance from directional light sources, using per-vertex normals and Gouraud shading, is as follows. The light will be represented by a direction and a light intensity (color). The light direction passed to our shader is expected to be in camera space already, so the shader is not responsible for this transformation. For each vertex (in addition to the normal position transform), we:
  • Transform the normal from model space to camera space using the model-to-camera transformation matrix.
  • Compute the cosine of the angle of incidence.
  • Multiply the light intensity by the cosine of the angle of incidence, and multiply that by the diffuse surface color.
  • Pass this value as a vertex shader output, which will be written to the screen by the fragment shader.
This is what we do in the Basic Lighting tutorial. It renders a cylinder above a flat plane, with a single directional light source illuminating both objects. One of the nice things about a cylinder is that it has both curved and flat surfaces, thus making an adequate demonstration of how light interacts with a surface.
...

[The Following From www.learnopengl.com]

...

[ Basic Lighting ]

...
  • Ambient lighting: even when it is dark there is usually still some light somewhere in the world (the moon, a distant light) so objects are almost never completely dark. To simulate this we use an ambient lighting constant that always gives the object some color.
  • Diffuse lighting: simulates the directional impact a light object has on an object. This is the most visually significant component of the lighting model. The more a part of an object faces the light source, the brighter it becomes.
  • Specular lighting: simulates the bright spot of a light that appears on shiny objects. Specular highlights are often more inclined to the color of the light than the color of the object.


...


Depth Testing


[State]
    To Be Continued....
...
[Conception]
   Depth Testing
...
[URL]
    http://www.learnopengl.com/#!Advanced-OpenGL/Depth-testing
...
[Contents]
...
The depth-buffer is a buffer that, just like the color buffer (that stores all the fragment colors: the visual output), stores information per fragment and (usually) has the same width and height as the color buffer. The depth buffer is automatically created by the windowing system and stores its depth values as 16, 24 or 32 bit floats. In most systems you'll see a depth buffer with a precision of 24 bits.
When depth testing is enabled OpenGL tests the depth value of a fragment against the content of the depth buffer. OpenGL performs a depth test and if this test passes, the depth buffer is updated with the new depth value. If the depth test fails, the fragment is discarded.
Depth testing is done in screen space after the fragment shader has run (and after stencil testing has run which we'll discuss in the next tutorial). The screen space coordinates relate directly to the viewport defined by OpenGL's glViewport function and can be accessed via GLSL's built-in gl_FragCoord variable in the fragment shader. The x and y components ofgl_FragCoord represent the fragment's screen-space coordinates (with (0,0) being the bottom-left corner). Thegl_FragCoord also contains a z-component which contains the actual depth value of the fragment. This z value is the value that is compared to the depth buffer's content.
...
[]
...
Depth testing is disabled by default so to enable depth testing we need to enable it with the GL_DEPTH_TEST option:
glEnable(GL_DEPTH_TEST);  
Once enabled OpenGL automatically stores fragments their z-values in the depth buffer if they passed the depth test and discards fragments if they failed the depth test accordingly. If you have depth testing enabled you should also clear the depth buffer before each render iteration using the GL_DEPTH_BUFFER_BIT, otherwise you're stuck with the written depth values from last render iteration:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
There are certain scenarios imaginable where you want to perform the depth test on all fragments and discard them accordingly, but not update the depth buffer. Basically, you're using a read-only depth buffer. OpenGL allows us to disable writing to the depth buffer by setting its depth mask to GL_FALSE:
glDepthMask(GL_FALSE); 
Note that this only has effect if depth testing is enabled.

...
[]

...
[]

...

Blending


[State]
    To Be Continued...

[Conception]
    Blending

[URL]
    http://www.learnopengl.com/#!Advanced-OpenGL/Blending

[Contents]
...
Blending in OpenGL is also commonly known as the technique to implement transparency within objects. Transparency is all about objects (or parts of them) not having a solid color, but having a combination of colors from the object itself and any other object behind it with varying intensity. A colored glass window is a transparent object; the glass has a color of its own, but the resulting color contains the colors of all the objects behind the glass as well. This is also where the name blending comes from, since we blend several colors (of different objects) to a single color. Transparency thus allows us to see through objects.
Blending



...

[ Orders Of Rendering]

...

Blending Basics
There are some things that deserve attention.  
Look at the order of rendering.  
First we rendered objects that are fully opaque, and then we turned the blending on to render the transparent objects. And not only that, we called function glDepthMask(0) to turn off writing to depth buffer, and after the rendering glDepthMask(1) to restore it.  
Why doing that?
Let's take an example: We want to render one opaque cube, and two transparent cubes in front of it After rendering opaque cube, we don't want to write values to depth buffer, because if there are two transparent object that pass Z-test, second transparent object can get behind the first, and after altering the depth buffer values with rendering the first transparent object, the second may not pass Z-test and thus won't be rendered at all. But since these objects are at least partially transparent, the second object should be visible as well. That's why we turn depth buffer writing off. 
Important lesson to take here is to pay attention to order of rendering - first opaque, then transparent with depth buffer writing disabled.
...
[]
...


...
[]
...

...
[]

Sunday, May 1, 2016

Buffer Objects

[State]
    To Be Continued...
[Concept]
    Buffer Objects

[URL]
    http://www.informit.com/articles/article.aspx?p=1377833&seqNum=7

    [Contents]

There are many operations in OpenGL where you send a large block of data to OpenGL, such as passing vertex array data for processing. Transferring that data may be as simple as copying from your system’s memory down to your graphics card. However, because OpenGL was designed as a client-server model, any time that OpenGL needs data, it will have to be transferred from the client’s memory. If that data doesn’t change, or if the client and server reside on different computers (distributed rendering), that data transfer may be slow, or redundant. 
Buffer objects were added to OpenGL Version 1.5 to allow an application to explicitly specify which data it would like to be stored in the graphics server.
          //----------
Many different types of buffer objects are used in the current versions of OpenGL:
  • Vertex data in arrays can be stored in server-side buffer objects starting with OpenGL Version 1.5. They are described in “Using Buffer Objects with Vertex-Array Data” on page 102 of this chapter. 
  • Support for storing pixel data, such as texture maps or blocks of pixels, in buffer objects was added into OpenGL Version 2.1 It is described in “Using Buffer Objects with Pixel Rectangle Data” in Chapter 8. 
  • Version 3.1 added uniform buffer objects for storing blocks of uniform-variable data for use with shaders.
You will find many other features in OpenGL that use the term “objects,” but not all apply to storing blocks of data. For example, texture objects (introduced in OpenGL Version 1.1) merely encapsulate various state settings associated with texture maps (See “Texture Objects” on page 437). Likewise, vertex-array objects, added in Version 3.0, encapsulate the state parameters associated with using vertex arrays. These types of objects allow you to alter numerous state settings with many fewer function calls. For maximum performance, you should try to use them whenever possible, once you’re comfortable with their operation.
An object is referred to by its name, which is an unsigned integer identifier. Starting with Version 3.1, all names must be generated by OpenGL using one of the glGen*() routines; user-defined names are no longer accepted.
          //----------

Creating Buffer Objects

In OpenGL Version 3.0, any nonzero unsigned integer may used as a buffer object identifier. You may either arbitrarily select representative values or let OpenGL allocate and manage those identifiers for you. Why the difference? By having OpenGL allocate identifiers, you are guaranteed to avoid an already used buffer object identifier. This helps to eliminate the risk of modifying data unintentionally. In fact, OpenGL Version 3.1 requires that all object identifiers be generated, disallowing user-defined names.

Making a Buffer Object Active

To make a buffer object active, it needs to be bound. Binding selects which buffer object future operations will affect, either for initializing data or using that buffer for rendering. That is, if you have more than one buffer object in your application, you’ll likely call glBindBuffer() multiple times: once to initialize the object and its data, and then subsequent times either to select that object for use in rendering or to update its data.

Allocating and Initializing Buffer Objects with Data

Once you’ve bound a buffer object, you need to reserve space for storing your data. This is done by calling glBufferData().
void glBufferData(GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
Allocates size storage units (usually bytes) of OpenGL server memory for storing vertex array data or indices. Any previous data associated with the currently bound object will be deleted.
  • target may be either GL_ARRAY_BUFFER for vertex data; GL_ELEMENT_ARRAY_BUFFER for index data; GL_PIXEL_UNPACK_BUFFER for pixel data being passed into OpenGL; GL_PIXEL_PACK_BUFFER for pixel data being retrieved from OpenGL; GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER for data copied between buffers; GL_TEXTURE_BUFFER for texture data stored as a texture buffer; GL_TRANSFORM_FEEDBACK_BUFFER for results from executing a transform feedback shader; or GL_UNIFORM_BUFFER for uniform variable values. 
  • size is the amount of storage required for storing the respective data. This value is generally number of elements in the data multiplied by their respective storage size. 
  • data is either a pointer to a client memory that is used to initialize the buffer object or NULL. If a valid pointer is passed, size units of storage are copied from the client to the server. If NULL is passed, size units of storage are reserved for use, but are left uninitialized. 
  • usage provides a hint as to how the data will be read and written after allocation. Valid values are GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, GL_DYNAMIC_COPY.
glBufferData() will generate a GL_OUT_OF_MEMORY error if the requested size exceeds what the server is able to allocate. It will generate a GL_INVALID_VALUE error if usage is not one of the permitted values. 

Updating Data Values in Buffer Objects

There are two methods for updating data stored in a buffer object. 
The first method assumes that you have data of the same type prepared in a buffer in your application. glBufferSubData() will replace some subset of the data in the bound buffer object with the data you provide.
void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
Update size bytes starting at offset (also measured in bytes) in the currently bound buffer object associated with target using the data pointed to by data. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_PIXEL_PACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER.
glBufferSubData() will generate a GL_INVALID_VALUE error if size is less than zero or if size + offset is greater than the original size specified when the buffer object was created.
The second method allows you more control over which data values are updated in the buffer.glMapBuffer() and glMapBufferRange() return a pointer to the buffer object memory, into which you can write new values (or simply read the data, depending on your choice of memory access permissions), just as if you were assigning values to an array. When you’ve completed updating the values in the buffer, you call glUnmapBuffer() to signify that you’ve completed updating the data.

Copying Data Between Buffer Objects

On some occasions, you may need to copy data from one buffer object to another. In versions of OpenGL prior to Version 3.1, this would be a two-step process:
  1. Copy the data from the buffer object into memory in your application. You would do this either by mapping the buffer and copying it into a local memory buffer, or by callingglGetBufferSubData() to copy the data from the server.
  2. Update the data in another buffer object by binding to the new object and then sending the new data using glBufferData() (or glBufferSubData() if you’re replacing only a subset). Alternatively, you could map the buffer, and then copy the data from a local memory buffer into the mapped buffer.
In OpenGL Version 3.1, the glCopyBufferSubData() command copies data without forcing it to make a temporary stop in your application’s memory.

Cleaning Up Buffer Objects

When you’re finished with a buffer object, you can release its resources and make its identifier available by calling glDeleteBuffers(). Any bindings to currently bound objects that are deleted are reset to zero.

Using Buffer Objects with Vertex-Array Data

To store your vertex-array data in buffer objects, you will need to add a few steps to your application. 
  1. (Optional) Generate buffer object identifiers. 
  2. Bind a buffer object, specifying that it will be used for either storing vertex data or indices. 
  3. Request storage for your data, and optionally initialize those data elements. 
  4. Specify offsets relative to the start of the buffer object to initialize the vertex-array functions, such as glVertexPointer(). 
  5. Bind the appropriate buffer object to be utilized in rendering. 
  6. Render using an appropriate vertex-array rendering function, such as glDrawArrays() orglDrawElements(). 
If you need to initialize multiple buffer objects, you will repeat steps 2 through 4 for each buffer object. 
Both “formats” of vertex-array data are available for use in buffer objects. As described in “Step 2: Specifying Data for the Arrays,” vertex, color, lighting normal, or any other type of associated vertex data can be stored in a buffer object. Additionally, interleaved vertex array data, as described in “Interleaved Arrays,” can also be stored in a buffer object. In either case, you would create a single buffer object to hold all of the data to be used as vertex arrays. 
As compared to specifying a memory address in the client’s memory where OpenGL should access the vertex-array data, you specify the offset in machine units (usually bytes) to the data in the buffer. To help illustrate computing the offset, and to frustrate the purists in the audience, we’ll use the following macro to simplify expressing the offset: 
#define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes))
[ *** ]
...

[ Making a Buffer Object Active ]

...
To make a buffer object active, it needs to be bound. Binding selects which buffer object future operations will affect, either for initializing data or using that buffer for rendering. That is, if you have more than one buffer object in your application, you’ll likely call glBindBuffer() multiple times: once to initialize the object and its data, and then subsequent times either to select that object for use in rendering or to update its data.
To disable use of buffer objects, call glBindBuffer() with zero as the buffer identifier. This switches OpenGL to the default mode of not using buffer objects.

void glBindBuffer(GLenum target, GLuint buffer);
Specifies the current active buffer object. target must be set to one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. buffer specifies the buffer object to be bound to. 
glBindBuffer() does three things: 
  1. When using buffer of an unsigned integer other than zero for the first time, a new buffer object is created and assigned that name.
  2. When binding to a previously created buffer object, that buffer object becomes the active buffer object.
  3. When binding to a buffer value of zero, OpenGL stops using buffer objects.
...

[ Allocating and Initializing Buffer Object with Data ]

...
Once you’ve bound a buffer object, you need to reserve space for storing your data. This is done by calling glBufferData().
void glBufferData(GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage); 
Allocates size storage units (usually bytes) of OpenGL server memory for storing vertex array data or indices. Any previous data associated with the currently bound object will be deleted. 
target may be either GL_ARRAY_BUFFER for vertex data; GL_ELEMENT_ARRAY_BUFFER for index data; GL_PIXEL_UNPACK_BUFFER for pixel data being passed into OpenGL; GL_PIXEL_PACK_BUFFER for pixel data being retrieved from OpenGL; GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER for data copied between buffers; GL_TEXTURE_BUFFER for texture data stored as a texture buffer; GL_TRANSFORM_FEEDBACK_BUFFER for results from executing a transform feedback shader; or GL_UNIFORM_BUFFER for uniform variable values. 
size is the amount of storage required for storing the respective data. This value is generally number of elements in the data multiplied by their respective storage size. 
data is either a pointer to a client memory that is used to initialize the buffer object or NULL. If a valid pointer is passed, size units of storage are copied from the client to the server. If NULL is passed, size units of storage are reserved for use, but are left uninitialized. 
usage provides a hint as to how the data will be read and written after allocation. Valid values are GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, GL_DYNAMIC_COPY. 
glBufferData() will generate a GL_OUT_OF_MEMORY error if the requested size exceeds what the server is able to allocate. It will generate a GL_INVALID_VALUE error if usage is not one of the permitted values.
glBufferData() first allocates memory in the OpenGL server for storing your data. If you request too much memory, a GL_OUT_OF_MEMORY error will be set. Once the storage has been reserved, and if the data parameter is not NULL, size units of storage (usually bytes) are copied from the client’s memory into the buffer object. However, if you need to dynamically load the data at some point after the buffer is created, pass NULL in for the data pointer. This will reserve the appropriate storage for your data, but leave it uninitialized. 
The final parameter to glBufferData(), usage, is a performance hint to OpenGL. Based upon the value you specify for usage, OpenGL may be able to optimize the data for better performance, or it can choose to ignore the hint. There are three operations that can be done to buffer object data: 
  1. Drawing—the client specifies data that is used for rendering.
  2. Reading—data values are read from an OpenGL buffer (such as the framebuffer) and used in the application in various computations not immediately related to rendering.
  3. Copying—data values are read from an OpenGL buffer and then used as data for rendering. 
Additionally, depending upon how often you intend to update the data, there are various operational hints for describing how often the data will be read or used in rendering: 
  1. Stream mode—you specify the data once, and use it only a few times in drawing or other operations.
  2. Static mode—you specify the data once, but use the values often.
  3. Dynamic mode—you may update the data often and use the data values in the buffer object many times as well.
...
[ *** ]

[ Updating Data Values in Buffer Objects ]

...
There are two methods for updating data stored in a buffer object: glBufferSubData() and glMapBufferRange()
The first method assumes that you have data of the same type prepared in a buffer in your application. glBufferSubData() will replace some subset of the data in the bound buffer object with the data you provide.

void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); 
Update size bytes starting at offset (also measured in bytes) in the currently bound buffer object associated with target using the data pointed to by data. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_PIXEL_PACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. 
glBufferSubData() will generate a GL_INVALID_VALUE error if size is less than zero or if size + offset is greater than the original size specified when the buffer object was created. 
The second method allows you more control over which data values are updated in the buffer.glMapBuffer() and glMapBufferRange() return a pointer to the buffer object memory, into which you can write new values (or simply read the data, depending on your choice of memory access permissions), just as if you were assigning values to an array. When you’ve completed updating the values in the buffer, you call glUnmapBuffer() to signify that you’ve completed updating the data. 
glMapBuffer() provides access to the entire set of data contained in the buffer object. This approach is useful if you need to modify much of the data in buffer, but may be inefficient if you have a large buffer and need to update only a small portion of the values.

GLvoid *glMapBuffer(GLenum target, GLenum access); 
Returns a pointer to the data storage for the currently bound buffer object associated with target, which must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. access must be either GL_READ_ONLY, GL_WRITE_ONLY, or GL_READ_WRITE, indicating the operations that a client may do on the data. 
glMapBuffer() will return NULL either if the buffer cannot be mapped (setting the OpenGL error state to GL_OUT_OF_MEMORY) or if the buffer was already mapped previously (where the OpenGL error state will be set to GL_INVALID_OPERATION). 
When you’ve completed accessing the storage, you can unmap the buffer by calling glUnmapBuffer().
GLboolean glUnmapBuffer(GLenum target); 
Indicates that updates to the currently bound buffer object are complete, and the buffer may be released. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. 
As a simple example of how you might selectively update elements of your data, we’ll use glMapBuffer() to obtain a pointer to the data in a buffer object containing three-dimensional positional coordinates, and then update only the z-coordinates. 
          GLfloat* data;
data = (GLfloat*) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);
if (data != (GLfloat*) NULL) {
    for( i = 0; i < 8; ++i ) {
        data[3*i+2] *= 2.0; /* Modify Z values */
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);
} else {
    /* Handle not being able to update data */
}
If you need to update only a relatively small number of values in the buffer (as compared to its total size), or small contiguous ranges of values in a very large buffer object, it may be more efficient to use glMapBufferRange(). It allows you to map only the range of data values you need.
GLvoid *glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
Returns a pointer into the data storage for the currently bound buffer object associated with target, which must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. offset and length specify the range to be mapped. access is a bitmask composed of GL_MAP_READ_BIT, GL_MAP_WRITE_BIT, which indicate the operations that a client may do on the data, and optionally GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT, GL_MAP_FLUSH_EXPLICIT_BIT, or GL_MAP_UNSYNCHRONIZED_BIT, which provide hints on how OpenGL should manage the data in the buffer. 
glMapBufferRange() will return NULL if an error occurs. GL_INVALID_VALUE is generated ifoffset or length are negative, or offset+length is greater than the buffer size. GL_OUT_OF_MEMORY error is generated if adequate memory cannot be obtained to map the buffer. GL_INVALID_OPERATION is generated if any of the following occur: The buffer is already mapped; access does not have either GL_MAP_READ_BIT or GL_MAP_WRITE_BIT set; accesshas GL_MAP_READ_BIT set and any of GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT, or GL_MAP_UNSYNCHRONIZED_BIT is also set; or both GL_MAP_WRITE_BIT and GL_MAP_FLUSH_EXPLICIT_BIT are set in access. 
Using glMapBufferRange(), you can specify optional hints by setting additional bits within access.These flags describe how the OpenGL server needs to preserve data that was originally in the buffer before you mapped it. The hints are meant to aid the OpenGL implementation in determining which data values it needs to retain, or for how long, to keep any internal copies of the data correct and consistent. 
As described in Table 2-7, specifying GL_MAP_FLUSH_EXPLICIT_BIT in the access flags when mapping a buffer region with glMapBufferRange() requires ranges modified within the mapped buffer to be indicated to the OpenGL by a call to glFlushMappedBufferRange()
GLvoid glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length);
Signal that values within a mapped buffer range have been modified, which may cause the OpenGL server to update cached copies of the buffer object. target must be one of the following: GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. offset and length specify the range of the mapped buffer region, relative to the beginning of the mapped range of the buffer. 
A GL_INVALID_VALUE error is generated if offset or length is negative or if offset+length is greater than the size of the mapped region. A GL_INVALID_OPERATION error is generated if there is no buffer bound to target (i.e., zero was specified as the buffer to be bound in a call to glBindBuffer() for target), or if the buffer bound to target is not mapped, or if it is mapped without having set the GL_MAP_FLUSH_EXPLICIT_BIT.
...

[ Cleaning Up Buffer Objecs ]

...
When you’re finished with a buffer object, you can release its resources and make its identifier available by calling glDeleteBuffers(). Any bindings to currently bound objects that are deleted are reset to zero.
void glDeleteBuffers(GLsizei n, const GLuint *buffers);

Deletes n buffer objects, named by elements in the array buffers. The freed buffer objects may now be reused (for example, by glGenBuffers()).

If a buffer object is deleted while bound, all bindings to that object are reset to the default buffer object, as if glBindBuffer() had been called with zero as the specified buffer object. Attempts to delete nonexistent buffer objects or the buffer object named zero are ignored without generating an error.
...
[ *** ]
[  ]
...

...



Samplers


___ To Be Continued...
___
___
___
URL: http://www.mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=9 (Tut source)

Now that we have data sent to GPU, we need to tell OpenGL how to filter the texture. Well, for those who remember OpenGL in older days (2.1 and below), we would do something like this to set filtering:
// Set magnification filter
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
// Set minification filter
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_LINEAR);
But not now. Now we are ready to move on. Problem of the above was, that if we wanted to use the same texture with different filteringswe could do it by constantly changing its parameters. Well it could be done somehow, but isn't there a nicer, more elegant way ? Yes there is - Samplers

[ Samplers ]

I couldn't find a definition of sampler on them internets , but I will try to explain it as easy as possible. Sampling is the process of fetching a value from a texture at a given position, so sampler is an object where we store info of how to do it. Like which texture to use and all filtering parameters. If we want to change filtering, we just bind different samplers with different propertiees, and we're done. This line is copied from spec: 

"If a sampler object is bound to a texture unit and that unit is used to sample from a texture, the parameters in the sampler are used to sample from the texture, rather than the equivalent parameters in the texture object bound to that unit."
One part of it basically says, that if a sampler is bound to the texture, its parameters supersedes texture parameters. So instead of setting texture parameters, we will create a sampler, which will do exactly this. Even though in this tutorial we create one sampler per one texture (so it's like without samplers), it's a more general solution and thus it's better. As all OpenGL objects, samplers are generated (we get their names), and then we access them with that name. So when loading texture, we just call glGenerateSamplers(), and then we set its parameters with our member function:

void  CTexture::setFiltering(int isTFMag, int isTFMin)
    // magnification filter setting
    if (Texture_Filter_Mag_Nearest == isTFMag)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Mag_Filter
                                           , GL_Nearest
        );
    else
    if (Texture_FIlter_Mag_Bilinear == isTFMag)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Mag_Filter
                                           , GL_Linear
        );
    //
    //--
    // minification filter setting
    if (Texture_FIlter_Min_Nearest == isTFMin )
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Min_Filter
                                           , GL_Nearest
        );
    else
    if (Texture_FIlter_Min_Bilinear == isTFMin)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Min_Filter
                                           , GL_Linear
        );
    else
    if (Texture_Filter_Min_Nearest_Mipmap == isTFMin)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Min_Filter
                                           , GL_Nearest_Mipmap_Nearest
        );
    else
    if (Texture_Filter_Min_Bilinear_Mipmap == isTFMin)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Min_Filter
                                           , GL_Linear_Mipmap_Nearest
        );
    else
    if (Texture_Filter_Min_Trilinear == isTFMin)
        glSamplerParameteri(m_idSampler
                                           , GL_Texture_Min_Filter
                                           , GL_Linear_Mipmap_Linear
        );
    //
    //----
    m_idTF_Minification = isTFMin;
    m_idTF_Magnification = isTFMag;

___
___
___


___
___
___



_________________________________________________________________________
supersede:
  1. to take the place or position of something that is less efficient, lessmodern, or less appropriate, or cause something to do this

Texture Filtering


___
___Conceptions First
___

[Filtering Conception]

Filtering is the process of accessing a particular sample from a texture. There are two cases for filtering: minification and magnification. Magnification means that the area of the fragment in texture space is smaller than a texel, and minification means that the area of the fragment in texture space is larger than a texel. Filtering for these two cases can be set independently.
The magnification filter is controlled by the GL_TEXTURE_MAG_FILTER texture parameter. This value can be GL_LINEAR or GL_NEAREST. If GL_NEAREST is used, then the implementation will select the texel nearest the texture coordinate; this is commonly called "point sampling". If GL_LINEAR is used, the implementation will perform a weighted linear blend between the nearest adjacent samples.
The minification filter is controlled by the GL_TEXTURE_MIN_FILTER texture parameter. To understand these values better, it is important to discuss what the particular options are.
[]

___
___
___
 http://www.mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=9 (Tut source)

When telling OpenGL texture data, we must also tell it, how to FILTER the texture. What does this mean? It's the way how OpenGL takes colors from image and draws them onto a polygon. Since we will probably never map texture pixel-perfect (the polygon's on-screen pixel size is the same as texture size), we need to tell OpenGL which texels (single pixels (or colors) from texture) to take. There are several texture filterings available. They are defined for both minification and magnification. What does this mean? Well, first imagine a wall, that we are looking straight at, and its screen pixel size is the same as our texture size (256x256), so that each pixel has a corresponding texel:
www.mbsoftworks.sk
In this case, everything is OK, there is no problem. But, if we moved closer to the wall, then we need to MAGNIFY the texture - because there are now more pixels on screen than texels in texture, we must tell OpenGL how to fetch the values from texture. In this case, there are two filterings:  
NEAREST FILTERING: GPU will simply take the texel, that is nearest to exactly calculated point. This one is very fast, as no additional calculations are performed, but it's quality is also very low, since multiple pixels have the same texels, and the visual artifacts are very bold. The closer to the wall you are, the more "squary" it looks (many squares with different colors, each square represents a texel). 

GL_NEAREST
BILINEAR FILTERING: This one doesn't only get the closest texel, but rather it calculates the distances from all 4 adjacent texels, and retrieves weighted average from them, depending on the distance. This results in a lot better quality than nearest filtering, but requires a little more computational time (on modern hardware, this time is negligible). Have a look at the pictures:

www.mbsoftworks.sk
As you can see, bilinear filtering gives us smoother results. You may wonder, that I have also heard of trilinear filtering. Soon, we'll get into that as well..The second case is, if we moved further from the wall. Now the texture is bigger than the screen render of our simple wall, and thus it must be MINIFIED. The problem is, that now multiple texels may correspond to single fragment. And what shall we do now? One solution may be to average all corresponding texels, but this may be really slow, as whole texture might potentionally fall into single pixel. The nice solution to this problem is called MIPMAPPING. The original texture is stored not only in its original size, but also downsampled to all smaller resolutions, with each coordinate divided by 2, creating a "pyramid" of textures (this image is from Wikipedia):
www.mbsoftworks.sk
Particular images are called mipmaps. With mipmapping enabled, GPU selects a mipmap of appropriate size, according to the distance we see object from, and then perform some filtering. This results in higher memory consumption (exactly by 33%, as sum of 1/4, 1/16, 1/256... converges to 1/3), but gives nice visual results at very nice speed. And here is another filtering term - TRILINEAR filtering. What's that? Well, it's the almost same as bilinear filtering, but addition to it is that we take two nearest mipmaps, do the bilinear filtering on each of them, and then average results. The name TRIlinear is from the third dimension that comes into it - in case of bilinear we were finding fragments in two dimensions, trilinear filtering extends this to three dimensions.
GL_LINEAR

___
___
___