1.5.1 Exercises
1.5.1 Exercises
1
Adjust the vertex shader so that the triangle is upside down
2
Specify a horizontal offset via a uniform and move the triangle to the right side of the screen in the vertex shader using this offset value
3
Output the vertex position to the fragment shader using the out keyword and set the fragment's color equal to this vertex position (see how even the vertex position values are interpolated across the triangle). Once you managed to do this; try to answer the following question: why is the bottom-left side of our triangle black?
1
颠倒triangle,把底边的两个顶点的纵坐标和顶点的纵坐标对调。
实现:
float vertices[] = {
// positions // colors
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom right
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom left
0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f // top
};效果:
2
uniform 变量存储 横向偏移量,在vertex shader 中使用该变量,让triangle 显示在屏幕右侧。
- uniform 变量的定义
uniform float horizontalOffset;- 设置uniform 的值
shader.setFloat("horizontalOffset", 0.5);向右为正,偏移0.5
- 使用偏移量
gl_Position = vec4(aPos.x + horizontalOffset, aPos.y, aPos.z, 1.0);
//gl_Position = vec4(aPos, 1.0);
//gl_Position.x += horizontalOffset;本来想的是通过以下方式对aPos 进行修改
aPos.x += horizontalOffset;
aPos = vec3(aPos.x + horizontalOffset, aPos.y, aPos.z);但是均报错:
ERROR::SHADER_COMPILATION_ERROR of type: VERTEX
ERROR: 0:13: 'assign' : l-value required "aPos" (cannot modify an attribute)对于定义的attribute (in 类型变量)只能从vertex data 读取 或 由上一个 stage 传递,不能修改。
所以只能对输出变量进行修改
4. 效果
3
使用vertex shader 中的 aPos值作为 颜色值
实现:
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
out vec4 ourColor;
void main()
{
gl_Position = vec4(aPos, 1.0);
ourColor = gl_Position;
}#version 330 core
out vec4 FragColor;
in vec4 ourColor;
void main()
{
FragColor = ourColor;
}效果:
为什么triangle中左下角的一部分是黑色?
| 顶点 | rgb颜色 | rgb01 | NDC坐标值 |
|---|---|---|---|
| 左侧 | (0,127,0) | (0,0.498,0) | (-0.5,0.5,0) |
| 右侧 | (127,127,0) | (0.5,0.5,0) | |
| 下 | (0,0,0) | (0,-0.5,0) |
颜色的取值范围是0~1,对于超出范围的值-0.5,向上取值为0,所以左侧顶点的颜色值为(0,0.498,0)

左下角的顶点的x,y坐标值都小于0,所以其对应的颜色值都被向上取值为0,导致这一部分所有fragment 的颜色都是黑色。