我在webgl中有一个包含多个对象的场景.对于每个对象,我想使用不同的顶点和片段着色器.我的第一个问题是,是否可以为每个对象设置一个着色器?我知道在opengl中是可能的.
这就是我所想到的类似的伪代码.任何示例将不胜感激.
glenableshader
draw triangle
gldisableshader
glenableshader
draw square
gldisableshader
谢谢
解决方法:
您几乎可以查找任何WebGL示例并将其转换为多个着色器示例.
伪代码
// At init time
for each shader program
create and compile vertex shader
create and compile fragment shader
create program and attach shaders
link program
record locations of attributes and uniforms
for each model/set of geometry/points/data
create buffer(s) for model
copy data into buffer(s) for model
for each texture
create texture
usually asynchronously load textures
// at draw time
clear
for each model
useProgram(program for model)
setup attributes for model
setup textures for model
set uniforms for model
draw
这与使用1个着色器程序绘制1个模型没有什么不同.只需执行相同的设置即可.
多一点代码…
设置属性看起来像
for each attribute used by model
gl.enableVertexAttribArray(attribLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferWithDataForAttribute);
gl.vertexAttribPointer(attribLocation, ...);
设置纹理(可能)看起来有点像
for each texture used by model
gl.activeTexture(gl.TEXTURE0 + ndx);
gl.bindTexture(gl.TEXTURE_2D, texture);
最后,您将使用该程序
gl.useProgram(programForModel);
for each uniform
gl.uniform???(uniformLocation, uniformValue);
gl.drawArrays(...)
or
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferOfIndicesForModel);
gl.drawElements(...);