Draw polygons above background image - opengl

My question is to draw a polygon or some other OpenGL primitives above or over a background image. Summarizing like paint in different layers, but in OpenGL i think there is no layers.
Now i'm doing some test trying to draw a triangle and a line over the background image.
To draw the background i use a square with OpenGL window size and then apply the png image in this square as a texture.
After that I try to paint the triangle and the line with different colors but I don't see anything except the background image.
I play with the alpha channel but i don't see anything.
Code:
void init()
{
// glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
// The following two lines enable semi transparent
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
int width, height;
bool hasAlpha;
char filename[] = "prueba-luz.png";
bool success = loadPngImage(filename, width, height, hasAlpha, &textureImage);
if (!success)
{
cout << "Unable to load png file" << endl;
return;
}
cout << "Image loaded " << width << " " << height << " alpha " << hasAlpha << endl;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, width,
height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE,
textureImage);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void display(void)
{
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // Igual que GL_REPLACE pero se le puede aplicar transparencias a la textura
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glColor4f(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glTexCoord2i(0,0); glVertex2i(10, -10);
glTexCoord2i(1,0); glVertex2i(-10, -10);
glTexCoord2i(1,1); glVertex2i(-10, 10);
glTexCoord2i(0,1); glVertex2i(10, 10);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glBegin(GL_POLYGON);
glColor4f(1.0, 1.0, 1.0, 0.8);
glVertex3f(-1.0f, -3.0f, 0.0f); // A
glVertex3f( 1.0f, -3.5f, 0.0f); // B
glVertex3f( 0.0f, 0.5f, 0.0f); // C
glEnd();
glBegin(GL_LINES);
glColor4f( 1.0, 0.0, 0.0, 0.8 );
glVertex2f(-8.0, 6.0);
glVertex2f (5.0, -3.0);
glEnd();
glutSwapBuffers();
}
How can i draw one image over the background image ???

Some things spotted :
Try to disable depth test. You are drawing everything at Z=0 and your application is definitely writing to the depth buffer. I'm not sure why you enable depth testing here since everything you draw is on Z=0.
By default all fragments written to the same or higher Z value will be discarded when depth testing is enabled. This can be changed with glDepthFunc (Default value GL_LESS). This is probably why your geometry is discarded in this example.
Drawing 2D geometry do not mean that the depth buffer will not be affected. OpenGL will draw this geometry with Z=0 and write that to your depth buffer.
Currently there is no reason for your application to use depth testing unless you draw your geometry on different z positions. You can use depth testing in 2D drawing to make "layers" by assigning different z values to each object.
A good practice for 2D drawing with z-culling is to draw the closes layer first, then draw the layers further in. This makes sure your write fewer fragments.
For example :
Z = 0 : Draw non-transparent overlays
Z = -1 : Draw stuff hidden behind the overlays
Z = -2 : Draw background
However, transparent objects need special rules.
You need to get control over your depth buffer. There are options :
glEnable/Disable(GL_DEPTH_TEST) : Enable or disable z-culling
glDepthMask(GL_TRUE/GL_FALSE) : Enable or disable writing to the the depth buffer
(glDepthFunc can be used to define how fragments are discarded)
Note here that the two first functions give you way more options than you might think
Depth culling and depth write when drawing objects
Depth culling, but your object do not affect the depth buffer
No depth culling, but your object will write to the depth buffer
No depth culling and no depth write
If you want to draw all your transparent objects in a last pass you can for example enable depth testing so the objects are not drawn on top your your overlays, but you disable depth writes because you want to be able to draw several overlapping objects in that layer.
Use your creativity and learn to love the depth buffer :D

Related

openGL, text changes when I load textures

I'm developing a C++ application and I need to use an interface made in openGL. I have a grey background, some squared textures over the background and some text written next to the textures. The text is yellow but when I click with mouse on the window or I change the textures, the text turns grey (a different grey from the background) and I don't know why! Here is the code and screenshots:
int main(int argc, char** argv){
[...]
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_FLAT);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
// Render the scene
glutDisplayFunc(display);
glutReshapeFunc(reshape);
// Turn the flow of control over to GLUT
glutMainLoop();
[...]
}
void display(void){
glClearColor(0.2f, 0.2f, 0.2f, 0.5f); //Background color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Set up viewing transformation, looking down -Z axis
glLoadIdentity();
gluLookAt(posx, 0, -g_fViewDistance, 0, 0, -1, 0, 1, 0);
// Render the scene
glMatrixMode(GL_COLOR);
glColor3f(1.0f, 1.0f, 0.0f); // Textcolor
drawOnScreen(); // Draw text on screen
glMatrixMode(GL_MODELVIEW);
loadSquare(); // Load texture
glutSwapBuffers();
}
void reshape(GLint width, GLint height){
interface->setWindowWidth(width);
interface->setWindowHeight(height);
glViewport(0, 0, g_Width, g_Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0, (float)g_Width / g_Height, g_nearPlane, g_farPlane);
glMatrixMode(GL_MODELVIEW);
}
void printStringOnVideo(void* font, char* s){
if (s && strlen(s)) {
while (*s) {
glutBitmapCharacter(font, *s);
s++;
}
}
}
void drawOnScreen(){
GLfloat x, y;
// Draw the strings, according to the current mode and font.
x = 2.90f;
y = 0.80f;
glRasterPos2f(x, y);
int len;
char s[] = { 'H', 'E', 'L', 'L', 'O', '\0' };
len = (int)strlen(s);
printStringOnVideo(GLUT_BITMAP_TIMES_ROMAN_24, s);
}
The loadSquare() function applies texture to squares. Its main feature is calling the class method for loading textures on squares:
void P300Square::setTexture(bool func){
// Se func = 0 allora carico la texture, viceversa il flash
string tmp = "";
if (func == false)
tmp = texturePath;
else
tmp = textureFlashPath;
GLuint texture = SOIL_load_OGL_texture
(
tmp.c_str(),
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glColor3ub(50, 50, 50);
glEnable(GL_BLEND);
glBegin(GL_QUADS);
glColor4f(0.5f, 0.0, 0.0f, 0.8f);
// Top Left
glTexCoord2f(0, 1);
glVertex2f(u, v);
// Top Right
glTexCoord2f(1, 1);
glVertex2f(u + size, v);
// Bottom Right
glTexCoord2f(1, 0);
glVertex2f(u + size, v + size);
// Bottom Left
glTexCoord2f(0, 0);
glVertex2f(u, v + size);
glEnd();
glDisable(GL_BLEND);
}
Can please someone help me? Thank you!
You should disable GL_TEXTURE_2D before you draw the bitmap font.
Internally, glutBitmapCharacter() uses glBitmap. This function maps the bitmap to a rectangle to the screen and generates a fragment for every framebuffer pixel in that rectangle where the bitmap is 1. Those fragments get the associated data from the values associated with the current raster position.
The generated fragments are processed like every other fragment (i.e. the ones generated by drawing primitives like lines or triangles). So stuff like texturing, lighting, fog, blending and so on will also affect everything drawn by glBitmap. Due to the fact that all fragments generated by a single bitmap get the same associated data, they all will get the same texture coordinate. Since you left texturing on, the GL textures all of these fragments with the very same sample from the texture, so that they all appear in the same color.

Drawing text onto an OpenGL surface using SDL

I'm using SDL, I have OpenGL rendering setup, I want to draw some text to the screen.
I found this question: Using SDL_ttf with OpenGL which seems to address the same concern, but I think my GL-fu isn't good enough to understand what to do next.
Ie, I have the texture from that other post, which, if I understand everything correctly, is an integer ID representing a GL texture that contains the rendered text. How do I actually render this texture onto my screen (everything's 2D here so I just want to render it as flat text on the screen, not onto some fancy surface in a 3D scene or anything).
Alternatively, is there any easier way of getting this working? (ie, rendering some text via SDL while also being able to render GL shapes)
edit: Or, even more generally, is there an easier way of being able to render both text and shapes onto the screen via SDL?
Use SDL_ttf to turn your string into a bitmap; this is just a single function call.
Use the code in the link you posted to turn it into a texture.
Draw a rectangle using said texture. That is, glBindTexture, glBegin, (glTexCoord, glVertex) x4, glEnd. If you have doubts about this step, you better go through some basic OpenGL tutorials (covering texture mapping, of course) first.
Try this snippet, it renders a SDL true type font extension library font starting from the bottom left side of the screen.
Note the arrangment of the texcords to the shape on the screen. The pixels from the text texture start 0,0 at the top left of the image. So I need to flip that around to make it show properly on a screen with x,y at the bottom left.
void RenderText(std::string message, SDL_Color color, int x, int y,
TTF_Font* font)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, gWindow->getWidth(),0,gWindow->getHeight());
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
SDL_Surface * sFont = TTF_RenderText_Blended(font, message.c_str(), color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sFont->w, sFont->h, 0, GL_BGRA,
GL_UNSIGNED_BYTE, sFont->pixels);
glBegin(GL_QUADS);
{
glTexCoord2f(0,1); glVertex2f(x, y);
glTexCoord2f(1,1); glVertex2f(x + sFont->w, y);
glTexCoord2f(1,0); glVertex2f(x + sFont->w, y + sFont->h);
glTexCoord2f(0,0); glVertex2f(x, y + sFont->h);
}
glEnd();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glDeleteTextures(1, &texture);
SDL_FreeSurface(sFont);
}

