三角形頂點隨時間做圓周運動,片段著色器根據時間在紅、綠兩色間線性插值,呈現動態變色與移動效果。
#version 400
layout(location = 0) in vec3 vertexPosition;
uniform float loopDuration;
uniform float time;
void main() {
float timeScale = 6.2831853f / loopDuration; // 2π
float currTime = mod(time, loopDuration);
vec4 offset = vec4(cos(currTime*timeScale)*0.5, sin(currTime*timeScale)*0.5, 0, 0);
gl_Position = vec4(vertexPosition, 1.0) + offset;
}
#version 400
out vec4 fragColor;
uniform float fragLoopDuration;
uniform float time;
const vec4 colorA = vec4(1,0,0,1);
const vec4 colorB = vec4(0,1,0,1);
void main() {
float t = mod(time, fragLoopDuration) / fragLoopDuration;
fragColor = mix(colorA, colorB, t);
}
float positionData[] = { 0.8,0,0, -0.8,0,0, 0,0.8,0 };
void RenderScene() {
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vaoHandle);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
// 每幀更新 uniform
GLint tLoc = glGetUniformLocation(programHandle, "time");
GLint ldLoc = glGetUniformLocation(programHandle, "loopDuration");
GLint fldLoc = glGetUniformLocation(programHandle, "fragLoopDuration");
glUniform1f(ldLoc, 5.0f);
glUniform1f(fldLoc, 10.0f);
glUniform1f(tLoc, glutGet(GLUT_ELAPSED_TIME)/1000.0f);
glutSwapBuffers();
glutPostRedisplay();
}
glClearColor(1,0,0,1))。mod() 實現週期性時間。mix() 線性插值兩顏色。