Search code examples
openglglsllight

Inter dependency between gl_color and material


  1. In the fixed pipeline, what happens of the color set by gl_color when using a material?

  2. Is there a way to retrieve the color set by gl_color in a glsl fragment shader?


Solution

  • See OpenGL 2.1 API Specification - 2.15.3 Shader Variables, page 76

    Vertex Attributes

    Vertex shaders can access built-in vertex attribute variables corresponding to the per-vertex state set by commands such as Vertex, Normal, Color. .....

    See OpenGL Shading Language 1.20 Specification - 7.3 Vertex Shader Built-In Attributes, page 49:

    The following attribute names are built into the OpenGL vertex language and can be used from within a vertex shader to access the current values of attributes declared by OpenGL.

    attribute vec4 gl_Color;
    

    This means, the color which is set by glColor* can be accessed by the attribute attribute vec4 gl_Color; in the vertex shader.


    See [OpenGL Shading Language 1.20 Specification - 7.5 Built-In Uniform State, page 50]:

    As an aid to accessing OpenGL processing state, the following uniform variables are built into the OpenGL Shading Language.

    .....

    struct gl_MaterialParameters {
        vec4 emission; // Ecm
        vec4 ambient; // Acm
        vec4 diffuse; // Dcm
        vec4 specular; // Scm
        float shininess; // Srm
    };
    uniform gl_MaterialParameters gl_FrontMaterial;
    uniform gl_MaterialParameters gl_BackMaterial;
    

    This means, that the material properties which are set by glMaterial, can be accessed by the built-in uniform variables gl_FrontMaterial, gl_BackMaterial.


    See also OpenGL Shading Language (GLSL) Quick Reference Guide


    Referring to the additional question in the comment:

    And do you know which shader model (Gouraud, Phong...) is used by the old fixed pipeline, when only a color is set?

    Phong shading is not possibel in the OpenGL fixed function pipeline. See Legacy opengl - Why is phong shading not possible?

    Except you implement phong shading in your own shader. See Per Fragment Lighting

    In general the shading model can be set by glShadeModel, which can be either GL_SMOOTH or GL_FLAT.


    Further note:

    If Lighting is enabled (glEnable(GL_LIGHTING)), then then you have to set the color (gl_Color) by glMaterial.

    But if additionally GL_COLOR_MATERIAL is enabled (glEnable(GL_COLOR_MATERIAL)), then you can specify that the material parameters track the current color, by glColorMaterial.

    e.g.

    glEnable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    

    See How lighting works