简体   繁体   中英

How to apply a fragment shader to only one object in OpenGL?

I'm just beginning to learn OpenGL. With all of the tutorials I've seen, they demonstrate using a fragment shader to set the color of all the objects in view. What I haven't found yet is how you would use a fragment shader on just one of the objects, giving different objects different colors. How do you do that?

To provide background to the question, I'm drawing a simple scene with a house and a road in 2d. I have discovered how to set the colors of each of my objects (the main body of the house, the window, etc) using the fixed graphics pipeline, I just don't understand how to set the colors using fragment shaders.

Any clarification would be greatly appreciated, including correction if I'm misunderstanding something.

Before you draw an object with glDrawArrays or glDrawElements , pass the color to a shader as a variable.

http://www.opengl.org/sdk/docs/man/xhtml/glUniform.xml

Sample GLSL fragment shader:

uniform vec4 u_color;

void main(void)
{
     gl_FragColor = u_color;
 }

I would expand on this answer but I am being lazy. Hope it helps somewhat. There are a lot of tutorials online, just search for glsl, glUniform4f, etc.

To provide background to the question, I'm drawing a simple scene with a house and a road in 2d. I have discovered how to set the colors of each of my objects (the main body of the house, the window, etc) using the fixed graphics pipeline, I just don't understand how to set the colors using fragment shaders.

As RobertRouhani said , make the color a uniform and change it for each object.


How to apply a fragment shader to only one object in OpenGL?

You can simply change the shader program with glUseProgram and rendering calls after it will use the different shader.

See this: https://gamedev.stackexchange.com/questions/22216/using-multiple-shaders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM