WebGL---5.初入3D
一、索引缓冲对象
索引缓冲对象(Element Buffer Object,EBO,也叫Index Buffer Object,IBO)。
假设我们不再绘制一个三角形而是绘制一个矩形。我们可以绘制两个三角形来组成一个矩形(OpenGL主要处理三角形)。这会生成下面的顶点的集合:
float vertices[] = {
// 第一个三角形
0.5f, 0.5f, 0.0f, // 右上角
0.5f, -0.5f, 0.0f, // 右下角
-0.5f, 0.5f, 0.0f, // 左上角
// 第二个三角形
0.5f, -0.5f, 0.0f, // 右下角
-0.5f, -0.5f, 0.0f, // 左下角
-0.5f, 0.5f, 0.0f // 左上角
};
可以看到,有几个顶点叠加了。我们指定了右下角和左上角两次!一个矩形只有4个而不是6个顶点,这样就产生50%的额外开销。当我们有包括上千个三角形的模型之后这个问题会更糟糕,这会产生一大堆浪费。更好的解决方案是只储存不同的顶点,并设定绘制这些顶点的顺序。这样子我们只要储存4个顶点就能绘制矩形了,之后只要指定绘制的顺序就行了。
索引缓冲对象的工作方式正是这样的。和顶点缓冲对象一样,EBO也是一个缓冲,它专门储存索引,OpenGL调用这些顶点的索引来决定该绘制哪个顶点。所谓的索引绘制(Indexed Drawing)正是我们问题的解决方案。首先,我们先要定义(不重复的)顶点,和绘制出矩形所需的索引:
float vertices[] = {
0.5f, 0.5f, 0.0f, // 右上角
0.5f, -0.5f, 0.0f, // 右下角
-0.5f, -0.5f, 0.0f, // 左下角
-0.5f, 0.5f, 0.0f // 左上角
};
unsigned int indices[] = { // 注意索引从0开始!
0, 1, 3, // 第一个三角形
1, 2, 3 // 第二个三角形
};
创建索引缓冲对象:
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices), gl.STATIC_DRAW);
使用glDrawElements时,我们会使用当前绑定的索引缓冲对象中的索引进行绘制:
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
二、实例代码
<html>
<canvas id='c' width='640' height='480'></canvas>
<script type="x-shader/x-vertex" id="vertex-shader">
attribute vec4 a_position;
attribute vec4 a_color;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
varying lowp vec4 v_color;
void main(){
gl_Position = projection * view * model * a_position;
v_color = a_color;
}
</script>
<script type="x-shader/x-fragment" id="fragment-shader">
//需要声明浮点数精度,否则报错No precision specified for (float)
precision mediump float;
varying lowp vec4 v_color;
void main(){
gl_FragColor = v_color;
}
</script>
<script src="WebGLUtils.js"> </script>
<script src="gl-matrix.js"></script>
<script>
var rotation = 0.0
var gl = createGLContext('c')
// alert(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS))
//创建shader program
var program = createProgramFromElementId(gl,'vertex-shader','fragment-shader');
gl.useProgram(program);
function initBuffers(gl,program){
// 坐标数据写入GPU缓冲区
const positions = [
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
];
var FSIZE = positions.BYTES_PER_ELEMENT;
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// 向着色器传递坐标数据
var a_position = gl.getAttribLocation(program,"a_position");
gl.enableVertexAttribArray(a_position);
gl.vertexAttribPointer(a_position,3,gl.FLOAT,false,3*FSIZE,0);
// 颜色数据写入GPU缓冲区
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[1.0, 1.0, 0.0, 1.0], // Right face: yellow
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// 向着色器传递颜色数据
var a_color = gl.getAttribLocation(program,"a_color");
gl.enableVertexAttribArray(a_color);
gl.vertexAttribPointer(a_color,4,gl.FLOAT,false,4*FSIZE,0);
// 创建索引缓冲对象
const indices = [
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
];
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices), gl.STATIC_DRAW);
}
const buffers = initBuffers(gl,program);
function drawScene(gl,deltaTime){
gl.clearColor(0.0, 0.0, 0.0, 1.0)
gl.clearDepth(1.0)
gl.enable(gl.DEPTH_TEST)
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//-------创建投影矩阵-----------//
var projection = mat4.create()
// 视野,观察空间的大小
const fieldOfView = 45 * Math.PI / 180;
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
mat4.perspective(projection,
fieldOfView,
aspect,
zNear,
zFar);
// mat4.ortho(projection,0.0, 800, 0.0, 600, 0.1, 100.0)
var projection_matrix = gl.getUniformLocation(program, 'projection')
gl.uniformMatrix4fv(projection_matrix,false,projection)
//---------------------------//
//-------创建模型矩阵-----------//
var model = mat4.create()
mat4.rotate(model,model,rotation,[0,0,1])
mat4.rotate(model,model,rotation*.7,[0,1,0])
var model_matrix = gl.getUniformLocation(program, 'model')
gl.uniformMatrix4fv(model_matrix,false,model)
//----------------------------//
//-------创建观察矩阵-----------//
var view = mat4.create()
mat4.translate(view,view,[-0.0, 0.0, -6.0])
var view_matrix = gl.getUniformLocation(program, 'view')
gl.uniformMatrix4fv(view_matrix,false,view)
//----------------------------//
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
rotation += deltaTime;
}
var old = 0
function render(now) {
now *= 0.001; // convert to seconds
const deltaTime = now - old;
old = now;
drawScene(gl,deltaTime);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
</script>
</html>