Set a image(jpeg | png) backgound using GLX ( opengl and Xlib)

I create a x11 window with opengl functionality, i need to load a image(jpeg | png) on its background where size of window be bigger than image, it doesn't matter. I surfed to get resylts like use DevIL or free image. I dont know which one to use. I set up the opengl window with the sample code given in a link to sample code and i there i want to write code in void renderGL() so as to make the image as background. Can you tell me which image library to use and provode the code if possible.
And also what is to be done to plot color pixels in opengl. i need a function to draw a pixel in a window , for which i have to provide the x,y pixel position and rgb color alone(unsigned int).....
I'm not much of a opengl programmer, but somehow i did this
and its workinh
ilInit(); /* Initialization of DevIL */
ilGenImages(1, &texid); /* Generation of one image name */
ilBindImage(texid); /* Binding of image name */
success = ilLoadImage(backgroundimage); /* Loading of image "image.jpg" */
iWidth = ilGetInteger(IL_IMAGE_WIDTH);
iHeight = ilGetInteger(IL_IMAGE_HEIGHT);
if (success){
success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); // Convert every colour component into unsigned byte,replace IL_RGB with IL_RGBA for alpha channel
}
glGenTextures(1, &image); /* Texture name generation */
glBindTexture(GL_TEXTURE_2D, image); /* Binding of texture name */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
ilGetData()); /* Texture specification */
glRotatef(roll, 0.0f,0.0f, 10.0f);
glOrtho(0.0, float(width), float(height), 0.0, 0.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); // Reset The Modelview Matrix
glBindTexture(GL_TEXTURE_2D, image); // Select The First Image Texture
glBegin(GL_QUADS);// Start Drawing A Textured Quad
glTexCoord2i(0, 0); glVertex2f(width/2-iWidth/2,height/2-iHeight/2);
glTexCoord2i(0, 1); glVertex2f(width/2-iWidth/2,height/2+iHeight/2);
glTexCoord2i(1, 1); glVertex2f(width/2+iWidth/2,height/2+iHeight/2);
glTexCoord2i(1, 0); glVertex2f(width/2+iWidth/2,height/2-iHeight/2);
glEnd();

