0
\$\begingroup\$

I am trying to draw a triangle which changes color over time. My implementation is by using uniform variable.

my fragment shader-

#version 330 core
out vec4 FragColor;
uniform float var;

void main()
{
    FragColor = vec4(var*0.2, var*0.333, var*0.7, 1.0f);
}  

in render loop

while (!glfwWindowShouldClose(window))
{
    time = 1.0f*fabs(sin(glfwGetTime()*3.1416f));
    processInput(window);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    shader1.use();
    shader1.setFloat("var", time);
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwPollEvents();
    glfwSwapBuffers(window);
}

But the triangle goes blue to dark. What is missing?

\$\endgroup\$
2
  • \$\begingroup\$ FragColor will output colors between (0,0,0) (black) and (0.2,0.333,0.7) (blue). What colors are you trying to get? \$\endgroup\$
    – gotanod
    Apr 4 at 7:54
  • \$\begingroup\$ It should go from dark to blue to dark to blue to dark to blue .... is it not doing that? is it staying dark? \$\endgroup\$
    – user253751
    Apr 12 at 0:59

1 Answer 1

1
\$\begingroup\$

your sin() will only fluctuate between -1 to 1, and u turn that into 0 - 1 by using the fabs function, which doesn't get amplified (multiplication by 1.0f). so the line

time = 1.0f*fabs(sin(glfwGetTime()*3.1416f));

will result in a vec4 color range of (0, 0, 0, 1) to (0.2, 0.333, 0.7, 1) in a uniform pace for all rgb elements. To get better results, define 3 variables and calculate the color coefficient for each RGB element separately, whcih results in a non-uniform pace for the color change, something like this (i use pseudo-code):


...
time = glfwGetTime();
float r_amp = fmod(time, 0.5f);
float g_amp = fmod(time, 1.0f);
float b_amp = fmod(time, 2.0f);
...

shader1.use();
shader1.setFloat("var_r", r_amp);
shader1.setFloat("var_g", g_amp);
shader1.setFloat("var_b", b_amp);
...

and in your fragment shader clamp those values to a 0 to 1 range (or do that on the cpu side):

#version 330 core
out vec4 FragColor;
uniform float var_r;
uniform float var_g;
uniform float var_b;

void main()
{
    FragColor = vec4(var_r*2, var_g*1, var_b*0.5, 1.0f);
}  

you can also resort to sin() for fluctuations as you did initially but u need to multiply time by a different coefficient for each var and then calculate the sin(). for now fmod() will be much easier to understand but later on especially in performance-critical settings, sin() is faster than fmod()

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .