Sign in to follow this  
D.V.D

OpenGL Loading Shader Code from Files

Recommended Posts

D.V.D    1029
I was following some online tutorials about opengl and shader code and I encoutered a problem. They compiled their shader code from const char* variables but I wanted to find out how to do the same thing but reading the shaders from files. The problem I am having is this, when I run my program, I get no error messages from visual studio 2010 but in the console, I get this error message:

Error compiling shader type 35633: '0<1> : error c0000: syntax error, unexpected, $undefined at token "<undefined>"

I ran the same shader code before when it was in a string and it worked just fine. Im reading the file with this function:

[source lang="cpp"]const char* readShaderFile(const std::string fileName)
{
std::ifstream shaderFile( fileName.c_str() );

// find the file size
shaderFile.seekg(0,std::ios::end);
std::streampos length = shaderFile.tellg();
shaderFile.seekg(0,std::ios::beg);

// read whole file into a vector:
std::vector<char> buffer(length);
shaderFile.read(&buffer[0],length);

// convert to GLchar
const char* Shader = (std::string( buffer.begin(), buffer.end() )).c_str();

// return the shader string
return Shader;
}[/source]

and my shader code is here:

[source lang="cpp"]#version 330

in vec2 TexCoord0;
in vec3 Normal0;

out vec4 FragColor;

struct DirectionalLight
{
vec3 Color;
float AmbientIntensity;
float DiffuseIntensity;
vec3 Direction;
};

uniform DirectionalLight gDirectionalLight;
//uniform sampler2D gSampler;

void main()
{
vec4 AmbientColor = vec4(gDirectionalLight.Color, 1.0f) *
gDirectionalLight.AmbientIntensity;

float DiffuseFactor = dot(normalize(Normal0), -gDirectionalLight.Direction);

vec4 DiffuseColor;

if (DiffuseFactor > 0) {
DiffuseColor = vec4(gDirectionalLight.Color, 1.0f) *
gDirectionalLight.DiffuseIntensity *
DiffuseFactor;
}
else {
DiffuseColor = vec4(0, 0, 0, 0);
}

//FragColor = texture2D(gSampler, TexCoord0.xy) * (AmbientColor + DiffuseColor);
FragColor = vec4(1.0,0.0,0.0,1.0)*(AmbientColor + DiffuseColor);
}[/source]

Share this post


Link to post
Share on other sites
L. Spiro    25622
You have just returned a pointer to garbage from within [font=courier new,courier,monospace]readShaderFile()[/font].
[font=courier new,courier,monospace]buffer[/font] is a local variable and then you use it to create yet another temporary copy. It is destroyed on the next statement and with it the memory it has allocated. If that code ever worked it would only be luck.
You can’t return a pointer to its buffer. Either return the buffer itself (not recommended) or pass a buffer to be used to hold the return (and return a reference to that).
As in:

[CODE]std::string & readShaderFile(const std::string & fileName, std::string & buffer)
{
// Load file into buffer.
// Return buffer.
return buffer;
}[/CODE]


Notice also that [font=courier new,courier,monospace]fileName[/font] is now a reference. You should never pass std::string or other structures by copy.
Also notice that buffer is passed by reference. Not only is this once again a good idea, it is 100% necessary for this to work properly.


L. Spiro Edited by L. Spiro

Share this post


Link to post
Share on other sites
D.V.D    1029
My bad I thought I posted in the GL forum.

Okay but what do I do with the buffer if I want to compile the shader? My compile function only takes GLenum ShaderType and const GLchar* pShaderText. Since the buffer holds the text for the object, do I convert it to a GLchar? My compile code looks like this:

EDIT: Woops I thought the buffer was of class buffer not std::string. I think I understand this better now, Ill simply convert it to GLchar and see if it works.

EDIT2: Woops, Im still confused with how to do this, any help?

