Applying a simple Tesselation Evaluation Shader - c++

I'm trying to learn how to use tesselation to render simple polygons, and for a starter I'm trying to write a simple program that essentially would just draw whatever vertices it's given, without any extra logic. My three shaders compile without error, but when I try to apply the program OpenGL returns error 1282. Based on the documentation for glUseProgram my best guess is that OpenGL is in a state where the program cannot be used, but I'm not able to tell why. If I don't include the TES in the program my code runs just fine, so I'm sure I'm not trying to apply the wrong program ID.
Since I know with fairly good confidence that my vertex and fragment shader are working correctly, the issue must be with the TES, which in my eyes will only put out the control points as vertices.
Is it not possible to simply pass control points through the shader as vertices?
My Tesselation Evaluation Shader:
#version 440 core
layout(triangles, equal_spacing, ccw) in;
in vec4 positionIn[];
void main()
{
gl_Position = positionIn[0];
}
Vertex Shader:
#version 440 core
layout(location = 0) in vec4 position;
uniform mat4 u_MVP;
void main()
{
gl_Position = u_MVP * position;
}
Fragment Shader:
#version 440 core
layout(location = 0) out vec4 colour;
uniform vec4 u_Colour;
void main()
{
colour = u_Colour;
}
Rest of the code that handles the compilation and setup:
int compileShader(unsigned int type, const std::string& source)
{
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
char* message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(id, length, &length, message);
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
return id;
}
void setUpProgram()
{
unsigned int program = glCreateProgram();
unsigned int vs = compileShader(GL_VERTEX_SHADER, vertexShader);
unsigned int fs = compileShader(GL_FRAGMENT_SHADER, fragmentShader);
unsigned int es = compileShader(GL_TESS_EVALUATION_SHADER, tesselationEvaluationShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glAttachShader(program, es);
glLinkProgram(program);
glValidateProgram(program);
GLenum error = glGetError();
while (error != GL_NO_ERROR)
{
std::cout << "Error: " << error << std::endl;
GLenum error = glGetError();
}
glUseProgram(program);
error = glGetError();
std::cout << "Error: " << error << std::endl;
}

There are two problems.
The first is that the vertex shader output is not being consumed by the tessellation evaluation shader. The VS outputs gl_Position, but the TES doesn't read gl_Position. It instead reads a user-defined input positionIn, which has no linkage to the value of gl_Position. Indeed, it has no value at all, and your shader linking process would have told you that if you checked whether your program successfully linked.
The corresponding TES input for the gl_Position output is, cleverly named, gl_Position. However, since this is the same name as the output you intend to write to, it is defined within an input interface block gl_PerVertex. So if you want to access it, you need to declare this interface block appropriately:
in gl_PerVertex
{
vec4 gl_Position;
} gl_in[gl_MaxPatchVertices];
You can then use gl_in[ix].gl_Position to access the position for that vertex. Speaking of array indexing...
The second problem is that [0] is the wrong index. The job of the TES is to compute the attributes for a vertex within the tessellated abstract patch. To do that job, the TES is given all of the vertices for the patch. So each TES invocation for a patch gets the same set of inputs, in the same order.
So doing gl_in[0].gl_Position would yield the same value for each vertex in the patch. That's a triangle with zero area, and thus isn't helpful in displaying anything.
The only thing the TES invocations get which are different is the input value vertexTexCoord, which is the coordinate of this TES invocation within the abstract patch. This is a vec3, and for triangle tessellation, represents the barycentric coordinate of the vertex within the abstract patch.
So you need to convert this vec3 into an index. If you aren't doing any tessellation at all, then the barycentric coordinate will have one of the values at 1.0, with the other values being zero. So you can use that to tell you which index you should use.

Related

Cant access vec4 array in GLSL

When I try to compile this GLSL code in OpenGL 4.0 I get error 1282
Vertex shader:
#version 330 core
layout(location = 0) in vec2 aPos;
uniform mat4 model[100];
uniform mat4 projection;
out int instanceID;
void main()
{
instanceID = gl_InstanceID;
gl_Position = projection * model[gl_InstanceID] * vec4(aPos.x, aPos.y, 0.0, 1.0);
}
Fragment shader:
#version 330 core
in int instanceID;
out vec4 FragColor;
uniform vec4 color[100];
void main()
{
FragColor = color[instanceID];
}
The code is regular ShaderProgram creation because I get the error before drawing or anything like that but just in case here is the code:
unsigned int vertex, fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
std::string vShaderCode = ReadEntireTextFile(vertPath);
const char* c_vShaderCode = vShaderCode.c_str();
glShaderSource(vertex, 1, &c_vShaderCode, NULL);
glCompileShader(vertex);
std::string fShaderCode = ReadEntireTextFile(fragPath);
fragment = glCreateShader(GL_FRAGMENT_SHADER);
const char* c_fShaderCode = fShaderCode.c_str();
glShaderSource(fragment, 1, &c_fShaderCode, NULL);
glCompileShader(fragment);
// shader Program
m_RendererID = glCreateProgram();
glAttachShader(m_RendererID, vertex);
glAttachShader(m_RendererID, fragment);
glLinkProgram(m_RendererID);
// delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(vertex);
glDeleteShader(fragment);
glUseProgram(m_RendererID);
I know for sure that the error is because of instanceID because it worked when the shader didn't have that. but I tried to find where the problem is exactly with no luck.
UPDATE:
Made sure shaders were compiled successfully. and turns out they are compiled successfully.
I was able to pinpoint where the error occurs and it was the glUseProgram funtion.
I think the error is because of instanceID because when I change:
FragColor = color[instanceID];
to
FragColor = color[0];
the program works.
UPDATE(2):
I solved the problem.
Turns out I had 2 problems one being that I had too many components and I fixed that thanks to one of the answers alerting me.
The other was that I can't put uniforms directly in the fragment shader which I thought you could do.So I put the colors in the vertex shader and passed the one color I needed for the fragment shader.
Thanks for the help!
uniform mat4 model[100];
That is way outside of what is guaranteed by the spec. The limit here is GL_MAX_VERTEX_UNIFORM_COMPONENTS, which the spec guarantees to be at least 1024. Since a mat4 consumes 16 components, that's 64 matrices at most. Now your particular limit might be higher, but you also have the other uniforms in your program, like color[100].
(from comments):
It does not return anything for both fragment and vertex shaders and glGetShaderiv(shader, GL_COMPILE_STATUS, &output); returns true for both shaders.
But that does not imply that the program object linked successfully. Such ressource limits are usually enforced during linking.
I'm pretty sure program is an object created by openGL successfully, I'm not really sure about the others though. you see if i change the fragment shader main function to FragColor = color[0]; it will work so the issue is with instanceID I think.
That conclusion does not follow. If you write color[0], it will optimize your vec4r[100] array to vec4[1], and you might get below your particular limit.

Why does my GLSL shader fail compilation with no error message?

I'm building a game using OpenGL and C++. I'm using GLFW and GLAD. I'm currently in the process of setting up simple shaders, but I'm completely roadblocked by a compilation problem. In a nutshell, shader compilation fails with no error message.
Here's my vertex shader (it's meant to draw 2D images and text):
#version 330 core
layout (location = 0) in vec2 vPosition;
layout (location = 1) in vec2 vTexCoords;
layout (location = 2) in vec4 vColor;
out vec4 fColor;
out vec2 fTexCoords;
uniform mat4 mvp;
void main()
{
vec4 position = mvp * vec4(vPosition, 0, 1);
position.y *= -1;
gl_Position = position;
fColor = vColor;
fTexCoords = vTexCoords;
}
And here's the relevant code to create the shader, load the shader source, compile the shader, and check for errors.
GLuint shaderId = glCreateShader(GL_VERTEX_SHADER);
std::string source = FileUtilities::ReadAllText(Paths::Shaders + filename);
GLchar const* file = source.c_str();
GLint length = static_cast<GLint>(source.size());
glShaderSource(shaderId, 0, &file, &length);
glCompileShader(shaderId);
GLint status;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint logSize = 0;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);
std::vector<GLchar> message = std::vector<GLchar>(logSize);
glGetShaderInfoLog(shaderId, logSize, nullptr, &message[0]);
glDeleteShader(shaderId);
std::cout << std::string(message.begin(), message.end());
}
Using that code, logSize is returned as 1, meaning that I'm unable to access the error message provided by GL. From what I can tell, the message doesn't exist at all. I've already seen the question posted here, in which the issue was a missing call to glCompileShader. As you can see, my code does call that function.
In attempting to solve this problem, I've already confirmed a few things.
My shader source (a string) is being read correctly. The source is a single string that, as far as I can tell, exactly matches the actual shader file.
There are no casting issues from the string source to GLchar const* or GLint (the variables file and length). Both look correct.
If I artificially inflate the value of logSize (to, say, 1000), the resulting message is nothing but zeroes. No error message exists.
I am calling glfwInit() and related functions before reaching this point in the code. Querying glGetString(GL_VERSION) does correctly return the target version (3.3.0).
Does anyone know how to fix this? As I said, my progress is completely blocked since I can't render anything (2D or 3D) without working shaders.
Thank you!
The problem is that you never upload any shader source to the shader.
The second parameter in this line:
glShaderSource(shaderId, 0, &file, &length);
tells OpenGL to load 0 code strings to the shader (nothing). Change this to 1, and it should work.

