Sign in to follow this  
PAndersson

OpenGL Cube map troubles

Recommended Posts

PAndersson    394
Hey all, I'm having a bit of trouble trying to get a cubemap to work with OpenGL and GLSL. It seems to upload it just fine, at least GlIntercept outputs the cubemap texture in the way I would expect it too. However, when I try to sample the texture all I seem to get is just plain black no matter which coordinates I use to sample. The source texture has essentially no black at all.

I have been tearing my hair over this for the past few days and I'm wondering if any of you could spot the likely stupid mistake I've made?

Texture loading code:
[source lang="cpp"]namespace
{

SDL_Surface* createCubeMapFace(SDL_Surface* in, int faceStartX, int faceStartY, int width, int height)
{
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
SDL_Surface* bufferSurface = SDL_CreateRGBSurface(0, width, height, 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);

#else
SDL_Surface* bufferSurface = SDL_CreateRGBSurface(0, width, height, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
#endif

SDL_Rect rect;

rect.w = width;
rect.h = height;
rect.x = faceStartX;
rect.y = faceStartY;

SDL_Rect dest;
dest.x = 0;
dest.y = 0;

SDL_FillRect(bufferSurface, &dest, SDL_MapRGBA(bufferSurface->format, 0, 0xFF, 0, 0xFF));
SDL_BlitSurface(in, &rect, bufferSurface, &dest);

return bufferSurface;

}

void uploadCubeMapFace(GLenum cubeMapFace, SDL_Surface* face, bool generateMipMaps)
{
glTexImage2D(cubeMapFace, 0, GL_RGBA, face->w, face->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, face->pixels );
tryLogError();
if (generateMipMaps) gluBuild2DMipmaps(cubeMapFace, GL_RGBA, face->w , face->h, GL_RGBA,GL_UNSIGNED_BYTE, face->pixels);
tryLogError();
}

GLuint uploadFaceSet(SDL_Surface*left,
SDL_Surface* front,
SDL_Surface* right,
SDL_Surface* far,
SDL_Surface* top,
SDL_Surface* bottom,
bool mipmapped)
{

GLuint id;
glGenTextures(1, &id);

glEnable(GL_TEXTURE_CUBE_MAP);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);
tryLogError();

// Upload texture
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

//Create cube map
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, left, mipmapped);
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, front, mipmapped);
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X, right, mipmapped);
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, far, mipmapped);
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, top, mipmapped);
uploadCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, bottom, mipmapped);

glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return id;
}
// Loads a Texture into VideoRAM and returns a texture id
GLuint loadCubeMapTextureIntoVRAM(Image* image, bool generateMipMaps)
{

assert(image->getWidth() % 4 == 0);
assert(image->getHeight() % 3 == 0);
assert(image->getWidth()/4 == image->getHeight()/3);

int sideWidth = image->getWidth()/4;
int sideHeight = image->getHeight()/3;

auto left = createCubeMapFace(image->getInternalSurface(), sideWidth*0, sideHeight*1, sideWidth, sideHeight);
auto front = createCubeMapFace(image->getInternalSurface(), sideWidth*1, sideHeight*1, sideWidth, sideHeight);
auto right = createCubeMapFace(image->getInternalSurface(), sideWidth*2, sideHeight*1, sideWidth, sideHeight);
auto far = createCubeMapFace(image->getInternalSurface(), sideWidth*3, sideHeight*1, sideWidth, sideHeight);
auto top = createCubeMapFace(image->getInternalSurface(), sideWidth*1, sideHeight*0, sideWidth, sideHeight);
auto bottom = createCubeMapFace(image->getInternalSurface(), sideWidth*1, sideHeight*2, sideWidth, sideHeight);

auto retVal = uploadFaceSet(left,
front,
right,
far,
top,
bottom,
generateMipMaps);
SDL_FreeSurface(left);
SDL_FreeSurface(front);
SDL_FreeSurface(right);
SDL_FreeSurface(far);
SDL_FreeSurface(top);
SDL_FreeSurface(bottom);

return retVal;

}
}[/source]

Code used to sent the cubemap id to the shader program, I have checked that the id is correct and that the part of the of the code is executed as it should as well as having a unique sampler number.

[source lang="cpp"]void ShaderProgram::setTexture(String variableName, int samplerNo, ICubeMap* texture)
{
assert(this->programId == activeProgram);
assert(samplerNo >= 0);


glEnable(GL_TEXTURE_CUBE_MAP);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture->getOpenGLId());

glActiveTexture(GL_TEXTURE0 + samplerNo);

GLuint loc = glGetUniformLocation(this->programId, variableName.getStringUtf8());
glUniform1i(loc, samplerNo);
}[/source]

Finally, the minimimalistic test fragment shader:

[source lang="cpp"]#version 330

uniform samplerCube cubeMapTexture;

in vec4 rawNormal;

out vec4 fragmentColour;

