I am working with openGL quad buffer to render stereo 3D images (and I am very new to openGL).
I came across a question on how to define the output texture for each back buffer, which I supose is done in the fragment buffer by defining the output color (corresponding to a specified texture).
This is the code I am using for the shader sources:
// Shader sources
const GLchar* vertexSource =
"#version 150 core\n"
"in vec2 position;"
"in vec3 color;"
"in vec2 texcoord;"
"out vec3 Color;"
"out vec2 Texcoord;"
"void main() {"
" Color = color;"
" Texcoord = texcoord;"
" gl_Position = vec4(position, 0.0, 1.0);"
"}"; // Vertex buffer source
const GLchar* fragmentSource =
"#version 150 core\n"
"in vec3 Color;"
"in vec2 Texcoord;"
"out vec4 outColor;"
"uniform sampler2D texRight;"
"uniform sampler2D texLeft;"
"void main() {"
" outColor = texture(texRight, Texcoord);"
" outColor = texture(texLeft, Texcoord);"
"}"; // Fragment buffer source
This is the code I am using to fill the back buffers, that I use in the display function for the freeglut context window.
// Clear Buffers
glDrawBuffer(GL_BACK);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f,1.0f);
cudaGLMapBufferObject((void**)d_glpointer, pbo);
cudaGLMapBufferObject((void**)d_glpointer, pbo_Right);
//...
// Unmap buffer object
cudaGLUnmapBufferObject(pbo);
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo);
glDrawBuffer(GL_BACK_LEFT);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texturesID[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE,NULL); // NULL specifies that the image is in memory
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glUniform1i(glGetUniformLocation(shaderProgram, "texLeft"), 1);
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
// Unmap buffer object
cudaGLUnmapBufferObject(pbo_Right);
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo_Right);
// Draw Back Buffers
glDrawBuffer(GL_BACK_RIGHT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texturesID[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE,NULL); // NULL specifies that the image is in memory
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glUniform1i(glGetUniformLocation(shaderProgram, "texRight"), 0);
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
// Swap buffers
glutSwapBuffers();
By using this code I am able to see only the last outcolor defined, but I was not able to figure out a functional way to choose between the outColor definition depending on the buffer I am using.
I am using Cuda to put the images in memory, but the problem doesn't seem related to this mapping, since I am always able to see the image associated with texture defined last in the shader's outcolor.
I'll appreciate some help on figuring this out.
Edit 1:
I added a counter to the shader that verifies if the frame count (texCount) is even or odd. Although, I have no output image now.
#version 150 core
in vec3 Color;
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D texRight;
uniform sampler2D texLeft;
uniform int texCount=1;
void main() {
if (texCount%2){ // if texCount division by two is exact then this is false
outColor = texture(texLeft, Texcoord);
}else{
outColor = texture(texRight, Texcoord);
}
texCount++;
}
I think the following should work.
The new fragment shader:
#version 150 core in vec3 Color;
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D texIndex;
void main() {
outColor = texture(texIndex, Texcoord);
}
Then replace ”texLeft” and ”texRight” in your code by ”texIndex”.
Note that you shouldn't have to upload the textures at each frame if they are static. Ideally, you would put all the commands that need to be executed only once in a setup function, which you would execute only when the OS notify a window reshape.
Related
I'm trying to render font on screen using freetype. For that, I implemented single channel texture but it always samples 0.
cpp
unsigned char *blankData = new unsigned char[8 * 8];
for(int i = 0; i < 8 * 8; i++){
blankData[i] = 126;
}
glActiveTexture(GL_TEXTURE0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GLuint m_texture2D;
glGenTextures(1, &m_texture2D);
glBindTexture(GL_TEXTURE_2D, m_texture2D);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 8, 8, 0, GL_RED, GL_UNSIGNED_BYTE, blankData);
glUniform1i(glGetUniformLocation(m_program, "texture2D"), 0);
checkGLError();
glGetError() returns GL_NO_ERROR
fragment Shader
#version 330 core
in vec2 texCoord;
in vec4 color;
uniform sampler2D texture2D;
out vec4 outColor;
void main()
{
vec4 texColor = texture(texture2D, texCoord);
outColor = vec4(texColor.r, texColor.r, texColor.r, 1.0f);
}
result
ff00ff: clear color
black: fragment shader output texcoord bottomLeft(0, 0) to topRight(1, 1)
If you are not generating mipmaps (with glGenerateMipmap) it is important to set GL_TEXTURE_MIN_FILTER. Since the default filter is GL_NEAREST_MIPMAP_LINEAR, the texture would be "Mipmap Incomplete" if you do not change the minimize function to GL_NEAREST or GL_LINEAR.
glBindTexture(GL_TEXTURE_2D, m_texture2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
I'm trying to texture a tube object in OpenGL, for a project, and a have problem texturing it. The texture is coming up nicely but there is a white line in the middle of the back of the tube that I can't get rid of. I'm using standard texture class that I build from a tutorial that I read. the mesh and the texture are upload normally- meaning nothing is unusual.
Back of the tube
Front of the tube
Texture::Texture(const std::string& fileName)
{
int width, height, numComponents;
unsigned char* data = stbi_load((fileName).c_str(), &width, &height, &numComponents, 4);
if (data == NULL)
std::cerr << "Unable to load texture: " << fileName << std::endl;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
Texture::~Texture()
{
glDeleteTextures(1, &m_texture);
}
void Texture::Bind()
{
glBindTexture(GL_TEXTURE_2D, m_texture);
}
#version 130--fragment shader
varying vec2 texCoord0;
varying vec3 normal0;
varying vec3 color0;
uniform sampler2D ourTexture1; // added
uniform vec3 lightDirection;
uniform vec3 MinMax;
void main()
{
//vec3 tmp = dot(-lightDirection, normal0) * color0 ;44
gl_FragColor = texture(ourTexture1, texCoord0);
if(color0.y<MinMax.x||color0.y>MinMax.y)
gl_FragColor=vec4(1.0,1.0,1.0,1.0);
}
#version 120-vertex shader
attribute vec3 position;
attribute vec2 texCoord;
attribute vec3 normal;
attribute vec3 color;
varying vec2 texCoord0;
varying vec3 normal0;
varying vec3 color0;
uniform mat4 MVP;
uniform mat4 Normal;
void main()
{
gl_Position = MVP * vec4(position, 1.0);
texCoord0 = texCoord;
texCoord0[0]=0.25+texCoord0[0];
if(texCoord0[0]>=1)
{
texCoord0[0]=texCoord0[0]-1;
}
texCoord0[1]=1-texCoord0[1];
color0 = position;
normal0 = (Normal * vec4(normal, 0.0)).xyz;
}
The problem almost certainly comes from the following part of your vertex shader:
texCoord0[0]=0.25+texCoord0[0];
if(texCoord0[0]>=1)
{
texCoord0[0]=texCoord0[0]-1;
}
I'm not entirely sure what you are trying to accomplish with this, but it will cause neighbouring vertices to have values that are very far appart, which means that almost the entire texture gets squeezed in between these two vertices.
Normally, you would want to just apply the offset, and let the rendering pipeline take care of of the modulus operation. So I would have expected to just see this:
texCoord0[0]=0.25+texCoord0[0];
N.B.
You might still see the issue if you are sharing vertices accross the the entire circumference of the tube. The point of the mesh where the texture coordinate "loops" around should have duplicated vertices with different UVs.
stbi_uc* data = stbi_load(path, &width, &height, NULL, 4);
if (data == NULL) {
return false;
}
gl_flush_errors();
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D_ARRAY, id);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA, 50, 50, 1);
This is the portion of my code where the INVALID_ENUM error is coming from, which I've narrowed down to the glTexStorage3D call. I'm also experiencing an INVALID_VALUE error directly after this block of code with:
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_CLAMP_TO_EDGE);
My goal here is to set up a texture array with my working tile instancing so I can render my tilemap in one draw call. I'm experiencing the same issue as here:
Instanced drawing with texture atlas
However, I'm not sure if I'm doing this correctly at the moment so any help or direction would be appreciated. These are my shaders as well in case they're the cause of the issue:
Fragment Shader
#version 330
// From vertex shader
in vec2 uvcoord;
// Application data
uniform sampler2DArray textures;
// uniform vec3 fcolor;
// Output color
layout(location = 0) out vec4 color;
void main()
{
color = texture(textures, vec3(uvcoord.x, uvcoord.y, 0.0));
}
Vertex Shader
#version 330
// Input attributes
in vec2 in_position;
in vec2 in_uvcoord;
in vec2 in_centre_pos;
// Passed to fragment shader
out vec2 uvcoord;
out vec2 vpos;
// Application data
uniform mat3 transform;
uniform mat3 projection;
void main()
{
uvcoord = in_uvcoord;
vpos = in_position;
vec3 pos = projection * vec3(in_position.x + in_centre_pos.x, in_position.y + in_centre_pos.y, 1.0);
gl_Position = vec4(pos.x, pos.y, 0.0, 1.0);
}
OpenGL 4.6 API Core Profile Specification; 8.19. IMMUTABLE-FORMAT TEXTURE IMAGES; page 272:
The TexStorage* commands specify properties of the texture object bound to the target parameter of each command.
.....
Errors
An INVALID_ENUM error is generated if internalformat is one of the unsized base internal formats listed in table 8.11.
This means it is not allowed to use GL_RGBA for the 3rd paramter of glTexStorage3D.
Use GL_RGBA8 instead:
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, 50, 50, 1);
You specified OpenGL 3.2, in this version function glTexStorage3D does not exist. Use glTexImage3D, which works with GL_RGBA instead of sized format GL_RGBA8 required by storage functions.
I'm currently trying to implement deferred shading in OpenGL 3.2 and have a problem that I just can't seem to solve no matter what I try.
I implemented it in two steps(geometry pass and lighting pass) like one would expect. After compiling and running it the screen shows the scene I prepared almost like one would expect it to look like. The colors of the objects are correct and they are also positioned where and how I wanted them to be.
The thing is, that the light calculations seem to have no influence on the color, what so ever. After a lot of hours I found out, that the textures for the positions and normals seem to contain the same content like the color texture.
If one changes the last line in the lighting fragment shader from fragColor = lightIntensity * color; to fragColor = lightIntensity * norm; or fragColor = lightIntensity * pos; it has absolutely no impact on how the screen is rendered.
I have tried a lot to figure out what is going wrong but honestly have no idea what it could be.
It would be awesome if someone could help me.
My render method looks like this:
void render()
{
//geometry pass
gBuffer->bindForWriting();
geometryShader->use(true);
calculateGBuffer();
//lighting pass
gBuffer->bindForReading(lightShader->programID());
lightShader->use(true);
drawOnScreen();
}
The initialization of the gBuffer object is like this:
void GBuffer::initializeFBO(int viewWidth, int viewHeight)
{
//initialize fbo and corresponding textures;
glGenFramebuffers(1, &fbo_ID);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_ID);
glGenTextures(1, &colorTexture_ID);
glBindTexture(GL_TEXTURE_2D, colorTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, viewWidth, viewHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture_ID, 0);
glGenTextures(1, &posTexture_ID);
glBindTexture(GL_TEXTURE_2D, posTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, viewWidth, viewHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, posTexture_ID, 0);
glGenTextures(1, &normTexture_ID);
glBindTexture(GL_TEXTURE_2D, normTexture_ID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, viewWidth, viewHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, normTexture_ID, 0);
GLuint attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
glGenRenderbuffers(1, &depthBuffer_ID);
glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer_ID);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, viewWidth, viewHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer_ID);
//Check Status
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
qDebug() << "error while initializing framebuffer" << glCheckFramebufferStatus(GL_FRAMEBUFFER);
else{
qDebug() << "framebuffer successfully created";
initialized = true;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
The methods bindForReading and bindForWriting:
void GBuffer::bindForWriting()
{
glBindFramebuffer(GL_FRAMEBUFFER, fbo_ID);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void GBuffer::bindForReading(GLuint programID)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, colorTexture_ID);
GLuint samplerTexture_ID = glGetUniformLocation(programID, "colorTexture");
glUniform1i(samplerTexture_ID, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, posTexture_ID);
samplerTexture_ID = glGetUniformLocation(programID, "positionTexture");
glUniform1i(samplerTexture_ID, 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, normTexture_ID);
samplerTexture_ID = glGetUniformLocation(programID, "normTexture");
glUniform1i(samplerTexture_ID, 2);
}
And at last the 4 Shaders:
Geometry Vertex Shader:
#version 150
#extension GL_ARB_separate_shader_objects : enable
uniform mat4 MVPMatrix;
uniform mat4 modelMatrix;
in vec4 in_position;
in vec4 in_color;
in vec2 in_texcoord;
in vec3 in_norm;
out vec4 color_varying;
out vec3 frag_position;
out vec3 norm_vec;
out vec2 texcoord_varying;
void main()
{
gl_Position = MVPMatrix * in_position;
vec4 worldPosition = (modelMatrix * in_position);
frag_position = worldPosition.xyz;
norm_vec = in_norm;
color_varying = in_color;
texcoord_varying = in_texcoord;
}
Geometry Fragment Shader:
#version 150
#extension GL_ARB_explicit_attrib_location : enable
in vec4 color_varying;
in vec3 frag_position;
in vec3 norm_vec;
in vec2 texcoord_varying;
layout (location = 0) out vec4 fragColor;
layout (location = 1) out vec3 fragPosition;
layout (location = 2) out vec3 frag_norm_vec;
uniform sampler2D myTexture;
void main()
{
vec4 texel = texture(myTexture, texcoord_varying);
fragColor = texel * color_varying;
fragPosition = frag_position;
frag_norm_vec = normalize(norm_vec);
}
Lighting VertexShader:
#version 150
#extension GL_ARB_explicit_attrib_location : enable
layout (location = 0) in vec2 in_position;
out vec2 texCoord;
void main()
{
gl_Position = vec4(in_position, 0, 1.0f);
texCoord = in_position;
if(texCoord.x == -1.0f)
texCoord.x = 0.0f;
if(texCoord.y == -1.0f)
texCoord.y = 0.0f;
}
Lighting Fragment Shader(without lighting calculation to make it shorter)
#version 150
#extension GL_ARB_separate_shader_objects : enable
out vec4 fragColor;
in vec2 texCoord;
uniform sampler2D colorTexture;
uniform sampler2D positionTexture;
uniform sampler2D normTexture;
void main()
{
//extract fragment data from fbo
vec3 pos = texture(positionTexture, texCoord).rgb;
vec3 norm = texture(normTexture, texCoord).rgb;
vec4 color = texture(colorTexture, texCoord);
fragColor = lightIntensity * color;
}
Sry for the code spamming but I can't narrow down the error.
The problem is most likely in your order of operations here:
gBuffer->bindForReading(lightShader->programID());
lightShader->use(true);
where, in bindForReading(), you have calls like this one:
samplerTexture_ID = glGetUniformLocation(programID, "positionTexture");
glUniform1i(samplerTexture_ID, 1);
The glUniform*() calls set uniform values on the currently active program. Since you make the lightShader active after you make these calls, the uniform values will be set on the previously active program, which probably doesn't even have these uniforms.
Simply changing the order of these calls might already fix this:
lightShader->use(true);
gBuffer->bindForReading(lightShader->programID());
Also, you're using GL_RGB16F as the format of two of your buffers. The OpenGL implementation you use may support this, but this is not a format that is required to be color-renderable in the spec. If you want your code to work across platforms, you should use GL_RGBA16F, which is guaranteed to be color-renderable.
I made an application which renders skybox and particles over it. I want to add some effects and i need to use framebuffers to render skybox, particles color, depth and position to separate textures. Then i want to use simple shader to use values from these textures and mix them in a proper way. I wrote helper classes for textures, framebuffers and screen quad (simple rectangle to render) but unfortunately - nothing renders when i try to use it.
When binding framebuffers is commented out, my scene looks like this:
Modifying shader shows that depth and position values are calculated properly. Therefore problem lays in texture and framebuffers way of using. Time for some code:
Framebuffer helper class (only important methods):
void Framebuffer::init(){
// unbind all textures from openGL
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &framebuffer);
}
void Framebuffer::bind(){
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
}
void Framebuffer::unbind(){
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Framebuffer::attachTexture(GLuint texture, GLenum attachmentType){
glBindTexture(GL_TEXTURE_2D, texture);
glFramebufferTexture(GL_FRAMEBUFFER, attachmentType, texture, 0);
}
void Framebuffer::drawBuffers(GLsizei n, const GLenum *buffers){
glDrawBuffers(n, buffers);
}
Texture helper class:
void Texture::init(GLuint windowWidth, GLuint windowHeight, GLint internalFormat, GLenum format, GLenum type){
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texture);
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);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D( GL_TEXTURE_2D, 0, internalFormat , windowWidth, windowHeight, 0, format, type, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::bind(){
glBindTexture(GL_TEXTURE_2D, texture);
}
void Texture::unbind(){
glBindTexture(GL_TEXTURE_2D, 0);
}
GLuint Texture::getId(){
return texture;
}
ScreenQuad class:
void ScreenQuad::init(void){
vao.createVAO();
vao.bindVAO();
vbo.createVBO();
vbo.addData(vertices, 8*sizeof(GLfloat));
vbo.bindVBO(GL_ARRAY_BUFFER);
vbo.uploadDataToGPU(GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)3, 2, GL_FLOAT, GL_FALSE, 0, NULL);
loadShaders("shaders/basicPostShader.vp", "shaders/basicPostShader.fp");
}
void ScreenQuad::loadShaders(string vsPath, string fsPath){
shaderProgram.createProgram();
shaderProgram.loadVertexShader(vsPath);
shaderProgram.loadFragmentShader(fsPath);
glBindAttribLocation(shaderProgram.getProgramID(), 3, "v_coord");
shaderProgram.linkProgram();
}
void ScreenQuad::draw(GLuint depthTexture, GLuint colorTexture, GLuint positionTexture, GLuint backgroundTexture){
shaderProgram.bindProgram();
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthTexture);
shaderProgram.setUniform("u_depthtex", 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, colorTexture);
shaderProgram.setUniform("u_colortex", 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, positionTexture);
shaderProgram.setUniform("u_positiontex", 2);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, backgroundTexture);
shaderProgram.setUniform("u_backgroundtex", 3);
glEnableVertexAttribArray(3);
vbo.bindVBO();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
vbo.unbindVBO();
glDisableVertexAttribArray(3);
shaderProgram.unbindProgram();
}
and methods for initialization and rendering scene:
void OpenGLContext::setupScene(void) {
glClearColor(0.4f, 0.6f, 0.9f, 1.0f);
//FRAMEBUFFERS:
skyboxFramebuffer.init();
skyboxTexture.init(windowWidth, windowHeight, GL_RGBA32F, GL_RGBA, GL_FLOAT);
skyboxFramebuffer.bind();
skyboxFramebuffer.attachTexture(skyboxTexture.getId(), GL_COLOR_ATTACHMENT0);
const GLenum skyboxDrawBuffers[1] = { GL_COLOR_ATTACHMENT0};
skyboxFramebuffer.drawBuffers(1, skyboxDrawBuffers);
skyboxFramebuffer.validate();
skyboxFramebuffer.unbind();
mainFramebuffer.init();
mainColorTexture.init(windowWidth, windowHeight, GL_RGBA32F, GL_RGBA, GL_FLOAT);
mainPositionTexture.init(windowWidth, windowHeight, GL_RGBA32F, GL_RGBA, GL_FLOAT);
mainDepthTexture.init(windowWidth, windowHeight, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT);
mainFramebuffer.bind();
mainFramebuffer.attachTexture(mainColorTexture.getId(), GL_COLOR_ATTACHMENT0);
mainFramebuffer.attachTexture(mainPositionTexture.getId(), GL_COLOR_ATTACHMENT1);
mainFramebuffer.attachTexture(mainDepthTexture.getId(), GL_DEPTH_ATTACHMENT);
const GLenum mainDrawBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
mainFramebuffer.drawBuffers(2, mainDrawBuffers);
mainFramebuffer.validate();
mainFramebuffer.unbind();
//SKYBOX:
skybox->init("resources/skybox/default/",
"pos_x.tga",
"neg_x.tga",
"pos_y.tga",
"neg_y.tga",
"pos_z.tga",
"neg_z.tga");
//PARTICLES:
particles->init(scene);
//SCREENQUAD:
screenQuad.init();
}
void OpenGLContext::renderScene() {
glfwGetFramebufferSize(window, &windowWidth, &windowHeight);
glViewport(0, 0, windowWidth, windowHeight);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
fpsCounter->calcFPS(1.0, windowName);
if(mode==INPUT_ENABLED_MODE){
updateInputs();
}
projectionMatrix = controls->getProjectionMatrix();
viewMatrix = controls->getViewMatrix();
modelMatrix = glm::mat4(1.0f);
glm::mat4 mvpMatrix = projectionMatrix*viewMatrix*modelMatrix;
//SKYBOX:
skyboxFramebuffer.bind();
skybox->render(mvpMatrix);
skyboxFramebuffer.unbind();
//PARTICLES:
if(scene->tryLockScene()){
if(scene->isSceneUpdated()){
particles->updateParticlesPosition(scene);
scene->setSceneUpdated(false);
}
scene->unlockScene();
}
mainFramebuffer.bind();
particles->draw(modelMatrix, viewMatrix, projectionMatrix);
mainFramebuffer.unbind();
//SCREENQUAD:
screenQuad.draw(mainDepthTexture.getId(), mainColorTexture.getId(), mainPositionTexture.getId(), skyboxTexture.getId());
glfwSwapBuffers(window);
glfwPollEvents();
}
plus screenQuad shaders:
vertex:
#version 430
layout (location = 3) in vec2 v_coord;
layout (binding = 0) uniform sampler2D u_depthtex;
layout (binding = 1) uniform sampler2D u_colortex;
layout (binding = 2) uniform sampler2D u_positiontex;
layout (binding = 3) uniform sampler2D u_backgroundtex;
out vec2 fs_texcoord;
void main(void) {
gl_Position = vec4(v_coord, 0.0, 1.0);
fs_texcoord = (v_coord + 1.0) / 2.0;
}
and fragment:
#version 430
layout (binding = 0) uniform sampler2D u_depthtex;
layout (binding = 1) uniform sampler2D u_colortex;
layout (binding = 2) uniform sampler2D u_positiontex;
layout (binding = 3) uniform sampler2D u_backgroundtex;
layout (location = 0) out vec4 out_Color;
in vec2 fs_texcoord;
void main(void) {
float exp_depth = texture(u_depthtex,fs_texcoord).r;
if(exp_depth>0.99f){
out_Color = vec4(texture(u_backgroundtex,fs_texcoord).xyz,1.0f);
return;
}
out_Color = vec4(texture(u_colortex,fs_texcoord).xyz, 1.0f);
}
Shader helper classes, vao and vbo helper classes are fine for sure. No errors occurs in logs.
UPDATE:
particles vertex shader:
#version 430
uniform mat4x4 modelViewMatrix;
uniform mat4x4 projectionMatrix;
uniform float pointRadius; // point size in world space
uniform float pointScale; // scale to calculate size in pixels
layout (location = 0) in vec3 in_Position;
layout (location = 1) in vec4 in_Color;
out vec3 fs_PosEye;
out vec4 fs_Position;
out vec4 fs_Color;
void main(void) {
vec3 posEye = (modelViewMatrix * vec4(in_Position.xyz, 1.0f)).xyz;
float dist = length(posEye);
gl_PointSize = pointRadius * (pointScale/dist);
fs_PosEye = posEye;
fs_Position = modelViewMatrix * vec4(in_Position.xyz, 1.0f);
fs_Color = in_Color;
gl_Position = projectionMatrix * modelViewMatrix * vec4(in_Position.xyz, 1.0f);
}
fragment shader:
#version 430
uniform mat4x4 modelViewMatrix;
uniform mat4x4 projectionMatrix;
uniform float pointRadius; // point size in world space
uniform float pointScale; // scale to calculate size in pixels
in vec4 fs_Position;
in vec3 fs_PosEye;
in vec4 fs_Color;
layout (location = 0) out vec4 out_Color;
layout (location = 1) out vec4 out_Position;
void main(void)
{
// calculate normal from texture coordinates
vec3 normal;
normal.xy = gl_PointCoord.xy*vec2(2.0, -2.0) + vec2(-1.0, 1.0);
float r = dot(normal.xy, normal.xy);
if(r>1.0)
discard;
normal.z = sqrt(1.0-r);
//calculate depth
vec4 pixelPos = vec4(fs_PosEye + normalize(normal)*pointRadius,1.0f);
vec4 clipSpacePos = projectionMatrix * pixelPos;
gl_FragDepth = (clipSpacePos.z / clipSpacePos.w);
out_Color = fs_Color;
out_Position = pixelPos;
}
and Particles.draw() method:
void CParticles::draw(glm::mat4 modelMatrix, glm::mat4 viewMatrix, glm::mat4 projectionMatrix){
shaderProgram.bindProgram();
glm::mat4 modelViewMatrix = viewMatrix*modelMatrix;
shaderProgram.setUniform("projectionMatrix", &projectionMatrix);
shaderProgram.setUniform("modelViewMatrix", &modelViewMatrix);
shaderProgram.setUniform("pointRadius", &pointRadius);
shaderProgram.setUniform("pointScale", &pointScale);
glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
glEnable(GL_POINT_SPRITE);
glEnable(GL_PROGRAM_POINT_SIZE);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glDrawArrays(GL_POINTS, 0, n);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisable(GL_PROGRAM_POINT_SIZE);
glDisable(GL_POINT_SPRITE);
shaderProgram.unbindProgram();
}
UPDATE2:
The problem is that textures filled by a particle shader are empty when I try to sample data from them in a screenQuad shader. Each depth, position and color texture samplers return zeros. I use same classes and same methods as with a skybox, but skybox texture works fine.
UPDATE3:
Random code changes showed me that if I comment line with attaching depth texture to framebuffer, particle color is finally passed to a texture and i can see it on a screen quad (but without any depth test. Red particles (drawed last) are always on the front).
I guess there is a problem with connecting particle shader with depth texture. But still I can't find an exact bug. I hope my sugestion will be helpful.
I haven't studied the entire code, but one problem jumps out immediately:
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, colorTexture);
shaderProgram.setUniform("u_colortex", colorTexture);
The value of a uniform for a texture sampler is not the texture id (aka name). It's the texture unit the texture is bound to. So in this case, since you're using texture unit 1 for this texture, it should be:
shaderProgram.setUniform("u_colortex", 1);
The problem was that glDepthMask() was disabled when i invoked glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);.
It needs to be enabled in order to glClear(GL_DEPTH_BUFFER_BIT) took any effect.
Plus I needed to add cleaning framebuffers in a proper way as well.