View Full Version : how can I have the shader handle two different objects?

01-24-2017, 05:32 AM
I have a cube which has a texture on it (picture on each face of it), which I want to retain.

Also, I have a sphere that orbits the cube, which I just want to color.

Now, I can display the textures, or color the items with the fragment/vertex shader, but I would like to change the color of just the sphere, but leave the cube unchanged.

Ultimately, then, I want to apply lighting and shading to both objects, equally. But, want to start out with baby steps.

Here are my vertex and fragment shaders

//varying vec4 color;

//image texture
uniform sampler2D myTexture;
varying vec2 vTexCoord;

void main (void) {

//gl_FragColor = vec4(1.0, 0.5, 0.0, 0.0);
//one or the other gives me the desired results
gl_FragColor = texture2D(myTexture, vTexCoord);

and here is my vertex shader

//varying vec4 color;
varying vec2 vTexCoord;

void main(void) {
vTexCoord = vec2(gl_MultiTexCoord0);
//vTexCoord = gl_MultiTexCoord0;
//color = gl_Color;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

Dark Photon
01-24-2017, 07:08 AM
It looks like you've just about got the vertex color plumbed into your shader already.

Once you have that, you have options.

You could pass in a uniform that tells you whether to apply the texture or apply the color. But it might be simpler to just apply both, modulating them together (e.g. color * texture). Consider that 1 * X = X and X * 1 = X.

01-24-2017, 08:12 AM
Thanks for the reply Dark Photon,

I am not familiar enough with uniforms to know exactly what they are doing.

I assume I am close, because depending on which gl_FragColor I enable, I get the desired result.

But, how exactly would I go about implementing that?

I will mediate on it, in the interim=)


Dark Photon
01-24-2017, 05:32 PM
I am not familiar enough with uniforms to know exactly what they are doing.

Here's a wiki page in the OpenGL Wiki (http://www.opengl.org/wiki) on them: Uniform (GLSL) (https://www.khronos.org/opengl/wiki/Uniform_(GLSL)). Basically, they're values you can pass in from your C++ program that are effectively constant for all of the primitives in a draw call. You can use them to pass in state that doesn't need to change vertex-to-vertex or fragment-to-fragment.

However, if you just use the modulate approach, you probably don't need one.

If you don't have a good book on OpenGL programming, I'd suggest you pick one up. Alternatively, you can consult the online OpenGL Wiki (http://www.opengl.org/wiki), the OpenGL man pages, and various OpenGL tutorials around the net.