I've a problem with opengl shader compiling. The problem is that when I run the program, I obtain this error:
Vertex info
0(1) : error c0000: syntax error, unexpected '' at token ''
the same message is for the fragment object. At the end I obtain a 'program not validated' error. here's my initialization shader code:
struct ShadeState {
int gl_program_id = 0; // OpenGL program handle
int gl_vertex_shader_id = 0; // OpenGL vertex shader handle
int gl_fragment_shader_id = 0; // OpenGL fragment shader handle
};
// initialize the shaders
void init_shaders(ShadeState* state) {
// load shader code from files
auto vertex_shader_code = load_text_file("shade_vertex.glsl");
auto fragment_shader_code = load_text_file("shade_fragment.glsl");
auto vertex_shader_codes = (char *)vertex_shader_code.c_str();
auto fragment_shader_codes = (char *)fragment_shader_code.c_str();
//devono essere costanti altrimenti glShaderSource non li accetta
//auto vertex_codes = (const GLchar*)vertex_shader_codes;
//auto fragment_codes = (const GLchar*)fragment_shader_codes;
//GLint const vert_size = vertex_shader_code.size();
//GLint const frag_size = fragment_shader_code.size();
// create shaders
state->gl_vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); //come da documentazione
state->gl_fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); //come da documentazione
// load shaders code onto the GPU
//glShaderCode non esiste!
glShaderSource(state->gl_vertex_shader_id, 1, (const GLchar**)&vertex_shader_codes, NULL);
glShaderSource(state->gl_fragment_shader_id, 1, (const GLchar**)&fragment_shader_codes, NULL);
// compile shaders
glCompileShader(state->gl_vertex_shader_id);
glCompileShader(state->gl_fragment_shader_id);
// check if shaders are valid
//funzione presente in glcommon.h
error_if_glerror();
error_if_shader_not_valid(state->gl_vertex_shader_id);
error_if_shader_not_valid(state->gl_fragment_shader_id);
// create program
state->gl_program_id = glCreateProgram();
// attach shaders
glAttachShader(state->gl_program_id, state->gl_vertex_shader_id);
glAttachShader(state->gl_program_id, state->gl_fragment_shader_id);
// bind vertex attributes locations
//faccio il bind delle variabili in input del vertex shader
glBindAttribLocation(state->gl_program_id, 0, "vertex_pos"); // primo attributo in shade_vertex
glBindAttribLocation(state->gl_program_id, 1, "vertex_norm"); //secondo attributo in shade_vertex
// link program
glLinkProgram(state->gl_program_id);
// check if program is valid
//funzione presente in glcommon.h
error_if_glerror();
error_if_program_not_valid(state->gl_program_id);
}
How ca I resolve?
EDIT
shade_vertex.glsl
#version 120
attribute vec3 vertex_pos; // vertex position (in mesh coordinate frame)
attribute vec3 vertex_norm; // vertex normal (in mesh coordinate frame)
uniform mat4 mesh_frame; // mesh frame (as a matrix)
uniform mat4 camera_frame_inverse; // inverse of the camera frame (as a matrix)
uniform mat4 camera_projection; // camera projection
varying vec3 pos; // [to fragment shader] vertex position (in world coordinate)
varying vec3 norm; // [to fragment shader] vertex normal (in world coordinate)
// main function
void main() {
// compute pos and normal in world space and set up variables for fragment shader (use mesh_frame)
// project vertex position to gl_Position using mesh_frame, camera_frame_inverse and camera_projection
}
shade_fragment.glsl
#version 120
varying vec3 pos; // [from vertex shader] position in world space
varying vec3 norm; // [from vertex shader] normal in world space (need normalization)
uniform vec3 camera_pos; // camera position (center of the camera frame)
uniform vec3 ambient; // scene ambient
uniform int lights_num; // number of lights
uniform vec3 light_pos[16]; // light positions
uniform vec3 light_intensity[16]; // light intensities
uniform vec3 material_kd; // material kd
uniform vec3 material_ks; // material ks
uniform float material_n; // material n
// main
void main() {
// re-normalize normals
// use faceforward to ensure the normals points toward us
// accumulate ambient
vec3 c = vec3(0,0,0)
// foreach light
// compute point light color at pos
// compute light direction at pos
// compute view direction using camera_pos and pos
// compute h
// accumulate blinn-phong model
// output final color by setting gl_FragColor
gl_FragColor = vec4(c,1);
}
GLSL requires that a newline (\n) follow the #version directive.
I suspect your load_text_file() function is either not preserving newlines in the source text files or the text files themselves are missing newlines.
Other issues:
Your vertex shader needs to write to gl_Position.
Your fragment shader is missing a semicolon after vec3 c = vec3(0,0,0)
These (updated) shaders compile on my system:
#include <GL/glew.h>
#include <GL/glut.h>
#include <iostream>
struct Program
{
static GLuint Load( const char* vert, const char* geom, const char* frag )
{
GLuint prog = glCreateProgram();
if( vert ) AttachShader( prog, GL_VERTEX_SHADER, vert );
if( geom ) AttachShader( prog, GL_GEOMETRY_SHADER, geom );
if( frag ) AttachShader( prog, GL_FRAGMENT_SHADER, frag );
glLinkProgram( prog );
CheckStatus( prog );
return prog;
}
private:
static void CheckStatus( GLuint obj )
{
GLint status = GL_FALSE;
if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status );
if( status == GL_TRUE ) return;
GLchar log[ 1 << 15 ] = { 0 };
if( glIsShader(obj) ) glGetShaderInfoLog( obj, sizeof(log), NULL, log );
if( glIsProgram(obj) ) glGetProgramInfoLog( obj, sizeof(log), NULL, log );
std::cerr << log << std::endl;
exit( -1 );
}
static void AttachShader( GLuint program, GLenum type, const char* src )
{
GLuint shader = glCreateShader( type );
glShaderSource( shader, 1, &src, NULL );
glCompileShader( shader );
CheckStatus( shader );
glAttachShader( program, shader );
glDeleteShader( shader );
}
};
#define GLSL(version, shader) "#version " #version "\n" #shader
const char* vert = GLSL
(
120,
attribute vec3 vertex_pos; // vertex position (in mesh coordinate frame)
attribute vec3 vertex_norm; // vertex normal (in mesh coordinate frame)
uniform mat4 mesh_frame; // mesh frame (as a matrix)
uniform mat4 camera_frame_inverse; // inverse of the camera frame (as a matrix)
uniform mat4 camera_projection; // camera projection
varying vec3 pos; // [to fragment shader] vertex position (in world coordinate)
varying vec3 norm; // [to fragment shader] vertex normal (in world coordinate)
// main function
void main() {
// compute pos and normal in world space and set up variables for fragment shader (use mesh_frame)
// project vertex position to gl_Position using mesh_frame, camera_frame_inverse and camera_projection
gl_Position = vec4( 0, 0, 0, 1 );
}
);
const char* frag = GLSL
(
120,
varying vec3 pos; // [from vertex shader] position in world space
varying vec3 norm; // [from vertex shader] normal in world space (need normalization)
uniform vec3 camera_pos; // camera position (center of the camera frame)
uniform vec3 ambient; // scene ambient
uniform int lights_num; // number of lights
uniform vec3 light_pos[16]; // light positions
uniform vec3 light_intensity[16]; // light intensities
uniform vec3 material_kd; // material kd
uniform vec3 material_ks; // material ks
uniform float material_n; // material n
// main
void main() {
// re-normalize normals
// use faceforward to ensure the normals points toward us
// accumulate ambient
vec3 c = vec3(0,0,0);
// foreach light
// compute point light color at pos
// compute light direction at pos
// compute view direction using camera_pos and pos
// compute h
// accumulate blinn-phong model
// output final color by setting gl_FragColor
gl_FragColor = vec4(c,1);
}
);
void display()
{
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glewInit();
GLuint prog = Program::Load( vert, NULL, frag );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}
I resolved with the solution of genpfault. I had to write gl position and add the semicolon. Thanks to you all!
Related
I have a very basic engine based on OpenGL that can render polygons in any color to a resizeable window. I'm now trying to implement matrices for my shaders by giving the model, perspective and view matrices as uniforms via my shader. Before adding the uniforms everything worked as it should, I could even pass in a uniform vec2 to simulate a light source at my mouse position. The uniform mat4s doesn't work as well as the vec2s.
For debugging purposes I'm only rendering one yellow square centered on the screen. When using no uniforms the square shows as expected. i now try passing in one mat4, set as an identity matrix. In the vertex shader I'm multiplying gl_Position by the identity matrix I uniformed. When I run the program it only shows a black window.
I've tried manually creating an identity matrix in the vertex shader and multiplying gl_Position by that matrix instead of the uniform one. When I do that my yellow square shows as normal. This leads me to believe that the uniform mat4 doesn't get the correct values, however, I don't know how to check the values of the matrix when it's being used in the shader.
This is how my vertex shader looks:
#version 430 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec4 color;
out vec4 Color;
uniform mat4 model;
uniform mat4 view;
uniform mat4 project;
void main()
{
mat4 id;
id[0] = vec4(1.0, 0.0, 0.0, 0.0);
id[1] = vec4(0.0, 1.0, 0.0, 0.0);
id[2] = vec4(0.0, 0.0, 1.0, 0.0);
id[3] = vec4(0.0, 0.0, 0.0, 1.0);
Color = color;
gl_Position = id * vec4(position, 1.0);
}
The mat4 id is the manually created identity matrix, when changing id * to model * I get the black window.
This is how my fragment shader looks:
#version 430 core
in vec4 Color;
out vec4 outColor;
void main()
{
outColor = Color;
}
The shader is initialized by this code:
m_shaderID = glCreateProgram();
const char* vertexSource = ReadFile::readFile(vertpath);
const char* fragmentSource = ReadFile::readFile(fragpath);
GLint status;
// Vertex Shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE)
{
std::cout << "Failed to compile vertex shader!\nInfo log: " << std::endl;
char buffer[512];
glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glDeleteShader(vertexShader);
}
// Fragment Shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE)
{
std::cout << "Failed to compile fragment shader!\nInfo log: " << std::endl;
char buffer[512];
glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glDeleteShader(fragmentShader);
}
// Shader program
glAttachShader(m_shaderID, vertexShader);
glAttachShader(m_shaderID, fragmentShader);
glLinkProgram(m_shaderID);
glValidateProgram(m_shaderID);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
The matrix is created as a uniform by this code:
void Shader::setUniformmat4(const GLchar* name, glm::mat4 matrix)
{
for (int i = 0; i <= 3; i++)
printf("%f, %f, %f, %f\n", matrix[i].x, matrix[i].y, matrix[i].z, matrix[i].w);
glUniformMatrix4fv(glGetUniformLocation(m_shaderID, name), 1, GL_FALSE, glm::value_ptr(matrix));
}
The printf is for checking the values of the matrix as they are used to create the uniform, and they have the values of an identity matrix at that point.
The function setUniformmat4 is called by this code:
glm::mat4 model = glm::mat4(1.0);
shader.setUniformmat4("model", model);
When creating a lighting effect I create the uniform by calling this function:
void Shader::setUniformvec2(const GLchar* name, glm::vec2 vector)
{
glUniform2f(glGetUniformLocation(m_shaderID, name), vector.x, vector.y);
}
via this piece of code:
shader.setUniformvec2("light_pos", glm::vec2((x / window.getWidth()) * 2.0 - 1.0, 1.0 - 2.0 * (y / window.getHeight())));
Where x and y are the mouses coordinates. I then add the line
uniform vec2 light_pos;
To the fragment shader. This works no problem, and it traces the mouse perfectly. The function used for setting the uniform mat4 looks the same as the function for setting the uniform vec2, only difference is the 4fv for the mat4 and 2f for the vec2.
As you can see, I'm using glm for the matrices and vectors.
My main function looks like this:
Window window(720, 720, "Window");
Shader shader("shader.vert", "shader.frag");
glm::mat4 model = glm::mat4(1.0);
shader.setUniformmat4("model", model);
Renderer* renderer = new Renderer();
std::vector<StaticSprite*> sprites;
sprites.push_back(new StaticSprite(-0.5, -0.5, 0.0, 1.0, 1.0, glm::vec4(1.0, 1.0, 0.0, 1.0), &shader));
while (!window.closed())
{
window.clear();
shader.enable();
double x, y;
window.getMousePosition(x, y);
shader.setUniformvec2("light_pos", glm::vec2((x / window.getWidth()) * 2.0 - 1.0, 1.0 - 2.0 * (y / window.getHeight())));
for (StaticSprite* sprite : sprites)
renderer->submit(sprite);
renderer->flush();
shader.disable();
window.update();
}
return 0;
My question summarized is basically why are the values of the uniform mat4 not correct, is there any way to find out what those values are, and what should I change in the code to make the uniform mat4s work?
Please ask for any additional information needed to give an answer, I will happily provide anything I forgot to include.
glUniform* specify the value of a uniform variable for the current program object. This means the program has to be installed by glUseProgram before:
Shader shader("shader.vert", "shader.frag");
shader.enable(); // <--- this is missing
glm::mat4 model = glm::mat4(1.0);
shader.setUniformmat4("model", model);
Active program resources can be get from a program object which is not the "current" program (e.g. glGetUniformLocation). Note, the program object is a parameter of glGetUniformLocation.
But to set the value of a uniform by glUniform*, the program has to be the currently installed program.
I am trying to add some shaders to my glut scene objects.
At this time I am trying to implement "hello world" shaders
but when I use the default vertex shader, my objects dissapear.
shaders:
#define GLSL(version, shader) "#version " #version " core\n" #shader
const char* vert = GLSL
(
330,
layout (std140) uniform Matrices {
mat4 pvm;
} ;
in vec4 position;
out vec4 color;
void main()
{
color = position;
gl_Position = pvm * position ;
}
);
const char* frag = GLSL
(
330,
in vec4 color;
out vec4 outputF;
void main()
{
outputF = vec4(1.0, 0.5, 0.25, 1.0);
}
);
Compilation shows no error:
Compiling shader : vertex shader
VERTEX STATUS:1
Compiling shader : fragment shader
FRAGMENT STATUS:1
Linking program
PROGRAM STATUS:1
PROGRAM ID : 3
Before calling glUseProgram:
After calling glUseProgram:
After calling glUseProgram without attach vertex shader:
CODE for rendering:
int opengl_draw_path_gl(rendered_path_t *p) {
unsigned int num_vertices,j;
unsigned int face_size;
unsigned long i,num_elems;
vect_t *a,*b;
num_elems=p->num_prisms;
num_vertices=p->prism_faces;
face_size=num_vertices*2;
a=p->data+2; // saltem punt centre primera cara
b=a+face_size;
glColor4fv(p->color);
// dibuixem tapa inici
_opengl_draw_path_terminator(num_vertices,p->data,a);
// Dibuixem tots els prismes
glBegin(GL_TRIANGLE_STRIP);
for(i=0;i<num_elems;i++) {
for(j=0;j<num_vertices;j++) {
glNormal3fv((GLfloat *)(a+j*2));
glVertex3fv((GLfloat *)(a+j*2+1));
glNormal3fv((GLfloat *)(b+j*2));
glVertex3fv((GLfloat *)(b+j*2+1));
}
glNormal3fv((GLfloat *)(a));
glVertex3fv((GLfloat *)(a+1));
glNormal3fv((GLfloat *)(b));
glVertex3fv((GLfloat *)(b+1));
a+=face_size;
b+=face_size;
}
glEnd();
// dibuixem tapa final
_opengl_draw_path_terminator(num_vertices,b,a);
return 0;
}
First of all I recommend you, to read a tutorial about vertex array objects.
But, since you are drawing with glBegin and glEnd, which is deprecated, you have to use compatibility mode shaders. You have to use the deprecated built in uniforms gl_Vertex and gl_Normal, according to the OpenGL commands glVertex3fv and glNormal3fv.
Adapt your code somhow like this:
#define GLSL(version, shader) "#version " #version "\n" #shader
Vertex shader:
const char* vert = GLSL
(
110,
varying vec4 position;
varying vec3 normal;
void main()
{
position = gl_ModelViewMatrix * gl_Vertex;
normal = normalize( gl_NormalMatrix * gl_Normal.xyz );
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
);
Fragment shader:
const char* frag = GLSL
(
110,
varying vec4 position;
varying vec3 normal;
void main()
{
gl_FragColor = vec4(1.0, 0.5, 0.25, 1.0);
}
);
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
I have written a C++ program where I draw a teapot and apply lighting. It is itself simple, but I also use shaders. Simple I'm new with GLSL I just tried a simple fragment shader, but the screen output is inexplicable.
In this file I initialize glew in the init method, where I also compile the vertex and fragment shader. They're in the "vertex_shader" and "fragment_shader" files.
The thing you may not recognize is what's Light and Material. They're just some structs containing all info about the lights. I've tested these struct so I'm sure the work as expected. When I declare material=BlackPlastic I just set it to a default value defined with the define directive. I may also post this code if you think that the problem is there.
#include <GL/glew.h>
#include <GL/glut.h>
#include <iostream>
#include <fstream>
#include <vector>
#include "utility.hpp"
#define MAX_DIM 1000
GLfloat width=600, height=800;
GLuint vertex_shader, fragment_shader;
GLuint program;
const char* vertex_shader_filename= "vertex_shader";
const char* fragment_shader_filename= "fragment_shader";
Light light;
Material material;
void init()
{
// Inizializzazione di GLEW
glewInit();
if(GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
{
cout << "Supporto GLSL" << endl;
}
// Lettura e compilazione del vertex shader
GLchar* buffer= new GLchar[MAX_DIM];
ifstream stream;
streamsize count;
stream.open(vertex_shader_filename);
stream.read(buffer,MAX_DIM);
count= stream.gcount();
stream.close();
vertex_shader= glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, (const GLchar**)&buffer, &count);
glCompileShader(vertex_shader);
// Lettura, inizializzazione ed esecuzione del fragment shader
stream.open(fragment_shader_filename);
stream.read(buffer,MAX_DIM);
count= stream.gcount();
stream.close();
fragment_shader= glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, (const GLchar**)&buffer, &count);
glCompileShader(fragment_shader);
delete[] buffer;
// Creazione del programma
program= glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glUseProgram(program);
// Inizializzazione materiale e luce
material= BlackPlastic;
light= {vector<GLfloat>{-2,2,2,1} ,vector<GLfloat>{1,1,1,1},vector<GLfloat>{1,1,1,1},vector<GLfloat>{1,1,1,1} };
}
void display()
{
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,width/height,1,1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,-100,0,0,0,0,1,0);
// Illuminazione
glShadeModel(GL_SMOOTH);
material.apply(); // This just causes glMaterialfv to be called for the ambient, diffuse, specular and shininess values.
light.apply(); // This just causes glLightfv to be called for the ambient, diffuse and specular values
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
// Rendering
glClearColor(0.8,0.8,0.8,1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSolidTeapot(10);
glutSwapBuffers();
}
void reshape(int w, int h)
{
width=w;
height=h;
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow("test");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
init();
glutMainLoop();
return 0;
}
I don't think that the vertex shader is causing any problem, it just assigns the color and calculate the position, correctly. Also the fragment shader is apparently correct, this is the only instruction executed:
gl_FragColor = gl_Color;
If I do this I just see a white teapot. If instead I change this value to a whatever color:
gl_FragColor = vec4{0,0,1,1};
I get the teapot with the right color: black plastic. And I don't know why, I don't apply lighting here, I should calculate it.
I precisate that I executed the same identical program but without applying the shaders, and I got the teapot to have the right color.
First off all you are mixing the fixed function pipeline with "the newer stuff". This is a real bad practice because it could couse a lot of issues because you don't really know what is going on in background.
If you want to have real lighting with diffuse shaders you have to calculate the diffuse color on your own. It's a long time ago i used the ffp the last time so i searched for some shaders wich use it:
Vertex-Shader
varying vec3 normal;
varying vec3 v;
varying vec3 lightvec;
void main(void)
{
normal = normalize(gl_NormalMatrix * gl_Normal);
v = vec3(gl_ModelViewMatrix * gl_Vertex);
lightvec = normalize(gl_LightSource[0].position.xyz - v);
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
Fragment-Shader
varying vec3 normal;
varying vec3 v;
varying vec3 lightvec;
void main(void)
{
vec3 Eye = normalize(-v);
vec3 Reflected = normalize( reflect( -lightvec, normal ));
vec4 IAmbient = gl_LightSource[0].ambient * gl_FrontMaterial.ambient;
vec4 IDiffuse = gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * max(dot(normal, lightvec), 0.0);
vec4 ISpecular = gl_LightSource[0].specular * gl_FrontMaterial.specular * pow(max(dot(Reflected, Eye), 0.0), gl_FrontMaterial.shininess);
gl_FragColor = gl_FrontLightModelProduct.sceneColor + IAmbient + IDiffuse + ISpecular;
}
glLineStipple has been deprecated in the latest OpenGL APIs.
What is it replaced with?
If not replaced, how can I get a similar effect?
(I don't want to use a compatibility profile of course...)
Sorry, it hasn't been replaced with anything. The first idea coming to my mind for emulating it would be the geometry shader. You feed the geometry shader with a line, compute its screen space length and based on that you generate a variable number of sub lines between its start and end vertex.
EDIT: Perhaps you could also use a 1D texture with the alpha (or red) channel encoding the pattern as 0.0 (no line) or 1.0 (line) and then have the lines texture coordinate go from 0 to 1 and in the fragment chader you make a simple alpha test, discarding fragments with alpha below some threshold. You can facilitate the geometry shader to generate your line texCoords, as otherwise you need different vertices for every line. This way you can also make the texCoord dependent on the screen space length of the line.
The whole thing get's more difficult if you draw triangles (using polygon mode GL_LINE). Then you have to do the triangle-line transformation yourself in the geometry shader, putting in triangles and putting out lines (that could also be a reason for deprecating polygon mode in the future, if it hasn't already).
EDIT: Although I believe this question abandomned, I have made a simple shader triple for the second approach. It's just a minimal solution, feel free to add custom features yourself. I haven't tested it because I lack the neccessary hardware, but you should get the point:
uniform mat4 modelViewProj;
layout(location=0) in vec4 vertex;
void main()
{
gl_Position = modelViewProj * vertex;
}
The vertex shader is a simple pass through.
layout(lines) in;
layout(line_strip, max_vertices=2) out;
uniform vec2 screenSize;
uniform float patternSize;
noperspective out float texCoord;
void main()
{
vec2 winPos0 = screenSize.xy * gl_in[0].gl_Position.xy / gl_in[0].gl_Position.w;
vec2 winPos1 = screenSize.xy * gl_in[1].gl_Position.xy / gl_in[1].gl_Position.w;
gl_Position = gl_in[0].gl_Position;
texCoord = 0.0;
EmitVertex();
gl_Position = gl_in[1].gl_Position;
texCoord = 0.5 * length(winPos1-winPos0) / patternSize;
EmitVertex();
}
In the geometry shader we take a line and compute its screen space length in pixels. We then devide this by the size of the stipple pattern texture, which would be factor*16 when emulating a call to glLineStipple(factor, pattern). This is taken as 1D texture coordinate of the second line end point.
Note that this texture coordinate has to be interpolated linearly (noperspective interpolation specifier). The usual perpective-correct interpolation would cause the stipple pattern to "squeeze together" on farther away parts of the line, whereas we are explicitly working with screen-space values.
uniform sampler1D pattern;
uniform vec4 lineColor;
noperspective in float texCoord;
layout(location=0) out vec4 color;
void main()
{
if(texture(pattern, texCoord).r < 0.5)
discard;
color = lineColor;
}
The fragment shader now just performs a simple alpha test using the value from the pattern texture, which contains a 1 for line and a 0 for no line. So to emulate the fixed function stipple you would have a 16 pixel 1-component 1D texture instead of a 16bit pattern. Don't forget to set the pattern's wrapping mode to GL_REPEAT, about the filtering mode I'm not that sure, but I suppose GL_NEAREST would be a good idea.
But as said earlier, if you want to render triangles using glPolygonMode, it won't work this way. Instead you have to adapt the geometry shader to accept triangles and generate 3 lines for each triangle.
EDIT: In fact OpenGL 3's direct support for integer operations in shaders allows us to completely drop this whole 1D-texture approach and work straight-forward with an actual bit-pattern. Thus the geometry shader is slightly changed to put out the actual screen-size pattern coordinate, without normalization:
texCoord = 0.5 * length(winPos1-winPos0);
In the fragment shader we then just take a bit pattern as unsigned integer (though 32-bit in contrast to glLineStipple's 16-bit value) and the stretch factor of the pattern and just take the texture coordinate (well, no texture anymore actually, but nevermind) modulo 32 to get it's position on the pattern (those explicit uints are annoying, but my GLSL compiler says implicit conversions between int and uint are evil):
uniform uint pattern;
uniform float factor;
...
uint bit = uint(round(linePos/factor)) & 31U;
if((pattern & (1U<<bit)) == 0U)
discard;
To answer this question, we've to investigate first, what glLineStipple actually does.
See the image, where the quad at the left is drawn by 4 separated line segments using the primitive type GL_LINES.
The circle at the right is drawn by a consecutive polygon line, using the primitive type GL_LINE_STRIP.
When using line segments, the stipple pattern started at each segment. The pattern is restarted at each primitive.
When using a line strip, then the stipple pattern is applied seamless to the entire polygon. A pattern seamlessly continuous beyond vertex coordinates.
Be aware that the length of the pattern is stretched at the diagonals. This is possibly the key to the implementation.
For separate line segments, this is not very complicated at all, but for line strips things get a bit more complicated. The length of the line cannot be calculated in the shader program, without knowing all the primitives of the line. Even if all the primitives would be known (e.g. SSBO), then the calculation would have to be done in a loop.
See also Dashed lines with OpenGL core profile.
Anyway, it is not necessary to implement a geometry shader. The trick is to know the start of the line segment in the fragment shader. This easy by using a flat interpolation qualifier.
The vertex shader has to pass the normalized device coordinate to the fragment shader. Once with default interpolation and once with no (flat) interpolation. This causes that in the fragment shade, the first input parameter contains the NDC coordinate of the actual position on the line and the later the NDC coordinate of the start of the line.
#version 330
layout (location = 0) in vec3 inPos;
flat out vec3 startPos;
out vec3 vertPos;
uniform mat4 u_mvp;
void main()
{
vec4 pos = u_mvp * vec4(inPos, 1.0);
gl_Position = pos;
vertPos = pos.xyz / pos.w;
startPos = vertPos;
}
Additionally the varying inputs, the fragment shader has uniform variables. u_resolution contains the width and the height of the viewport. u_factor and u_pattern are the multiplier and the 16 bit pattern according to the parameters of glLineStipple.
So the length of the line from the start to the actual fragment can be calculated:
vec2 dir = (vertPos.xy-startPos.xy) * u_resolution/2.0;
float dist = length(dir);
And fragment on the gap can be discarded, by the discard command.
uint bit = uint(round(dist / u_factor)) & 15U;
if ((u_pattern & (1U<<bit)) == 0U)
discard;
Fragment shader:
#version 330
flat in vec3 startPos;
in vec3 vertPos;
out vec4 fragColor;
uniform vec2 u_resolution;
uniform uint u_pattern;
uniform float u_factor;
void main()
{
vec2 dir = (vertPos.xy-startPos.xy) * u_resolution/2.0;
float dist = length(dir);
uint bit = uint(round(dist / u_factor)) & 15U;
if ((u_pattern & (1U<<bit)) == 0U)
discard;
fragColor = vec4(1.0);
}
This implementation is much easier and shorter, then using geometry shaders. The flat interpolation qualifier is supported since GLSL 1.30 and GLSL ES 3.00. In this version geometry shaders are not supported.
See the line rendering which was generated with the above shader.
The shader gives a proper result line segments, but fails for line strips, since the stipple pattern is restarted at each vertex coordinate.
The issue can't even be solved by a geometry shader. This part of the question remains still unresolved.
For the following simple demo program I've used the GLFW API for creating a window, GLEW for loading OpenGL and GLM -OpenGL Mathematics for the math. I don't provide the code for the function CreateProgram, which just creates a program object, from the vertex shader and fragment shader source code:
#include <vector>
#include <string>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <gl/gl_glew.h>
#include <GLFW/glfw3.h>
std::string vertShader = R"(
#version 330
layout (location = 0) in vec3 inPos;
flat out vec3 startPos;
out vec3 vertPos;
uniform mat4 u_mvp;
void main()
{
vec4 pos = u_mvp * vec4(inPos, 1.0);
gl_Position = pos;
vertPos = pos.xyz / pos.w;
startPos = vertPos;
}
)";
std::string fragShader = R"(
#version 330
flat in vec3 startPos;
in vec3 vertPos;
out vec4 fragColor;
uniform vec2 u_resolution;
uniform uint u_pattern;
uniform float u_factor;
void main()
{
vec2 dir = (vertPos.xy-startPos.xy) * u_resolution/2.0;
float dist = length(dir);
uint bit = uint(round(dist / u_factor)) & 15U;
if ((u_pattern & (1U<<bit)) == 0U)
discard;
fragColor = vec4(1.0);
}
)";
GLuint CreateVAO(std::vector<glm::vec3> &varray)
{
GLuint bo[2], vao;
glGenBuffers(2, bo);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, bo[0] );
glBufferData(GL_ARRAY_BUFFER, varray.size()*sizeof(*varray.data()), varray.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
return vao;
}
int main(void)
{
if ( glfwInit() == 0 )
return 0;
GLFWwindow *window = glfwCreateWindow( 800, 600, "GLFW OGL window", nullptr, nullptr );
if ( window == nullptr )
return 0;
glfwMakeContextCurrent(window);
glewExperimental = true;
if ( glewInit() != GLEW_OK )
return 0;
GLuint program = CreateProgram(vertShader, fragShader);
GLint loc_mvp = glGetUniformLocation(program, "u_mvp");
GLint loc_res = glGetUniformLocation(program, "u_resolution");
GLint loc_pattern = glGetUniformLocation(program, "u_pattern");
GLint loc_factor = glGetUniformLocation(program, "u_factor");
glUseProgram(program);
GLushort pattern = 0x18ff;
GLfloat factor = 2.0f;
glUniform1ui(loc_pattern, pattern);
glUniform1f(loc_factor, factor);
//glLineStipple(2.0, pattern);
//glEnable(GL_LINE_STIPPLE);
glm::vec3 p0(-1.0f, -1.0f, 0.0f);
glm::vec3 p1(1.0f, -1.0f, 0.0f);
glm::vec3 p2(1.0f, 1.0f, 0.0f);
glm::vec3 p3(-1.0f, 1.0f, 0.0f);
std::vector<glm::vec3> varray1{ p0, p1, p1, p2, p2, p3, p3, p0 };
GLuint vao1 = CreateVAO(varray1);
std::vector<glm::vec3> varray2;
for (size_t u=0; u <= 360; u += 8)
{
double a = u*M_PI/180.0;
double c = cos(a), s = sin(a);
varray2.emplace_back(glm::vec3((float)c, (float)s, 0.0f));
}
GLuint vao2 = CreateVAO(varray2);
glm::mat4(project);
int vpSize[2]{0, 0};
while (!glfwWindowShouldClose(window))
{
int w, h;
glfwGetFramebufferSize(window, &w, &h);
if (w != vpSize[0] || h != vpSize[1])
{
vpSize[0] = w; vpSize[1] = h;
glViewport(0, 0, vpSize[0], vpSize[1]);
float aspect = (float)w/(float)h;
project = glm::ortho(-aspect, aspect, -1.0f, 1.0f, -10.0f, 10.0f);
glUniform2f(loc_res, (float)w, (float)h);
}
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 modelview1( 1.0f );
modelview1 = glm::translate(modelview1, glm::vec3(-0.6f, 0.0f, 0.0f) );
modelview1 = glm::scale(modelview1, glm::vec3(0.5f, 0.5f, 1.0f) );
glm::mat4 mvp1 = project * modelview1;
glUniformMatrix4fv(loc_mvp, 1, GL_FALSE, glm::value_ptr(mvp1));
glBindVertexArray(vao1);
glDrawArrays(GL_LINES, 0, (GLsizei)varray1.size());
glm::mat4 modelview2( 1.0f );
modelview2 = glm::translate(modelview2, glm::vec3(0.6f, 0.0f, 0.0f) );
modelview2 = glm::scale(modelview2, glm::vec3(0.5f, 0.5f, 1.0f) );
glm::mat4 mvp2 = project * modelview2;
glUniformMatrix4fv(loc_mvp, 1, GL_FALSE, glm::value_ptr(mvp2));
glBindVertexArray(vao2);
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei)varray2.size());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
See also
Dashed line in OpenGL3?
OpenGL ES - Dashed Lines
Since I struggled a bit (no pun intended) to get it right, I thought it could be useful to others if I shared my implementation of a set of stippling shaders based on Christian Rau's version.
To control pattern density, the fragment shader requires the number of patterns nPatterns per unit length of the viewport - instead of setting a factor. Also included is an optional clipping plane feature.
The rest is mainly commenting and cleaning.
Free to use to all intents and purposes.
The vertex shader:
#version 330
in vec4 vertex;
void main(void)
{
// just a pass-through
gl_Position = vertex;
}
The geometry shader:
#version 330
layout(lines) in;
layout(line_strip, max_vertices = 2) out;
uniform mat4 pvmMatrix;
uniform mat4 mMatrix;
uniform mat4 vMatrix;
out vec3 vPosition; // passed to the fragment shader for plane clipping
out float texCoord; // passed to the fragment shader for stipple pattern
void main(void)
{
// to achieve uniform pattern density whatever the line orientation
// the upper texture coordinate is made proportional to the line's length
vec3 pos0 = gl_in[0].gl_Position.xyz;
vec3 pos1 = gl_in[1].gl_Position.xyz;
float max_u_texture = length(pos1 - pos0);
// Line Start
gl_Position = pvmMatrix * (gl_in[0].gl_Position);
texCoord = 0.0;
// depth position for clip plane
vec4 vsPos0 = vMatrix * mMatrix * gl_Position;
vPosition = vsPos0.xyz / vsPos0.w;
EmitVertex(); // one down, one to go
// Line End
gl_Position = pvmMatrix * (gl_in[1].gl_Position);
texCoord = max_u_texture;
// depth position for clip plane
vec4 vsPos1 = vMatrix * mMatrix * gl_Position;
vPosition = vsPos0.xyz / vsPos0.w;
EmitVertex();
// done
EndPrimitive();
}
The fragment shader:
#version 330
uniform int pattern; // an integer between 0 and 0xFFFF representing the bitwise pattern
uniform int nPatterns; // the number of patterns/unit length of the viewport, typically 200-300 for good pattern density
uniform vec4 color;
uniform vec4 clipPlane0; // defined in view-space
in float texCoord;
in vec3 vPosition;
layout(location=0) out vec4 fragColor;
void main(void)
{
// test vertex postion vs. clip plane position (optional)
if (vPosition.z > clipPlane0.w) {
discard;
return;
}
// use 4 bytes for the masking pattern
// map the texture coordinate to the interval [0,2*8[
uint bitpos = uint(round(texCoord * nPatterns)) % 16U;
// move a unit bit 1U to position bitpos so that
// bit is an integer between 1 and 1000 0000 0000 0000 = 0x8000
uint bit = (1U << bitpos);
// test the bit against the masking pattern
// Line::SOLID: pattern = 0xFFFF; // = 1111 1111 1111 1111 = solid pattern
// Line::DASH: pattern = 0x3F3F; // = 0011 1111 0011 1111
// Line::DOT: pattern = 0x6666; // = 0110 0110 0110 0110
// Line::DASHDOT: pattern = 0xFF18; // = 1111 1111 0001 1000
// Line::DASHDOTDOT: pattern = 0x7E66; // = 0111 1110 0110 0110
uint up = uint(pattern);
// discard the bit if it doesn't match the masking pattern
if ((up & bit) == 0U) discard;
fragColor = color;
}