美文网首页
webGL缓冲区对象数据的存取

webGL缓冲区对象数据的存取

作者: jb3d | 来源:发表于2018-10-11 15:03 被阅读124次

将变量传入顶点着色器

1.创建缓冲区对象:var vertexBuffer = gl.createBuffer();

2.将缓冲区对象绑定到target上:gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);

这一步是为了允许使用vertexBuffer表示的缓冲区对象,并确定这个缓冲区对象是什么类型(作用),其中gl.ARRAY_BUFFER表示缓冲区对象包含了顶点的数据。另一个可能的参数gl.ELEMENT_ARRAY_BUFFER表示缓冲区对象包含了顶点的索引。

3.将数据(以顶点坐标为例)写入缓冲区对象:gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);

4.将缓冲区对象分配给对应的attribute变量:

var a_Position = gl.getAttribLocation(gl.program,'a_Position');

gl.vertexAttribPointer(a_Position,2,gl.FLOAT,false,0,0);

5.开启attribute变量:gl.enableVertexAttribArray(a_Position);

创建一个缓冲区对象传多种值

如果我们要同时传顶点的坐标和顶点的尺寸那么我们可以创建两个缓冲区对象重复上面的操作即可。但是如果我们要传多种值(比如点的颜色,纹理坐标等)不能一直创建缓冲区吧?这里我们可以通过只创建一个缓冲区来传多个值:

顶点坐标和顶点尺寸交错存储,例如第一个点的位置为0.0,0.5并且它的尺寸为10,下皆同。

var verticesSizes =new Float32Array([

// Coordinate and size of points

  0.0,0.5,10.0,// the 1st point

  -0.5, -0.5,20.0,// the 2nd point

  0.5, -0.5,30.0  // the 3rd point

]);

var n =3;// The number of vertices

// Create a buffer object

var vertexSizeBuffer = gl.createBuffer();

if (!vertexSizeBuffer) {

console.log('Failed to create the buffer object');

return -1;

}

// Bind the buffer object to target

gl.bindBuffer(gl.ARRAY_BUFFER,vertexSizeBuffer);

gl.bufferData(gl.ARRAY_BUFFER,verticesSizes, gl.STATIC_DRAW);

var FSIZE =verticesSizes.BYTES_PER_ELEMENT;

//Get the storage location of a_Position, assign and enable buffer

var a_Position = gl.getAttribLocation(gl.program,'a_Position');

if (a_Position <0) {

console.log('Failed to get the storage location of a_Position');

return -1;

}

gl.vertexAttribPointer(a_Position,2, gl.FLOAT,false,FSIZE *3,0);

gl.enableVertexAttribArray(a_Position);// Enable the assignment of the buffer object

// Get the storage location of a_PointSize

var a_PointSize = gl.getAttribLocation(gl.program,'a_PointSize');

if(a_PointSize <0) {

console.log('Failed to get the storage location of a_PointSize');

return -1;

}

gl.vertexAttribPointer(a_PointSize,1, gl.FLOAT,false,FSIZE *3,FSIZE *2);

gl.enableVertexAttribArray(a_PointSize);// Enable buffer allocation

// Unbind the buffer object

gl.bindBuffer(gl.ARRAY_BUFFER,null);

这里shader代码为

var VSHADER_SOURCE =

'attribute vec4 a_Position;\n' +

'attribute float a_PointSize;\n' +

'void main() {\n' +

'  gl_Position = a_Position;\n' +

'  gl_PointSize = a_PointSize;\n' +

'}\n';

// Fragment shader program

var FSHADER_SOURCE =

'void main() {\n' +

'  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +

'}\n';

最后

gl.clearColor(0.0,0.0,0.0,1.0);

gl.clear(gl.COLOR_BUFFER_BIT);

// Draw three points

gl.drawArrays(gl.POINTS,0,n);

相关文章

网友评论

      本文标题:webGL缓冲区对象数据的存取

      本文链接:https://www.haomeiwen.com/subject/jiivaftx.html