[source lang="cpp"]bool ShaderManager::AddShaderFile(GLenum ShaderType, const GLchar* pShaderText)
{
GLuint ShaderObj = glCreateShader(ShaderType);

if (ShaderObj == 0) {
fprintf(stderr, "Error creating shader type %d\n", ShaderType);
Sleep(10000);
return false;
}

// Save the shader object - will be deleted in the destructor
shaderObjList.push_back(ShaderObj);

const GLchar* p[1];
p[0] = pShaderText;
GLint Lengths[1];
Lengths[0]= strlen(pShaderText);
glShaderSource(ShaderObj, 1, p, Lengths);

glCompileShader(ShaderObj);

GLint success;
glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &amp;success);

if (!success) {
GLchar InfoLog[1024];
glGetShaderInfoLog(ShaderObj, 1024, NULL, InfoLog);
fprintf(stderr, "Error compiling shader type %d: '%s'\n", ShaderType, InfoLog);
Sleep(10000);
return false;
}

glAttachShader(shaderProgram, ShaderObj);

return true;
}[/source] Edited by D.V.D

Share this post


Link to post
Share on other sites
Kaptein    2224
you need to save the Shader object somehow [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] otherwise, the program will be lost
you'll need to link the program together

lets say your function returns 0 if it fails, and non-zero if it returns a valid shader object!
then:
[source lang="cpp"]void CreateShader(file_v, file_f)
{
GLuint vertex = LoadShader(file_v, GL_VERTEX_SHADER_ARB);
GLuint frag = LoadShader(file_f, GL_FRAGMENT_SHADER_ARB);
GLuint prog = glCreateProgram();
glAttachShader(vertex);
glAttachShader(frag);

// bind your attrib locations here, either directly or through another function, but here is an example:
switch(prog) {
case shaders.dummy:
glBindAttribLocation(prog, 0, "in_vertex");
glBindAttribLocation(prog, 1, "in_texture");
break;
}

// link program
glLinkProgram(prog);
// check for errors!
// bind program, and set some common uniforms
glUseProgram(prog);

// set uniform locations here that never changes, either directly or through another function, example:
GLint location = glGetUniformLocation(prog, "texture");
if (location+1) glUniform1i(location, 0);
// remember to check for glGetError through the whole ordeal!
// finally close program
glUseProgram(null);

}
[/source]



note: only an example! i hope this helps you
edit: i see now that you do what is needed, in the loader
but, you can try setting null for length in glShaderSource!
see: http://content.gpwiki.org/index.php/OpenGL:Codes:Simple_GLSL_example

also, shader source is a glchar ptr ptr
so GLchar* p[1]; p[0] = &shaderSource;
glShaderSource (shader, 1, (glchar**) p, null);
Edited by Kaptein

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 ZeldaFan555
      Hello, My name is Matt. I am a programmer. I mostly use Java, but can use C++ and various other languages. I'm looking for someone to partner up with for random projects, preferably using OpenGL, though I'd be open to just about anything. If you're interested you can contact me on Skype or on here, thank you!
      Skype: Mangodoor408
    • By tyhender
      Hello, my name is Mark. I'm hobby programmer. 
      So recently,I thought that it's good idea to find people to create a full 3D engine. I'm looking for people experienced in scripting 3D shaders and implementing physics into engine(game)(we are going to use the React physics engine). 
      And,ye,no money =D I'm just looking for hobbyists that will be proud of their work. If engine(or game) will have financial succes,well,then maybe =D
      Sorry for late replies.
      I mostly give more information when people PM me,but this post is REALLY short,even for me =D
      So here's few more points:
      Engine will use openGL and SDL for graphics. It will use React3D physics library for physics simulation. Engine(most probably,atleast for the first part) won't have graphical fron-end,it will be a framework . I think final engine should be enough to set up an FPS in a couple of minutes. A bit about my self:
      I've been programming for 7 years total. I learned very slowly it as "secondary interesting thing" for like 3 years, but then began to script more seriously.  My primary language is C++,which we are going to use for the engine. Yes,I did 3D graphics with physics simulation before. No, my portfolio isn't very impressive. I'm working on that No,I wasn't employed officially. If anybody need to know more PM me. 
       
    • 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.
       
  • Popular Now