GLSL: shader linking fail (but no log)

I'm trying to create a little shader for brightness and contrast of the window (that I've seen here).
I can load the file, and compile the shader successfully. But I fail to link it. My problem is that the log has no output, so I can't see what's wrong with it. How can I check the linking problem? Where can I find informations about linking failing, and check why linking can fail (I'm new to shaders).
I'm using Ubuntu 12.04.
This is the initialization code
if (GLEW_ARB_fragment_shader) {
// I enter here so I suppose that shader is enabled for
// my graphics card
std::cout << "arb shader enabled" << std::endl;
}
// Loading shader
string fragmentShaderSource;
GLint len;
std::ifstream in("/path/to/file.glsl");
fragmentShaderSource = std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
len = fragmentShaderSource->size();
// I've checked the string and file seems to be loaded properly.
// Creating shader
GLint flength;
GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
GLcharARB** text = new (GLcharARB*);
text[0] = (char*)fragmentShaderSource.c_str();
glShaderSourceARB(fragmentShader, 1, (const GLcharARB**) text, &flength);
// Compile shader
glCompileShaderARB(fragmentShader);
GLint compiled;
glGetObjectParameteriv(ShaderObject, GL_COMPILE_STATUS, &compiled);
if (compiled)
{
// I enter here so I suppose that compilation is ok.
std::cout << "shader compiled" << std::endl;
}
// Attaching to program
GLuint program;
program = glCreateProgram();
glAttachShader(program, fragmentShader);
// Linking
glLinkProgram(program);
// Link check
GLint linked;
glGetProgramivARB(program, GL_LINK_STATUS, &linked);
if (linked) {
std::cout << "linked" << std::endl;
} else {
// I enter here so linking is failed
std::cout << "not linked" << std::endl;
GLint blen = 0;
GLsizei slen = 0;
glGetShaderiv(program, GL_INFO_LOG_LENGTH, &blen);
// blen is equal to zero so I cannot print the log message
// because it's absent
if (blen > 1) {
GLchar* linking_log = (GLchar*) malloc(blen);
glGetProgramInfoLog(program, blen, &slen, linking_log);
glGetInfoLogARB(program, blen, &slen, linking_log);
std::cout << "compiler_log:\n" << linking_log << std::endl;
free(linking_log);
}
}
And this is the glsl code that I load
uniform float Brightness : register(C0);
uniform float Contrast : register(C1);
sampler2D Texture1Sampler : register(S0);
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 pixelColor = tex2D(Texture1Sampler, uv);
pixelColor.rgb /= pixelColor.a;
// Apply contrast.
pixelColor.rgb = ((pixelColor.rgb - 0.5f) * max(Contrast, 0)) + 0.5f;
// Apply brightness.
pixelColor.rgb += Brightness;
// Return final pixel color.
pixelColor.rgb *= pixelColor.a;
return pixelColor;
}
EDIT:
I fixed log, when linking fails, I obtain following output:
Fragment info
-------------
0(1) : warning C7557: OpenGL does not allow Cg-style semantics
0(2) : warning C7557: OpenGL does not allow Cg-style semantics
0(4) : warning C7557: OpenGL does not allow Cg-style semantics
0(4) : warning C7554: OpenGL requires sampler variables to be explicitly declared as uniform
0(6) : warning C7506: OpenGL does not define the global type float4
0(6) : warning C7506: OpenGL does not define the global type float2
0(6) : warning C7557: OpenGL does not allow Cg-style semantics
0(6) : warning C7557: OpenGL does not allow Cg-style semantics
0(6) : warning C7527: OpenGL requires main to take no parameters
0(6) : warning C7530: OpenGL requires main to return void
0(9) : warning C7506: OpenGL does not define the global function tex2D
0(13) : warning C7502: OpenGL does not allow type suffix 'f' on constant literals in versions below 120
0(13) : warning C7011: implicit cast from "int" to "float"
0(13) : warning C7502: OpenGL does not allow type suffix 'f' on constant literals in versions below 120
EDIT2:
I've fixed fragment shader
uniform float Brightness;
uniform float Contrast;
uniform vec2 vTextureCoord;
uniform sampler2D Texture1Sampler;
void main() {
vec4 textureColor = texture2D(Texture1Sampler, vTextureCoord);
vec3 fragRGB = textureColor.rgb / textureColor.a;
fragRGB.rgb = ((fragRGB.rgb - 0.5) * max(Contrast, 0.0)) + 0.5;
fragRGB.rgb += Brightness;
fragRGB.rgb *= textureColor.a;
gl_FragColor = vec4(fragRGB, textureColor.a);
}
And I've added a basic vertex shader
attribute vec4 gl_Vertex;
void main(){
gl_Position = gl_Vertex;
}
I've added them to program. Now all compilation warning disappeared, but linking fails again.
program = glCreateProgram();
glAttachShader(program, fragmentShader); // fragment shader compiled. No warnings
glAttachShader(program, vertexShader); // vertex shader compiled. No warnings
glLinkProgram(program);
GLint linked;
glGetProgramivARB(program, GL_LINK_STATUS, &linked); // linked != GL_TRUE. Linking failed.
What I'm yet doing wrong?
You are only attaching a fragment shader and not a vertex shader. In fully programmable openGL both are required. Your code should be:
glAttachShader(program, fragmentShader);
glAttachShader(program, vertexShader);
Linking happens after shaders are attached to a program, and since both vertex and fragment shaders are required linking failed.
Moreover you are basically writing Cg in GLSL.
float4 main(float2 uv : TEXCOORD) : COLOR // These Cg semantics are not accepted in GLSL
The point is that GLSL doen't use Cg like semantics and you need to use GLSL special out variables. Check the following psudo-GLSL code.
in vec3 vertex;
//vertex shader.
void main() // write a main and output should be done using special variables
{
// output using special variables.
gl_Position = vertex;
}
//fragment shader.
uniform vec4 color;
void main() // write a main and output should be done using special variables
{
// output using special variables.
gl_FragColor = color;
}
I actually recommend that you pick a GLSL language tutorial like this one.

