Drawing many shapes in WebGL

后端 未结 3 1340
小鲜肉
小鲜肉 2020-11-27 07:36

I was reading tutorials from here.



        
相关标签:
3条回答
  • 2020-11-27 08:06

    Create your buffers separately for each object you want on the scene otherwise they won't be able to move and use shader effects independently.

    But that is in case your objects are different. From what I got here I think you just want to draw the same shape more than once on different positions right?

    The way you go about that is you just set that translationLocation uniform right there with a different translation matrix after drawing the shape for the first time. That way when you draw the shape again it will be located somewhere else and not in top of the other one so you can see it. You can set all those transformation matrices differently and then just call gl.drawElements again since you're going to draw the same buffers that are already in use.

    0 讨论(0)
  • 2020-11-27 08:10

    In pseudo code

    At init time

    • Get a context (gl) from the canvas element.
    • for each shader
      • create shader
      • look up attribute and uniform locations
    • for each shape
      • initialize buffers with the shape
    • for each texture
      • create textures and/or fill them with data.

    At draw time

    • for each shape
      • if the last shader used is different than the shader needed for this shape call gl.useProgram
      • For each attribute needed by shader
        • call gl.enableVertexAttribArray, gl.bindBuffer and gl.vertexAttribPointer for each attribute needed by shape with the attribute locations for the current shader.
      • For each uniform needed by shader
        • call gl.uniformXXX with the desired values using the locations for the current shader
      • call gl.drawArrays or if the data is indexed called gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferOfIndicesForCurrentShape) followed by gl.drawElements

    Common Optimizations

    1) Often you don't need to set every uniform. For example if you are drawing 10 shapes with the same shader and that shader takes a viewMatrix or cameraMatrix it's likely that viewMatrix uniform or cameraMatrix uniform is the same for every shape so just set it once.

    2) You can often move the calls to gl.enableVertexAttribArray to initialization time.

    0 讨论(0)
  • 2020-11-27 08:10

    Having multiple meshes in one buffer (and rendering them with a single gl.drawArrays() as you're suggesting) yields better performance in complex scenes but obviously at that point you're not able to change shader uniforms (such as transformations) per mesh.

    If you want to have the meshes running around independently, you'll have to render each one separately. You could still keep all the meshes in one buffer to avoid some overhead from gl.bindBuffer() calls but imho that won't help that much, at least not in simple scenes.

    0 讨论(0)
提交回复
热议问题