void main(void)
{
fragmentColour = texture(cubeMapTexture, vec3(rawNormal.xyz));

}[/source]
The vertex shader works as it should, if I hard set the colour in the fragment shader the object appears as expected.

I would be thankful for any help.

Share this post


Link to post
Share on other sites
Brother Bob    10344
I am not sure about this, but I believe gluBuild2DMipmaps does not accept cube map faces as texture targets and thus cannot build cube map faces. If this is the case, then your call to gluBuild2DMipmaps will fail and thus leave the texture object in an incomplete, and therefore invalid, state since you have specified the minification filtering as a mipmap filter but only provided the base level texture. Either don't use mipmap filtering, or generate your mipmaps with the current glGenerateMipmap function instead.

Share this post


Link to post
Share on other sites
PAndersson    394
[quote name='Brother Bob' timestamp='1353707858' post='5003587']
I am not sure about this, but I believe gluBuild2DMipmaps does not accept cube map faces as texture targets and thus cannot build cube map faces. If this is the case, then your call to gluBuild2DMipmaps will fail and thus leave the texture object in an incomplete, and therefore invalid, state since you have specified the minification filtering as a mipmap filter but only provided the base level texture. Either don't use mipmap filtering, or generate your mipmaps with the current glGenerateMipmap function instead.
[/quote]

Looking at the documentation, you seem to be correct. Though removing any reference to mipmaps (the function and the filtering methods set to just GL_LINEAR instead) does not seem to correct the issue though. All samples are still pure black.

Share this post


Link to post
Share on other sites
Brother Bob    10344
I don't see anything obvious other than what I mentioned. Check for errors codes to see if anything is wrong. Keep in mind that some functions indicate errors by return value instead of an error state from glGetError, such as querying a uniform location, so make sure you check return values for functions as well.

Share this post


Link to post
Share on other sites
PAndersson    394
[quote name='Brother Bob' timestamp='1353709872' post='5003594']
I don't see anything obvious other than what I mentioned. Check for errors codes to see if anything is wrong. Keep in mind that some functions indicate errors by return value instead of an error state from glGetError, such as querying a uniform location, so make sure you check return values for functions as well.
[/quote]

I should have done it from the beginning, especially as I usually program fairly defensivly. But I went and added error checking to all OpenGL calls and it seems that the shader program is unable to find the cubemap sampler. Strange, it is used so it should not be optimized away and I double checked the name after discovering this. No trouble there, are there any known causes for this issue?

Edit: Nevermind, was reporting for a different shader program. It finds it just fine for this, but still black an no clear errors... Edited by PAndersson

Share this post


Link to post
Share on other sites
PAndersson    394
If I write this shader:

[source lang="cpp"]uniform samplerCube cubeTest;
uniform samplerCube terrainNoiseTexture;

void main(void)
{
fragmentColour.rbg = texture(terrainNoiseTexture, vec3(rawNormal.xyz)).rrr;
fragmentColour.rbg += texture(cubeTest, vec3(rawNormal.xyz)).rrr;
fragmentColour.a = 1;
}[/source]

I can suddenly read from the black cubemap as expected....

Maybe I just should update my drivers...
Still nothing. So what could cause a cubemap to be all blick until I sample another cubemap first? Edited by PAndersson

Share this post


Link to post
Share on other sites
PAndersson    394
[quote name='Brother Bob' timestamp='1353757833' post='5003718']
So if you use that exact code and just comment out one of the two texture samplers, then it stops working? Reduce your application to an absolute minimum and show the complete code.
[/quote]

All right, have not had any more success with this (to be fair, not a lot of time to work on it either) so I will see what I can do. The application currently uses A LOT of infrastructure and getting rid of that will be a major effort...

Share this post


Link to post
Share on other sites
PAndersson    394
Finally got some more time to look into the issue and managed to find and solve the problem.

The setTexture method should look like this:

[source lang="cpp"] void ShaderProgram::setTexture(String variableName, int samplerNo, ICubeMap* texture)
{
assert(this->programId == this->activeProgram);
assert(samplerNo >= 0);


//Prepere texture
glCheckedCall( glActiveTexture(GL_TEXTURE0 + samplerNo) );

glCheckedCall( glEnable(GL_TEXTURE_CUBE_MAP) );
glCheckedCall( glBindTexture(GL_TEXTURE_CUBE_MAP, texture->getOpenGLId()) );


GLint loc = glCheckedCall( glGetUniformLocation(this->programId, variableName.getStringUtf8()) );
if (loc < 0) syslog.Error(String("Failed to find uniform cubemap name \"") + variableName + "\" in program " + this->getProgramID());
glCheckedCall( glUniform1i(loc, samplerNo) );

}[/source]
As in my previous post, I bound the texture before activating it thus effectivly messing with other texture units. Simply swapping the order in which the function calls are made solved everything.

Thank you for your help, and this just cements my sentiment that state-based interfaces are evil :P Edited by PAndersson

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By Zaphyk
      I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?
    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      Question:
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
       
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
       
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
  • Popular Now