Dmi*_*try 4 shader buffer webgl
现在我有三个独立的顶点缓冲区:1.XYZ缓冲区2.NX,NY,NZ缓冲区3.紫外缓冲区
所以这是8个浮点数.将来还会添加切线和bitangent信息,所以+6浮点数.
以下是我为着色器声明它们的方法:
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);
shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
Run Code Online (Sandbox Code Playgroud)
在这里,我将它们传递给着色器程序:
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexCoordBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexNormalBuffer);
gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexTextureCoordBuffer);
gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
Run Code Online (Sandbox Code Playgroud)
由于缓冲区是独立的,我可以在着色器中将它们定义为vec3和vec2:
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
Run Code Online (Sandbox Code Playgroud)
但是,如果我将它们组合到一个缓冲区,每个顶点有8个浮点数呢?所以,项目大小将是8:
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexCoordBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 8, gl.FLOAT, false, 0, 0);
Run Code Online (Sandbox Code Playgroud)
但是如何在着色器中访问它们?vec8?有最大的vec4!那我该怎么办?
您可以使用stride和offset参数(当前设置为0)创建一个包含每个顶点所有属性的缓冲区,以定义属性的交错.事实上,我听说你应该这样做,以改善每个顶点的内存访问的位置.
步幅是每个顶点的总字节数(而不是相同属性的出现之间的间距),而偏移量是特定属性第一次出现的字节索引.因此,要获取示例属性并从单个缓冲区中读取它们:
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexAttrBuffer);
var step = Float32Array.BYTES_PER_ELEMENT;
var total = 3 + 3 + 2;
var stride = step * total;
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 3, gl.FLOAT, stride, 0);
gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, 3, gl.FLOAT, false, stride, step * 3);
gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, stride, step * 6);
Run Code Online (Sandbox Code Playgroud)
缓冲区将从Float32Array
其元素中加载
[px1, py1, pz1, nx1, ny1, nz1, u1, v1,
px2, py2, pz2, nx2, ny2, nz2, u2, v2,
...]
Run Code Online (Sandbox Code Playgroud)