5
我在写一个使用javascript和webgl的游戏引擎。为了测试它,我写了一个绘制立方体的程序。为了这个程序的工作,我必须在调用绑定缓冲区之后调用vertexAttribPointer,但在我调用绘制三角形之前。我想知道这个方法究竟做了什么,为什么我必须按这个顺序调用这些方法?vertexAttribPointer的用途是什么?
我最好的猜测是它初始化属性,但我不明白为什么它必须在客户端调用,如果是这样的话。
我已经包括下面的一些来源。一切都是用打字稿写的。对于完整的源代码见github.com/dkellycollins/nemesis
设置着色器:
var cubeShader = new shaderProgram();
cubeShader.addShader(shaders.colorVertexShader);
cubeShader.addShader(shaders.colorFragmentShader);
cubeShader.init();
cubeShader.enableAttrib("position", 3, 4 * (3 + 3), 0);
cubeShader.enableAttrib("color", 3, 4 * (3 + 3), 3 * 4);
ShaderProgram:
class shaderProgram {
constructor() {
this.Id = gl.createProgram();
}
public Id;
public addShader(shader:WebGLShader[]):void {
if(shader instanceof Array) {
shader.forEach(s => {
gl.attachShader(this.Id, s);
});
} else {
gl.attachShader(this.Id, shader);
}
}
public init():void {
gl.linkProgram(this.Id);
}
public setActive() {
gl.useProgram(this.Id);
}
public enableAttrib(attribName: string, index: number, stride:number, offset: number) {
var attrib = gl.getAttribLocation(this.Id, attribName);
gl.enableVertexAttribArray(attrib);
gl.vertexAttribPointer(attrib, index, gl.FLOAT, false, stride, offset);
}
public setFloatAttrib(attribName:string, value:number) {
var attrib = gl.getAttribLocation(this.Id, attribName);
gl.vertexAttrib1f(attrib, value);
}
public setMatrix(uniName: string, value: number[]) {
var uniform = gl.getUniformLocation(this.Id, uniName);
gl.uniformMatrix4fv(uniform, false, value);
}
}
渲染立方体:
public render():void {
gl.drawElements(gl.TRIANGLES, this._triangles, gl.UNSIGNED_SHORT, 0);
}
顶点着色器来源:
attribute vec3 position; //the position of the point
uniform mat4 Pmatrix;
uniform mat4 Vmatrix;
uniform mat4 Mmatrix;
attribute vec3 color; //the color of the point
varying vec3 vColor;
void main(void) { //pre-built function
gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.); //0. is the z, and 1 is w
vColor=color;
}
那么,为什么必须完成属性?制服不需要这样做。不应该webgl能够确定索引,偏移量和步幅,只是从属性是一个vec3还是我缺少什么? – dkellycollins 2014-10-31 15:48:05
它将无法找出跨度(完全取决于程序员如何交错数据,但是紧密排列的缺省值为0),并且有些人使用半浮点数或整数或短数据(和缓冲区只存储没有类型信息的字节序列) – 2014-10-31 15:57:42
我想我现在明白了。我并没有把所有属性都从数组缓冲区中获取数据。感谢您的帮助! – dkellycollins 2014-10-31 20:19:44