我如何使用 C 和 OpenGL 实现一个例程,使背景颜色从一种颜色很好地过渡到另一种颜色,然后再返回,重复?我调色板中的所有颜色都具有 3 位精度。从 0.000 到 1.000。让颜色分量以统一的时间到达第二种颜色变得很复杂,更不用说调整过渡速度了。我现在可以保持在 0.001。
最佳答案
在 genpfault 的回答中回答你的问题:
glm::mix
(以及 GLSL 的)基本上就是做 linear interpolation .在代码中可能意味着类似的东西
struct Color
{
float r, g, b;
};
Color lerp(Color a, Color b, float t)
{
Color c;
c.r = (1-t)*a.r + t*b.r;
c.g = (1-t)*a.g + t*b.g;
c.b = (1-t)*a.b + t*b.b;
return c;
}
现在,用于返回一些来回效果的常用函数是 cosine function .
余弦给你一个介于 -1 和 1 之间的值,所以你可能想在 0 和 1 之间缩放它。这可以使用
float t = cos(x) * 0.5 + 0.5; // *0.5 gets to [-0.5, 0.5], +0.5 gets to [0,1]
然后您使用此 t
来计算您的颜色。 x
可以是当前时间乘以某个有助于控制插值速度的值。
编辑: 使用 gpenfault 的代码作为起点,你可以做这种事情(如果它造成任何问题我将其删除):
// g++ main.cpp -lglut -lGL
#include <GL/glut.h>
#include <cmath>
int dstTime = 0; // milliseconds
struct Color
{
float r, g, b;
};
Color makeColor(float r, float g, float b)
{
Color c = { r, g, b };
return c;
};
Color lerp(Color a, Color b, float t)
{
Color c;
c.r = (1-t)*a.r + t*b.r;
c.g = (1-t)*a.g + t*b.g;
c.b = (1-t)*a.b + t*b.b;
return c;
}
void display()
{
const int curTime = glutGet( GLUT_ELAPSED_TIME );
// figure out how far along duration we are, between 0.0 and 1.0
const float t = std::cos(float(curTime) * 0.001) * 0.5 + 0.5;
// interpolate between two colors
Color curColor = lerp(makeColor(0.0, 0.0, 0.0), makeColor(1.0, 1.0, 1.0), t);
glClearColor( curColor.r, curColor.g, curColor.b, 1 );
glClear( GL_COLOR_BUFFER_BIT );
glutSwapBuffers();
}
void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 400,400 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}
关于c - OpenGL 背景颜色渐变器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316082/