Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is instanced array slower than glDrawElement?

Tags:

c++

opengl

glsl

in my program I want to draw many spheres. 1st I create vertices,indices for sphere then bind them to voa/vbo/ibo. After that I create 1000 random model Matrices. Now I have 2 ways to Draw the mesh.

  1. just loop 1000 times through list of ModelMatrices calling glDrawElements. Where matrix MVP is computed on CPU and sent to shader like as uniform.
  2. bind all Matrices to additional VBO and send them to shader like as "in" variable. Then call just once with glDrawElementsInstanced.

in test program I draw 1000 spheres (around 20milions vertices) When I use 1st method I get around 27FPS while 2nd decrease performance to 19FPS.In theory 2nd method should achieve better performance then 1st.

Here is the code.

  • Binding matrices to VBO http://pastebin.com/iX9tUWfY
  • Drawing http://pastebin.com/FsSXcnqK http://pastebin.com/8WMrUiu1
  • Vertex Shader http://pastebin.com/39m34PZk

I think that the bottleneck is this multiplication in vertex shader (VP * ModelMatrix) ,because it needs to be done for each (vertex in mesh)*1000.

What can be upgraded and what am I doing wrong?

like image 694
user1075940 Avatar asked Dec 07 '22 11:12

user1075940


1 Answers

Instancing is not always a win. It's the kind of optimization you have to profile for to see if it's worth doing.

In general, instancing is a win if you're rendering lots of instances (1000 is quite a bit, but not enough. Think 10,000) which contain a modest number of vertices (20,000 is probably too many. Look more into 100-3000 or so). Also, your per-instance data is needlessly large; you use a matrix when you could have easily used a vector and a quaternion.

The purpose of instancing is to reduce CPU overhead. Specifically the CPU per-draw-call overhead and state-change. With 20 million total vertices, odds are good that the CPU overhead of 1000 draw calls and state changes isn't your biggest problem.

like image 131
Nicol Bolas Avatar answered Dec 09 '22 15:12

Nicol Bolas