How to draw transparent rubberband on OpenGL scene

i'm using OpenGL for showing grabbed frames from video camera with texture mapping. There is no problem at all but i have to select some region of the grabbed frame then i have to zoom it, first of all i can't draw a Rubber rectangle it must be transparent when i select the some region of grabbed frame i have to see textured frame transparently could you gimme some piece of code or clue, btw i'm showing grabbed frames like that any suggestion will be good for me...
void GLWidget::initializeGL()
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &m_pTextureId);
glBindTexture(GL_TEXTURE_2D, m_pTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void GLWidget::resizeGL(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1,1,-1,1,-1,1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void GLWidget::setTextureData(BYTE *data, int width, int height)
{
makeCurrent();
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
if (m_isTextured)
glTexSubImage2D(GL_TEXTURE_2D,0,0,0,width,height,GL_BGRA_EXT,GL_UNSIGNED_BYTE,data);
else
glTexImage2D(GL_TEXTURE_2D,0,3,width,height,0,GL_BGRA_EXT,GL_UNSIGNED_BYTE,0);
glBindTexture(GL_TEXTURE_2D,m_pTextureId);
glBegin(GL_QUADS);
glTexCoord2f(0.0,0.0);glVertex2f(-1.0,-1.0);
glTexCoord2f(0.0,1.0);glVertex2f(-1.0,1.0);
glTexCoord2f(1.0,1.0);glVertex2f(1.0,1.0);
glTexCoord2f(1.0,0.0);glVertex2f(1.0,-1.0);
glEnd();
swapBuffers();
}
I'm passing captured frame data to setTextureData it's working but i dunno does it good way ...
Thanks for reply #genpfault,
i used x1=0, y1=0, x2=1, y2=1 but it's drawing rectangle to all texture area. and draws 1 more rectangle to coordinates x1,y1... . How can i fix it. Btw how can i remove that rectangle ?, There is one more issue if i draw a rectangle then texture again rectangle going invisible ...
Just draw a translucent (alpha < 1.0) rectangle:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4ub(255, 255, 255, 128);
glRectf(x1, y1, x2, y2);
glDisable(GL_BLEND);

Shadows via shadowmaps and other textures - how to combine? OpenGL

Good day.
I draw a scene with shadows using shadow maps method (when we're rendering scene from light point of view to retrieve depth buffer, making shadow texture and projecting it on the scene, rendered from a camera point of view)
As I use shadowmap texture, all other textured objects, of course, lose their texturing.
But I really DO want textured scene with shadows:)
I read about multitexturing, I actually tried to apply it, but failed.
What exactly should I do?
(I took code from OpenGl superbible)
Here is the main setup procedure's code. I marked new strings (those for multitexturing) with //<====
void SetupRC()
{
ambientShadowAvailable = GL_TRUE;
npotTexturesAvailable = GL_TRUE;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize);
fprintf(stdout, "Controls:\n");
fprintf(stdout, "\tRight-click for menu\n\n");
fprintf(stdout, "\tx/X\t\tMove +/- in x direction\n");
fprintf(stdout, "\ty/Y\t\tMove +/- in y direction\n");
fprintf(stdout, "\tz/Z\t\tMove +/- in z direction\n\n");
fprintf(stdout, "\tf/F\t\tChange polygon offset factor +/-\n\n");
fprintf(stdout, "\tq\t\tExit demo\n\n");
// Black background
glClearColor(0.32f, 0.44f, 0.85f, 0.5f );
// Hidden surface removal
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glPolygonOffset(factor, 0.0f);
// Set up some lighting state that never changes
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHT0);
// Set up some texture state that never changes
glActiveTexture(GL_TEXTURE1); //<=====
glGenTextures(1, &shadowTextureID);
glBindTexture(GL_TEXTURE_2D, shadowTextureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
// if (ambientShadowAvailable)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB,
0.5f);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
::scene->fog->init();
RegenerateShadowMap();
}
Here is shadowmap generation procedure:
void RegenerateShadowMap(void)
{
GLfloat lightToSceneDistance, nearPlane, fieldOfView;
GLfloat lightModelview[16], lightProjection[16];
GLfloat sceneBoundingRadius = 200.0f; // based on objects in scene
// Save the depth precision for where it's useful
lightToSceneDistance = sqrt(lightPos[0] * lightPos[0] +
lightPos[1] * lightPos[1] +
lightPos[2] * lightPos[2]);
nearPlane = lightToSceneDistance - sceneBoundingRadius;
// Keep the scene filling the depth texture
fieldOfView = (GLfloat)m3dRadToDeg(2.0f * atan(sceneBoundingRadius / lightToSceneDistance));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fieldOfView, 1.0f, nearPlane, nearPlane + (2.0f * sceneBoundingRadius));
glGetFloatv(GL_PROJECTION_MATRIX, lightProjection);
// Switch to light's point of view
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(lightPos[0], lightPos[1], lightPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glGetFloatv(GL_MODELVIEW_MATRIX, lightModelview);
glViewport(0, 0, shadowWidth, shadowHeight);
// Clear the depth buffer only
glClear(GL_DEPTH_BUFFER_BIT);
// All we care about here is resulting depth values
glShadeModel(GL_FLAT);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_NORMALIZE);
glActiveTexture(GL_TEXTURE0); //<=====
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1); //<=====
glColorMask(0, 0, 0, 0);
// Overcome imprecision
glEnable(GL_POLYGON_OFFSET_FILL);
// Draw objects in the scene except base plane
// which never shadows anything
DrawModels(GL_FALSE);
// Copy depth values into depth texture
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
0, 0, shadowWidth, shadowHeight, 0);
// Restore normal drawing state
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glActiveTexture(GL_TEXTURE0); //<=====
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColorMask(1, 1, 1, 1);
glDisable(GL_POLYGON_OFFSET_FILL);
// Set up texture matrix for shadow map projection,
// which will be rolled into the eye linear
// texture coordinate generation plane equations
M3DMatrix44f tempMatrix;
m3dLoadIdentity44(tempMatrix);
m3dTranslateMatrix44(tempMatrix, 0.5f, 0.5f, 0.5f);
m3dScaleMatrix44(tempMatrix, 0.5f, 0.5f, 0.5f);
m3dMatrixMultiply44(textureMatrix, tempMatrix, lightProjection);
m3dMatrixMultiply44(tempMatrix, textureMatrix, lightModelview);
// transpose to get the s, t, r, and q rows for plane equations
m3dTransposeMatrix44(textureMatrix, tempMatrix);
}
Scene render proc:
void RenderScene(void)
{
// Track camera angle
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (windowWidth > windowHeight)
{
GLdouble ar = (GLdouble)windowWidth / (GLdouble)windowHeight;
glFrustum(-ar * cameraZoom, ar * cameraZoom, -cameraZoom, cameraZoom, 1.0, 1000.0);
}
else
{
GLdouble ar = (GLdouble)windowHeight / (GLdouble)windowWidth;
glFrustum(-cameraZoom, cameraZoom, -ar * cameraZoom, ar * cameraZoom, 1.0, 1000.0);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraPos[0], cameraPos[1], cameraPos[2],
0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
glViewport(0, 0, windowWidth, windowHeight);
// Track light position
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (showShadowMap)
{
// Display shadow map for educational purposes
glActiveTexture(GL_TEXTURE1); //<=====
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
// Show the shadowMap at its actual size relative to window
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(((GLfloat)shadowWidth/(GLfloat)windowWidth)*2.0f-1.0f,
-1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(((GLfloat)shadowWidth/(GLfloat)windowWidth)*2.0f-1.0f,
((GLfloat)shadowHeight/(GLfloat)windowHeight)*2.0f-1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f,
((GLfloat)shadowHeight/(GLfloat)windowHeight)*2.0f-1.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
gluPerspective(45.0f, 1.0f, 1.0f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
}
else if (noShadows)
{
// Set up some simple lighting
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
// Draw objects in the scene including base plane
DrawModels(GL_TRUE);
}
else
{
if (!ambientShadowAvailable)
{
GLfloat lowAmbient[4] = {0.1f, 0.1f, 0.1f, 1.0f};
GLfloat lowDiffuse[4] = {0.35f, 0.35f, 0.35f, 1.0f};
// Because there is no support for an "ambient"
// shadow compare fail value, we'll have to
// draw an ambient pass first...
glLightfv(GL_LIGHT0, GL_AMBIENT, lowAmbient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lowDiffuse);
// Draw objects in the scene, including base plane
DrawModels(GL_TRUE);
// Enable alpha test so that shadowed fragments are discarded
glAlphaFunc(GL_GREATER, 0.9f);
glEnable(GL_ALPHA_TEST);
}
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
// Set up shadow comparison
glActiveTexture(GL_TEXTURE1); //<=====
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
GL_COMPARE_R_TO_TEXTURE);
// Set up the eye plane for projecting the shadow map on the scene
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
glEnable(GL_TEXTURE_GEN_Q);
glTexGenfv(GL_S, GL_EYE_PLANE, &textureMatrix[0]);
glTexGenfv(GL_T, GL_EYE_PLANE, &textureMatrix[4]);
glTexGenfv(GL_R, GL_EYE_PLANE, &textureMatrix[8]);
glTexGenfv(GL_Q, GL_EYE_PLANE, &textureMatrix[12]);
// Draw objects in the scene, including base plane
DrawModels(GL_TRUE);
//glPushMatrix();
//glScalef(1, -1, 1);
//DrawModels(GL_TRUE);
//glPopMatrix();
glDisable(GL_ALPHA_TEST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_TEXTURE_GEN_Q);
}
if (glGetError() != GL_NO_ERROR)
fprintf(stderr, "GL Error!\n");
//glBindTexture
// Flush drawing commands
glutSwapBuffers();
//RegenerateShadowMap();
}
And an example of textured object draw:
CTeapot::CTeapot(std::string fn, float s, float iX, float iY, float iZ)
{
this->setCoords(iX, iY, iZ);
this->size = s;
glActiveTexture(GL_TEXTURE0); //<=====
try
{
this->texture = new C2DTexture(fn);
}
catch(ERR::CError err)
{
throw err;
}
glActiveTexture(GL_TEXTURE1); //<=====
}
void CTeapot::draw()
{
glPushMatrix();
glTranslatef(this->coords[0], this->coords[1], this->coords[2]);
if(this->angle[0] != 0.0f)
glRotatef(this->angle[0], 1.0f, 0.0f, 0.0f);
if(this->angle[1] != 0.0f)
glRotatef(this->angle[1], 0.0f, 1.0f, 0.0f);
if(this->angle[2] != 0.0f)
glRotatef(this->angle[2], 0.0f, 0.0f, 1.0f);
glScalef(this->size, this->size, this->size);
glActiveTexture(GL_TEXTURE0); //<=====
//glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, this->texture->getGLTexture());
glutSolidTeapot(this->size);
glPopMatrix();
glActiveTexture(GL_TEXTURE1); //<=====
//glEnable(GL_TEXTURE_2D);
}
C2DTexture texture generaton proc:
C2DTexture::C2DTexture(std::string fn)
{
this->filename = fn;
this->imgTexture = auxDIBImageLoad(this->filename.c_str());
if(this->imgTexture == NULL)
throw ERR::CError(ERR::ERR_NOSUCHFILE, ERR::ERR_NOSUCHFILETEXT + this->filename);
// Creating a texture
glGenTextures(1, &this->glTexture);
glBindTexture(GL_TEXTURE_2D, this->glTexture);
// Setting filters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, this->imgTexture->sizeX, this->imgTexture->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, this->imgTexture->data);
}
You tried to apply multi-texturing ? It does not show in your code. You do need to use it. One texture unit for the shadow texture, one for your diffuse map. If you tried, you should show the code with multi-texturing.
Multi-texturing is handled through glActiveTexture (and for fixed function that you seem to be using, glClientActiveTexture to handle the texture coordinates specifications).
Some pieces of advice:
it's easier to understand exactly what you're doing if you use shaders.
you want to map the depth texture to the texture unit 1: the setup of the texture unit for shadow mapping needs to be preceded by a glActiveTexture(GL_TEXTURE1) -- the BindTexture, the TexGen, and the texturing related Enable/Disable. Of course, you need to switch back to the texture unit 0 for the rest.
you don't want any texturing when you draw to the depth map.
It is faster to draw directly to the texture with the framebuffer_object extension, than to copy to it
Hope this helps.
Edit: Since you've changed quite a bit your question, let me add some pieces of advice and answers to your comments:
A single texture unit will always fetch from a single texture object. You use glActiveTexture followed by glBindTexture to specify which texture will be fetched from on that texture unit. Note that to get any texturing on that unit, you still need to call glEnable(GL_TEXTURE_2D) for that unit.
What to apply first... Well, this is where using shaders simplifies quite a lot the discussion. In general, the order of application completely depends on what fragment math you want to end up with. Let's put the following nomenclature:
T_0 the result of the first texture fetch,
T_1 the result of the second texture fetch.
C_f The input color that OpenGL computed and rasterized for this fragment (You're using the fixed function lighting, that's what I'm talking about)
C_o The final color of the fragment
T_s the result of the shadow texture fetch,
T_d the result of the diffuse texture fetch.
The result you'll get, with 2 texture units enabled, is something like
C_o = TexEnv1(TexEnv0(C_f,T_0), T_1)
The result you want is likely
C_o = C_f * T_s * T_d
What does that tell us ?
to implement the multiplications, you want modulate as your TexEnv for both texture unit 0 and texture unit 1
the order does not matter in this case (this is because the multiplication -aka modulation- is commutative)
what I showed is pretty much shader code. A lot easier to read than TexEnv settings.
Now to get back to your problem... At this point, I hope you understand what OpenGL state you should have come draw time. However, trying to know exactly what state you actually have from reading your code is a perilous exercise at best. If you are serious about using OpenGL, I recommend either of the following:
use an OpenGL debugger. There are a number of tools out there that will show the exact state at a specific draw call.
build your own debugging state tracking
dump the OpenGL state of interest at the time of the draw. OpenGL provides getter methods for every bit of its state (or almost, I won't go into the dirtiest details here), You want to do that only for debugging purposes, Getters are not guaranteed to be efficient at all).