Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL: glColor3f() and glVertex3f() with shader

Can I use glColor3f(), glVertex3f() or other API functions with shader? I wrote a shader for draw a colorful cube and it works fine. My vertex shader and fragment shader look like this

#vertext shader
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
out vec4 vertexColor;
void main()
{
    gl_Position = proj * view * model * vec4(aPos.x, aPos.y, aPos.z, 1.0);
    vertexColor = vec4(aColor, 1.0);
};

#fragment shader
#version 330 core
in vec4 vertexColor;
out vec4 FragColor;
void main(){
    FragColor = vertexColor;
};

Noe, I try to use gl functions along with my colorful cube. Let's say I have some draw code like this.

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -1, 0, 0, 0, 0, 1, 0);
glColor3f(1.0, 0.0, 0.0);
glLineWidth(3);
glBegin(GL_LINES);
glVertex3f(-1, -1, 0);
glVertex3f(1, 1, 0);

Since I used glUseProgram() to use my own shader. The above gl functions doesn't seems to work as expect (coordinates and color are both wrong). How does function like glVertex3f() pass vertex to shader? And how do the shaders should look like when using gl function to draw?

like image 793
Josh Chiu Avatar asked Jan 24 '26 09:01

Josh Chiu


1 Answers

Can I use glColor3f(), glVertex3f() or other API functions with shader?

Yes you can.

However, you need to use a Compatibility profile OpenGL Context and you are limited to a GLSL 1.20 vertex shader and the Vertex Shader Built-In Attributes (e.g. gl_Vertex, gl_Color). You can combine a GLSL 1.20 vertex shader with your fragment shader. The matrices in the fixed function matrix stack can be accessed with Built-In Uniforms like gl_ModelViewProjectionMatrix.
All attributes and uniforms are specified in detail in the OpenGL Shading Language 1.20 Specification.

A suitable vertex shader can look like this:

#version 120

varying vec4 vertexColor;

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    vertexColor = gl_Color;
};
#version 330

in vec4 vertexColor;
out vec4 FragColor;

void main(){
    FragColor = vertexColor;
};
like image 149
Rabbid76 Avatar answered Jan 26 '26 22:01

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!