WebGL - 如何传递无符号字节顶点属性颜色值?

Mar*_*kus 17 opengl-es glsl webgl

我的顶点由具有以下结构的数组组成:

[     Position      ][        colour        ]
[float][float][float][byte][byte][byte][byte]
Run Code Online (Sandbox Code Playgroud)

传递顶点位置没有问题:

gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.vertexAttribPointer(this.material.aVertexPosition, 3, gl.FLOAT, false, 4, 0);
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何将颜色传递给着色器.不幸的是,在glsl着色器中使用整数是不可能的,所以我必须使用浮点数.如何将无符号字节颜色值转换为glsl浮点颜色值?我为r,g和b做了这样的尝试,但颜色都搞砸了:

gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.vertexAttribPointer(this.material.aR, 1, gl.BYTE, false, 15, 12);
Run Code Online (Sandbox Code Playgroud)

顶点着色器(colouredPoint.vs)

precision highp float;

attribute vec3 aVertexPosition;
attribute float aR;
attribute float aG;
attribute float aB;

uniform mat4 world;
uniform mat4 view;
uniform mat4 proj;

varying vec3 vVertexColour;

void main(void){
    gl_PointSize = 4.0;  
    gl_Position = proj * view * world * vec4(aVertexPosition, 1.0);
    vVertexColour = vec3(aR, aG, aB);
} 
Run Code Online (Sandbox Code Playgroud)

像素着色器(colouredPoint.fs)

precision highp float;

varying vec3 vVertexColour;

void main(void){
    gl_FragColor = vec4(vVertexColour, 1);
} 
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 27

gl.vertexAttribPointer(this.material.aVertexPosition, 3, gl.FLOAT, false, 4, 0);
gl.vertexAttribPointer(this.material.aR, 1, gl.BYTE, false, 15, 12);
Run Code Online (Sandbox Code Playgroud)

你的步伐应该是16,而不是15,当然不是4.

此外,每种颜色不需要是单独的属性.四个字节可以是vec4输入.哦,你的颜色应该是标准化的无符号字节.也就是说,当着色器获取它们时,范围[0,255]上的值应缩放为[0,1].因此,你想要的是:

gl.vertexAttribPointer(this.material.aVertexPosition, 3, gl.FLOAT, false, 16, 0);
gl.vertexAttribPointer(this.material.color, 4, gl.UNSIGNED_BYTE, true, 16, 12);
Run Code Online (Sandbox Code Playgroud)

哦,属性不是材料.你不应该这样称呼他们.