c++ OpenGL glGetUniformLocation for Sampler2D returns -1 on Raspberry PI but works on Windows

I'm making a crossplatform OpenGL program. However, I've encountered a problem, where glGetUniformLocation, which should return the location of a uniform variable in my shader program, returns -1, and it only occurs on Linux (Raspbian distro, ran on Raspberry PI), and on Windows the same code works perfectly! Here's my code:
Load Shader program function:
int shader, status;
programID = glCreateProgram();
// Load vertex shader
shader = LoadShaderFromString(GL_VERTEX_SHADER, Tools::GetFileAsString("VertexShader.glsl"), "Unable to compile vertex shader.\n");
glAttachShader(programID, shader);
// Load pixel shader
shader = LoadShaderFromString(GL_FRAGMENT_SHADER, Tools::GetFileAsString("FilterPixelShader.glsl"), "Unable to compile pixel shader.\n");
glAttachShader(programID, shader);
// Link the program
glLinkProgram(programID);
glGetProgramiv(programID, GL_LINK_STATUS, &status);
if (status == 0)
{
Log("Unable to link filter shader program.\n");
PrintProgramLog(programID);
Fail(); // Quits program
}
// returns -1 here!
frameTextureLocation = glGetUniformLocation(programID, "FrameTextureUnit");
if (frameTextureLocation == -1)
{
int errorCode = glGetError();
Log(string("Error retrieving variable frameTextureLocation from shader program: "));
Log((const char*)glewGetErrorString(errorCode))
Log("!\n");
Fail();
}
LoadShaderFromString:
int Shader::LoadShaderFromString(int type, const string& shaderSource, const string& errorMessage)
{
int shader, status;
const char* programSource;
shader = glCreateShader(type);
programSource = shaderSource.c_str();
glShaderSource(shader, 1, &programSource, nullptr);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == 0)
{
Log(errorMessage);
PrintShaderLog(shader);
Fail();
}
return shader;
}
Lastly, the shader itself:
uniform sampler2D FrameTextureUnit;
uniform sampler2D BackgroundTextureUnit;
#if __VERSION__ >= 130
// Texture coordinate
in vec2 texCoord;
// Final color
out vec4 gl_FragColor;
#else
// Texture coordinate
varying vec2 texCoord;
#endif
uniform float Tolerance; // Tolerance for color difference
uniform vec4 FilterColor; // Color of the filter
void main()
{
vec4 pixel = texture2D(FrameTextureUnit, texCoord);
vec4 background = texture2D(BackgroundTextureUnit, texCoord);
float difference = abs(background.x - pixel.x)
+ abs(background.y - pixel.y)
+ abs(background.z - pixel.z);
if (difference > Tolerance)
{
gl_FragColor = FilterColor;
}
else
{
// Y = 0.2126 R + 0.7152 G + 0.0722 B
float gray = pixel.x * 0.2126 + pixel.y * 0.7152 + pixel.z * 0.0722;
gl_FragColor = vec4(gray, gray, gray, 1);
}
}
Does anyone know why this might be happening? :( It's worth adding that the error handling code:
int errorCode = glGetError();
Log(string("Error retrieving variable frameTextureLocation from shader program: "));
Log((const char*)glewGetErrorString(errorCode));
Prints "Error retrieving variable frameTextureLocation from shader program: No error".
Always specify GLSL version at the top of your shaders, otherwise it defaults to a very old version. It must be the first line. It will also eliminate the need for version checking inline.
#version 150
// rest of shader here

OpenGL - Problems getting shaders to compile

Finally isolated the issue of my shader not being able to be used to it failing to compile.
Here is my shader loading routine. The first part reads in the shader:
void GLSLShader::LoadFromFile(GLenum whichShader, const string filename)
{
ifstream fp;
// Attempt to open the shader
fp.open(filename.c_str(), ios_base::in);
// If the file exists, load it
if(fp)
{
// Copy the shader into the buffer
string buffer(std::istreambuf_iterator<char>(fp), (std::istreambuf_iterator<char>()));
// Debug output to show full text of shader
errorLog.writeSuccess("Shader debug: %s", buffer.c_str());
LoadFromString(whichShader, buffer);
}
else
{
errorLog.writeError("Could not load the shader %s", filename.c_str());
}
}
After it has loaded it into a string, it sends it to be loaded:
void GLSLShader::LoadFromString(GLenum type, const string source)
{
// Create the shader
GLuint shader = glCreateShader(type);
// Convert the string
const char * ptmp = source.c_str();
glShaderSource(shader, 1, &ptmp, NULL);
// Compile the shader
glCompileShader(shader);
// Check to see if the shader has loaded
GLint status;
glGetShaderiv (shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
glGetShaderInfoLog (shader, infoLogLength, NULL, infoLog);
errorLog.writeError("could not compile: %s", infoLog);
delete [] infoLog;
}
_shaders[_totalShaders++]=shader;
}
I am getting the debug output "could not compile: " and it seems that the error buffer is empty. This has been driving me crazy for the past 3 days. Does anyone see my error?
Here are the very simple shaders:
#version 330
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;
smooth out vec4 theColor;
void main()
{
gl_Position = position;
theColor = color;
}
#version 330
smooth in vec4 theColor;
out vec4 outputColor;
void main()
{
outputColor = theColor;
}
UPDATE
It looks like for some reason there is crap being added to the end of the shader in memory. I am not sure why. I have tried reading it in to a char* and a string. Here is the output:
<-!-> Shader: #version 330
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;
smooth out vec4 theColor;
void main()
{
gl_Position = position;
theColor = color;
}
n
<-!-> Shader: #version 330
smooth in vec4 theColor;
out vec4 outputColor;
void main()
{
outputColor = theColor;
}
nts/Resources
Notice the 'n' at the end of the first shader and the 'nts/Resources' at the end of the second one. Any idea why?
ANOTHER UPDATE
The crap at the end was caused by an extra line at the end. I removed it and it is back to outputting the correct shader text. Still no luck thought with compiling.
I am at a loss here. The Superbible has their extensive libraries that are unoptimized and I don't need. There doesn't seem to be a damn decent shader compiler for Mac. I really don't mind how simple it is. It just needs to work with shaders. Does anyone have an example?
You're calling glShaderSource without supplying the length of each string in the sources array. Hence the string supplied is assumed to be terminated by a null byte ('\0'). The way you're reading the file into memory does not terminate the shader source with an additional null byte. So the GLSL compiler will read beyond the end of the shader source into random memory, where it finds… garbage.
Solution: Either add a terminating null byte, or supply the shader text lengths parameter.