opengl - OpenGL GLSL 将颜色作为整数发送到着色器以分解为 vec4 RGBA
问题描述
我可以将颜色作为 4 个浮点数发送到着色器 - 没问题。但是我想将它作为整数(或无符号整数,并不重要,重要的是 32 位)发送并在着色器上的 vec4 中分解。
我使用 OpenTK 作为 OpenGL 的 C# 包装器(尽管它应该只是一个直接包装器)。
让我们考虑一个最简单的着色器,它的顶点包含位置(xyz)和颜色(rgba)。
顶点着色器:
#version 150 core
in vec3 in_position;
in vec4 in_color;
out vec4 pass_color;
uniform mat4 u_WorldViewProj;
void main()
{
gl_Position = vec4(in_position, 1.0f) * u_WorldViewProj;
pass_color = in_color;
}
片段着色器:
#version 150 core
in vec4 pass_color;
out vec4 out_color;
void main()
{
out_color = pass_color;
}
让我们创建顶点缓冲区:
public static int CreateVertexBufferColor(int attributeIndex, int[] rawData)
{
var bufferIndex = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, bufferIndex);
GL.BufferData(BufferTarget.ArrayBuffer, sizeof(int) * rawData.Length, rawData, BufferUsageHint.StaticDraw);
GL.VertexAttribIPointer(attributeIndex, 4, VertexAttribIntegerType.UnsignedByte, 0, rawData);
GL.EnableVertexAttribArray(attributeIndex);
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
return bufferIndex;
}
我在顶点着色器中得到了 vec4 'in_color' 的全零。不知道出了什么问题。
我发现的最接近的东西:https ://www.opengl.org/discussion_boards/showthread.php/198690-I-cannot-send-RGBA-color-as-unsigned-int 。
同样在 VertexAttribIPointer 中,我将 0 作为步幅传递,因为我确实有 VertexBufferArray 并保持数据分离。因此,每个顶点的颜色紧密排列为 32 位(每种颜色)。
解决方案
当着色器中的输入是浮点数(vec4)时,您必须使用 VertexAttribPointer 而不是 VertexAttribIPointer。
将标准化参数设置为 GL_TRUE。
规格 说:
glVertexAttribPointer,如果 normalized 设置为 GL_TRUE,则表示以整数格式存储的值将被映射到范围 [-1,1](对于有符号值)或 [0,1](对于无符号值)。访问并转换为浮点数。否则,值将直接转换为浮点数而不进行规范化。
推荐阅读
- c++ - 返回对局部变量的引用的问题...?
- c# - 远端没有完成握手就关闭了websocket连接
- list - 如何根据相似的值对列表进行分组
- python - Python + KivyMD 和代码优化上的小部件之间的交互和删除
- php - VSCode + Lando:Xdebug 不会停止
- reactjs - React-Redux Redux Action 被多次调用
- python - numpy中的3d矩阵乘法
- xcode - 为 iOS Simulator-i386 构建 Nativescript,但尝试链接为 iOS Simulator-x86_64 构建的文件
- javascript - 日志中的 ValidationError 项
- javascript - Javascript:填充表格的行/单元格,新数据不会覆盖现有的单元格数据