I'm having a bit of a problem with my code for compiling shaders, namely they both register as failed compiles and no log is received.
This is the shader compiling code:
/* Make the shader */
Uint size;
GLchar* file;
loadFileRaw(filePath, file, &size);
const char * pFile = file;
const GLint pSize = size;
newCashe.shader = glCreateShader(shaderType);
glShaderSource(newCashe.shader, 1, &pFile, &pSize);
glCompileShader(newCashe.shader);
GLint shaderCompiled;
glGetShaderiv(newCashe.shader, GL_COMPILE_STATUS, &shaderCompiled);
if(shaderCompiled == GL_FALSE)
{
ReportFiler->makeReport("ShaderCasher.cpp", "loadShader()", "Shader did not compile", "The shader " + filePath + " failed to compile, reporting the error - " + OpenGLServices::getShaderLog(newCashe.shader));
}
And these are the support functions:
bool loadFileRaw(string fileName, char* data, Uint* size)
{
if (fileName != "")
{
FILE *file = fopen(fileName.c_str(), "rt");
if (file != NULL)
{
fseek(file, 0, SEEK_END);
*size = ftell(file);
rewind(file);
if (*size > 0)
{
data = (char*)malloc(sizeof(char) * (*size + 1));
*size = fread(data, sizeof(char), *size, file);
data[*size] = '\0';
}
fclose(file);
}
}
return data;
}
string OpenGLServices::getShaderLog(GLuint obj)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0)
{
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
string log = infoLog;
free(infoLog);
return log;
}
return "<Blank Log>";
}
and the shaders I'm loading:
void main(void)
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
void main(void)
{
gl_Position = ftransform();
}
In short I get
From: ShaderCasher.cpp, In: loadShader(), Subject: Shader did not compile
Message: The shader Data/Shaders/Standard/standard.vs failed to compile, reporting the error - <Blank Log>
for every shader I compile.
I've tried replacing the file reading with just a hard coded string but I get the same error so there must be something wrong with how I'm compiling them. I have run and compiled example programs with shaders, so I doubt my drivers are the issue, but in any case I'm on a Nvidia 8600m GT.
Can anyone help?
In loadFileRaw, you pass char *data by value. Then you assign to it:
data = (char*)malloc(sizeof(char) * (*size + 1));
so your call
loadFileRaw(filePath, file, &size);
does not change the value of file! To change file, pass it in by pointer:
loadFileRaw(filePath, &file, &size);
and then change your function to
bool loadFileRaw(string fileName, char** data, Uint* size) { ... }
and in it,
*data = (char*)malloc(sizeof(char) * (*size + 1));
etc. (for the remaining references to data).
That said, since you're using C++, look into using std::vector<char> or std::string for your memory management. To get you started,
{
std::vector<char> data;
data.resize(100); // now it has 100 entries, initialized to zero
silly_C_function_that_takes_a_char_pointer_and_a_size(&data[0], 100); // OK
} // presto, memory freed
Also, you can look into using std::ifstream for reading files, instead of using FILE *.
Try with:
glShaderSource(newCashe.shader, 1, &pFile, NULL);
Which is the most commonly used call to load shader sources.
Related
I am trying to compile a simple colored triangle example with OpenGL 3 (GLSL 130) but my fragment shader never compiles. The error reported is always
syntax error unexpected $end
My vertex shader compiles and shows the geometry but the fragment shader fails.
Here are the sources (very simple one):
Vertex.vs:
attribute vec3 vertex_position;
attribute vec3 vertex_color;
varying vec4 out_color;
void main(void)
{
gl_Position = vec4(vertex_position, 1.0);
out_color = vec4(vertex_color, 1.0);
}
And fragment.fs:
varying vec4 out_color;
void main(void)
{
gl_FragColor = out_color;
}
[EDIT] Here is my shader compile code:
char *loadShader(const char *fname)
{
FILE* fp = fopen(fname, "rb");
long size = 0;
if (!fp)
return NULL;
fseek(fp, 0, SEEK_END);
size = ftell(fp) + 1;
fseek(fp, 0, SEEK_SET);
char* data = (char*) malloc((sizeof(char) * size));
::fread(data, 1, size, fp);
data[size-1] = '\0';
fclose(fp);
return data;
}
Shader::Shader(const char *fname)
: m_data(NULL),
ID(0)
{
if (fname)
m_data = ilian::loadShader(fname);
}
Shader::Shader(const char *data, size_t size)
{
if (data && size >0)
{
m_data = (char*) malloc(sizeof(char) * size);
::memmove(m_data, data, size);
}
}
Shader::~Shader()
{
if (m_data)
{
free(m_data);
m_data = NULL;
}
glDeleteShader(ID);
std::cout << "~Shader()\n";
}
std::string Shader::data()
{
std::string s((char*)m_data);
return s;
}
GLuint &Shader::getID()
{
return ID;
}
void Shader::createShader(ShaderType type)
{
GLint res = -1;
switch (type)
{
case VERTEX:
ID = glCreateShader(GL_VERTEX_SHADER);
break;
case FRAGMENT:
ID = glCreateShader(GL_FRAGMENT_SHADER);
break;
default:
break;
}
const GLchar* source = (const GLchar*) data().c_str();
int shader_len = data().length();
glShaderSource(ID, 1, &source, &shader_len);
glCompileShader(ID);
glGetShaderiv(ID, GL_COMPILE_STATUS, &res);
if (res == GL_TRUE)
{
std::cout << "Shader Compile OK!\n";
}
else
{
std::cout << "Shader Compile FAIL!\n";
GLint maxLength = 0;
glGetShaderiv(ID, GL_INFO_LOG_LENGTH, &maxLength);
//The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(ID, maxLength, &maxLength, &infoLog[0]);
std::cout << (char*)infoLog.data() << "\n";
//We don't need the shader anymore.
glDeleteShader(ID);
}
}
GLProgram::GLProgram(const char *vs_source, const char *fs_source)
: ID(0), vs(nullptr), fs(nullptr)
{
vs = new Shader(vs_source);
fs = new Shader(fs_source);
vs->createShader(VERTEX);
fs->createShader(FRAGMENT);
}
GLProgram::~GLProgram()
{
if (vs)
delete vs;
if (fs)
delete fs;
}
VAO &GLProgram::getVertexArrayObject()
{
return vao;
}
bool GLProgram::createProgram()
{
static GLint msg;
ID = glCreateProgram();
glAttachShader(ID, vs->getID());
glAttachShader(ID, fs->getID());
glLinkProgram(ID);
glGetProgramiv(ID, GL_LINK_STATUS, &msg);
std::cout << "Link status: (" <<msg
<< ")"<< std::endl;
if (!msg)
{
GLint infoLen = 0;
glGetProgramiv(ID, GL_INFO_LOG_LENGTH, &infoLen);
if(infoLen > 1)
{
char* infoLog = new char[infoLen];
glGetProgramInfoLog(ID, infoLen, NULL, infoLog);
printf("Error linking program:\n%s\n", infoLog);
delete [] infoLog;
}
}
}
void GLProgram::bind(int location, const char *attribyte)
{
glBindAttribLocation(ID, location, attribyte);
}
void GLProgram::useProgram()
{
glUseProgram(ID);
glBindVertexArray(vao.ID());
}
You are passing a pointer to an invalid memory address to glShaderSource. This happens because you try to get the c_str() pointer from a temporary string object in this line:
const GLchar* source = (const GLchar*) data().c_str();
Right after this line, the temporary string returned by data() gets deleted and the source pointer points to an invalid memory address.
The shortest (but ugly) fix to your code is to make sure that the string object still lives when you use the pointer by storing it:
auto data_str = data();
const GLchar* source = (const GLchar*)data_str.c_str();
But since the construction of the whole string object is completely useless in your code (and actually hurts performance because the string object creates a copy of the underlying char array), the better way is to return the char* instead of a new std::string in the data() function:
const char* Shader::data()
{
return m_data;
}
and use it with:
const GLchar* source = data();
Or even better: Do not use a char* with malloc in the first place and use the proper C++ methods to directly load a std::string from the file.
This is my first post, so I am thrilled to get some new insights and enlarge my knowledge. Currently I am working on a C-project where a binary raw file with 3d-data is loaded, processed in CUDA and saved in a new binary raw file.
This is based on the simpleTexture3D project from CUDA Samples:
This is my cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, cuda
#include <vector_types.h>
#include <driver_functions.h>
#include <cuda_runtime.h>
// CUDA utilities and system includes
#include <helper_cuda.h>
#include <helper_functions.h>
#include <vector_types.h>
typedef unsigned int uint;
typedef unsigned char uchar;
const char *sSDKsample = "simpleTexture3D";
const char *volumeFilename = "Bucky.raw";
const cudaExtent volumeSize = make_cudaExtent(32, 32, 32);
const uint width = 64, height = 64, depth=64;
//const char *volumeFilename = "TestOCT.raw";
//const cudaExtent volumeSize = make_cudaExtent(1024, 512, 512);
//
//const uint width = 1024, height = 512, depth=512;
const dim3 blockSize(8, 8, 8);
const dim3 gridSize(width / blockSize.x, height / blockSize.y, depth / blockSize.z);
uint *d_output = NULL;
int *pArgc = NULL;
char **pArgv = NULL;
extern "C" void cleanup();
extern "C" void initCuda(const uchar *h_volume, cudaExtent volumeSize);
extern "C" void render_kernel(dim3 gridSize, dim3 blockSize, uint *d_output, uint imageW, uint imageH, uint imageD);
void loadVolumeData(char *exec_path);
// render image using CUDA
void render()
{
// call CUDA kernel
render_kernel(gridSize, blockSize, d_output, width, height, depth);
getLastCudaError("render_kernel failed");
}
void cleanup()
{
// cudaDeviceReset causes the driver to clean up all state. While
// not mandatory in normal operation, it is good practice. It is also
// needed to ensure correct operation when the application is being
// profiled. Calling cudaDeviceReset causes all profile data to be
// flushed before the application exits
checkCudaErrors(cudaDeviceReset());
}
// Load raw data from disk
uchar *loadRawFile(const char *filename, size_t size)
{
FILE *fp = fopen(filename, "rb");
if (!fp)
{
fprintf(stderr, "Error opening file '%s'\n", filename);
return 0;
}
uchar *data = (uchar *) malloc(size);
size_t read = fread(data, 1, size, fp);
fclose(fp);
printf("Read '%s', %lu bytes\n", filename, read);
return data;
}
// write raw data to disk
int writeRawFile(const char *filename, uchar *data, size_t size)
{
int returnState=0;
// cut file extension from filename
char *a=strdup(filename); //via strdup you dumb a const char to char, you must free it yourself
int len = strlen(a);
a[len-4] = '\0'; //deletes '.raw'
//printf("%s\n",a);
char b[50];
sprintf(b, "_%dx%dx%d_out.raw", width, height, depth);
//char b[]="_out.raw"; //Add suffix out to filename
char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));
free(a);
FILE *fp = fopen(buffer, "wb"); //Open or create file for writing as binary, all existing data is cleared
if (!fp)
{
fprintf(stderr, "Error opening or creating file '%s'\n", buffer);
return 0;
}
size_t write = fwrite(data, 1, size, fp);
fclose(fp);
if (write==size)
{
printf("Wrote %lu bytes to '%s'\n", write, buffer);
return 0;
}
else
{
printf("Error writing data to file '%s'\n", buffer);
return 1;
}
}
// General initialization call for CUDA Device
int chooseCudaDevice(int argc, char **argv)
{
int result = 0;
result = findCudaDevice(argc, (const char **)argv);
return result;
}
void runAutoTest(char *exec_path, char *PathToFile)
{
// set path
char *path;
if (PathToFile == NULL)
{
path = sdkFindFilePath(volumeFilename, exec_path);
}
else
{
path = PathToFile;
}
if (path == NULL)
{
fprintf(stderr, "Error unable to find 3D Volume file: '%s'\n", volumeFilename);
exit(EXIT_FAILURE);
}
// Allocate output memory
checkCudaErrors(cudaMalloc((void **)&d_output, width*height*depth*sizeof(uchar)));
// zero out the output array with cudaMemset
cudaMemset(d_output, 0, width*height*depth*sizeof(uchar));
// render the volumeData
render_kernel(gridSize, blockSize, d_output, width, height, depth);
checkCudaErrors(cudaDeviceSynchronize());
getLastCudaError("render_kernel failed");
uchar *h_output = (uchar*)malloc(width*height*depth);
checkCudaErrors(cudaMemcpy(h_output, d_output, width*height*depth*sizeof(uchar), cudaMemcpyDeviceToHost));
int wState=writeRawFile(path,h_output,width*height*depth);
checkCudaErrors(cudaFree(d_output));
free(h_output);
// cudaDeviceReset causes the driver to clean up all state. While
// not mandatory in normal operation, it is good practice. It is also
// needed to ensure correct operation when the application is being
// profiled. Calling cudaDeviceReset causes all profile data to be
// flushed before the application exits
cudaDeviceReset();
//exit(bTestResult ? EXIT_SUCCESS : EXIT_FAILURE);
}
void loadVolumeData(char *exec_path, char *PathToFile)
{
char *path;
// load volume data
if (PathToFile == NULL)
{
path = sdkFindFilePath(volumeFilename, exec_path);
}
else
{
path = PathToFile;
}
if (path == NULL)
{
fprintf(stderr, "Error unable to find 3D Volume file: '%s'\n", volumeFilename);
exit(EXIT_FAILURE);
}
size_t size = volumeSize.width*volumeSize.height*volumeSize.depth;
uchar *h_volume = loadRawFile(path, size);
//int wState=writeRawFile(path,h_volume,size);
initCuda(h_volume, volumeSize);
free(h_volume);
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
pArgc = &argc;
pArgv = argv;
char *image_file = NULL;
printf("%s Starting...\n\n", sSDKsample);
if (checkCmdLineFlag(argc, (const char **)argv, "file")) //Note cmd line argument is -file "PathToFile/File.raw"
{ // for example -file "C:\ProgramData\NVIDIA Corporation\CUDA Samples\v7.0\2_Graphics\simpleTexture3D_FanBeamCorr\data\TestOCT_Kopie.raw"
getCmdLineArgumentString(argc, (const char **)argv, "file", &image_file);
}
if (image_file)
{
chooseCudaDevice(argc, argv);
loadVolumeData(argv[0],image_file);
runAutoTest(argv[0],image_file);
}
else
{
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
chooseCudaDevice(argc, argv);
loadVolumeData(argv[0],NULL);
runAutoTest(argv[0],NULL);
}
printf("I am finished...\n"
"Can I get some ice cream please\n");
exit(EXIT_SUCCESS);
}
And this is my .cu
#ifndef _SIMPLETEXTURE3D_KERNEL_CU_
#define _SIMPLETEXTURE3D_KERNEL_CU_
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <helper_cuda.h>
#include <helper_math.h>
typedef unsigned int uint;
typedef unsigned char uchar;
texture<uchar, 3, cudaReadModeNormalizedFloat> tex; // 3D texture
cudaArray *d_volumeArray = 0;
__global__ void
d_render(uint *d_output, uint imageW, uint imageH, uint imageD)
{
uint x = __umul24(blockIdx.x, blockDim.x) + threadIdx.x;
uint y = __umul24(blockIdx.y, blockDim.y) + threadIdx.y;
uint z = __umul24(blockIdx.z, blockDim.z) + threadIdx.z;
// float u = x / (float) imageW;
// float v = y / (float) imageH;
//float w = z / (float) imageD;
// // read from 3D texture
// float voxel = tex3D(tex, u, v, w);
uint ps=__umul24(imageW,imageH);
if ((x < imageW) && (y < imageH) && (z < imageD))
{
// write output color
uint i = __umul24(z,ps) +__umul24(y, imageW) + x;
d_output[1] = (uchar) 255;//+0*voxel*255;
}
}
extern "C"
void initCuda(const uchar *h_volume, cudaExtent volumeSize)
{
// create 3D array
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<uchar>();
checkCudaErrors(cudaMalloc3DArray(&d_volumeArray, &channelDesc, volumeSize));
// copy data to 3D array
cudaMemcpy3DParms copyParams = {0};
copyParams.srcPtr = make_cudaPitchedPtr((void *)h_volume, volumeSize.width*sizeof(uchar), volumeSize.width, volumeSize.height);
copyParams.dstArray = d_volumeArray;
copyParams.extent = volumeSize;
copyParams.kind = cudaMemcpyHostToDevice;
checkCudaErrors(cudaMemcpy3D(©Params));
// set texture parameters
tex.normalized = true; // access with normalized texture coordinates
tex.filterMode = cudaFilterModeLinear; // linear interpolation
tex.addressMode[0] = cudaAddressModeBorder; // wrap texture coordinates
tex.addressMode[1] = cudaAddressModeBorder;
tex.addressMode[2] = cudaAddressModeBorder;
// bind array to 3D texture
checkCudaErrors(cudaBindTextureToArray(tex, d_volumeArray, channelDesc));
}
extern "C"
void render_kernel(dim3 gridSize, dim3 blockSize, uint *d_output, uint imageW, uint imageH, uint imageD)
{
d_render<<<gridSize, blockSize>>>(d_output, imageW, imageH, imageD);
}
#endif // #ifndef _SIMPLETEXTURE3D_KERNEL_CU_
As you can see, currently, I set all values to zero except the index = 1, which is set to 255. Yet when I now open the image stack in Fiji, I see that the fourth pixel on the first slide is white. If I use index=i instead, I get white vertical lines across the image stack periodically every four columns. Generally spoken, it seems that only every fourth element is beeing indexed in the CudaArray. So I am wondering if there is somekind of error here resulting from sizeof(uchar)=1 and sizeof(uint)=4. There would obviously be the factor 4 :)
I am eager to here from you experts
Cheers Mika
I figured it out by myself. The kernel works with uint* d_output while the copy to the host is written into a uchar* h_output
uchar *h_output = (uchar*)malloc(width*height*depth);
checkCudaErrors(cudaMemcpy(h_output, d_output, width*height*depth*sizeof(uchar), cudaMemcpyDeviceToHost));
This led to this strange behavior
Well this is a bit of an embarrasing problem, I can't seem to load any sort of file through a program I made. My program fails everytime regardless of the file i try to load, so I'm not quite sure what's going on. Specifically, the program is supposed to be loading GLSL shaders, and it hasn't been working. Here is my code:
static inline GLuint GetProgram(const char* vert,const char* frag)
{
GLuint vertex,fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
fragment = glCreateShader(GL_FRAGMENT_SHADER);
std::string vCode,fCode;
std::ifstream vss(vert);
std::ifstream fss(frag);
if(vss.is_open())
{
std::string line;
while(std::getline(vss,line))
{
vCode += line + '\n';
}
}
else
{
OutputDebugStringA("ERROR READING VERTEX SHADER\n");
}
if(fss.is_open())
{
std::string line;
while(std::getline(fss,line))
{
fCode += line + '\n';
}
}
else
{
OutputDebugStringA("ERROR READING FRAGMENT SHADER\n");
}
vss.close();
fss.close();
char const* vsp = vCode.c_str();
char const* fsp = fCode.c_str();
glShaderSource(vertex,1,&vsp,NULL);
glShaderSource(fragment,1,&fsp,NULL);
OutputDebugStringA("Vertex Source:\n");
OutputDebugStringA(vsp + '\n');
OutputDebugStringA("Fragment Source:\n");
OutputDebugStringA(fsp + '\n');
glCompileShader(vertex);
glCompileShader(fragment);
GLuint prog = glCreateProgram();
glAttachShader(prog,vertex);
glAttachShader(prog,fragment);
glLinkProgram(prog);
char errbuf[1024];
GLsizei len;
glGetProgramInfoLog(prog,sizeof(errbuf),&len,errbuf);
OutputDebugStringA(errbuf);
glUseProgram(prog);
return prog;
}
vss.is_open() and fss.is_open() return false everytime. This problem only occurs with this program too, I have another that runs the exact same function listed and it works just fine.
How I am calling it:
GLuint program = Shader::GetProgram("v.vert","f.frag");
The directory:
Finally got it! Just had to use _getcwd(), move my files to that location and append the file names of the two shaders. Here is my code now:
static inline GLuint GetProgram(const char* vert,const char* frag)
{
GLuint vertex,fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
fragment = glCreateShader(GL_FRAGMENT_SHADER);
const char* dir = _getcwd(NULL,0);
std::string var1 = dir;
std::string vCode,fCode;
std::fstream vss;
std::fstream fss;
char* var2 = "/";
std::string vertpath = var1;
std::string fragpath = var1;
vertpath.append(var2);
fragpath.append(var2);
fragpath.append(frag);
vertpath.append(vert);
vss.open(vertpath);
fss.open(fragpath);
Help me with the error Source1.cpp(128): error C3861: 'InitShader': identifier not found when I have 2 files and one is InitShader.cpp. Both files compile. I believe that it is some setting in Visual Studio to make the one file find the other, since the InitShader is referenced by the other source file. The project looks like this in VS 2012
The code is
#include "Angel.h"
namespace Angel {
// Create a NULL-terminated string by reading the provided file
static char*
readShaderSource(const char* shaderFile)
{
FILE* fp = fopen(shaderFile, "r");
if ( fp == NULL ) { return NULL; }
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char* buf = new char[size + 1];
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
return buf;
}
// Create a GLSL program object from vertex and fragment shader files
GLuint
InitShader(const char* vShaderFile, const char* fShaderFile)
{
struct Shader {
const char* filename;
GLenum type;
GLchar* source;
} shaders[2] = {
{ vShaderFile, GL_VERTEX_SHADER, NULL },
{ fShaderFile, GL_FRAGMENT_SHADER, NULL }
};
GLuint program = glCreateProgram();
for ( int i = 0; i < 2; ++i ) {
Shader& s = shaders[i];
s.source = readShaderSource( s.filename );
if ( shaders[i].source == NULL ) {
std::cerr << "Failed to read " << s.filename << std::endl;
exit( EXIT_FAILURE );
}
GLuint shader = glCreateShader( s.type );
glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
glCompileShader( shader );
GLint compiled;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
if ( !compiled ) {
std::cerr << s.filename << " failed to compile:" << std::endl;
GLint logSize;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
char* logMsg = new char[logSize];
glGetShaderInfoLog( shader, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
delete [] s.source;
glAttachShader( program, shader );
}
/* link and error check */
glLinkProgram(program);
GLint linked;
glGetProgramiv( program, GL_LINK_STATUS, &linked );
if ( !linked ) {
std::cerr << "Shader program failed to link" << std::endl;
GLint logSize;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
char* logMsg = new char[logSize];
glGetProgramInfoLog( program, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
/* use program object */
glUseProgram(program);
return program;
}
} // Close namespace Angel block
The error sounds like it's coming from Source1.cpp not being communicating properly with InitShader.cpp
Since there doesn't appear to be a InitShader.h, I'm assuming you're trying to #include in Source1.cpp, which probably is where the error comes in, since it's expecting a header file.
I'd say try moving all your function definition from InitShader.cpp over to an InitShader.h file, and try including that in Source1.cpp. This is my best guess without seeing the actual code in Source1.cpp.
Alternate idea:
It appears that you're providing the function body in InitShader.cpp for the function prototypes I assume in Angel.h. Are you declaring functions in Angel.h that you then define in InitShader.cpp? If so, I'd highly recomend creating an Angel.cpp file and defining the Angel functions there instead. It would be much cleaner, and I have a hunch that it might end up being the problem you're facing.
I run into the following problem.I load my shaders from files.The shader program ,when trying to compile, throws these errors for the vertex and fragment shaders:
Vertex info
0(12) : error C0000: syntax error, unexpected $undefined at token ""
Fragment info
0(10) : error C0000: syntax error, unexpected $undefined at token ""
When inspecting the loaded content of the files I can see all kinds of garbage text is attached at the beginnings and the ends of the shader files.Like this one:
#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;
}ýýýý««««««««þîþîþîþ
The methods loading the shaders look as follows:
void ShaderLoader::loadShaders(char * vertexShaderFile,char *fragmentShaderFile){
vs = loadFile(vertexShaderFile,vlen);
fs = loadFile(fragmentShaderFile,flen);
}
char *ShaderLoader::loadFile(char *fname,GLint &fSize){
ifstream::pos_type size;
char * memblock;
string text;
// file read based on example in cplusplus.com tutorial
ifstream file (fname, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
fSize = (GLuint) size;
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "file " << fname << " loaded" << endl;
text.assign(memblock);
}
else
{
cout << "Unable to open file " << fname << endl;
exit(1);
}
return memblock;
}
I tried to change the encoding from UTF-8 top ANSI ,also tried to edit outside the visual studio but the problem still persists .Any help on this will be greatly appreciated.
You're using C++, so I suggest you leverage that. Instead of reading into a self allocated char array I suggest you read into a std::string:
#include <string>
#include <fstream>
std::string loadFileToString(char const * const fname)
{
std::ifstream ifile(fname);
std::string filetext;
while( ifile.good() ) {
std::string line;
std::getline(ifile, line);
filetext.append(line + "\n");
}
return filetext;
}
That automatically takes care of all memory allocation and proper delimiting -- the keyword is RAII: Resource Allocation Is Initialization. Later on you can upload the shader source with something like
void glcppShaderSource(GLuint shader, std::string const &shader_string)
{
GLchar const *shader_source = shader_string.c_str();
GLint const shader_length = shader_string.size();
glShaderSource(shader, 1, &shader_source, &shader_length);
}
void load_shader(GLuint shaderobject, char * const shadersourcefilename)
{
glcppShaderSource(shaderobject, loadFileToString(shadersourcefilename));
}
It looks like all you have to do is allocate one more byte of memory in which you can place a null ('\0'):
...
memblock = new char[1 + fSize];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
memblock[size] = '\0';
...
edit
I changed my code to use fSize in the array rather than size, since it is a GLint, which is just a typedef over an integer. Also, I tried this fix on my machine, and it works as far as I can tell - no junk at the beginning, and none at the end.