Sign in to follow this  
Followers 0
space_cadet

OpenGL
OpenGL ES 2.0 on Android: how to render 500 cubes effectively

7 posts in this topic

Hi,

I am trying to simulate a starfield of rotating cubes moving towards the user:

[img]http://i.imgur.com/7d9zu.png[/img]

I am struggling to maintain a smooth animation on Android. I can't see why a Dual-core 1 GHz Cortex-A9 with a ULP GeForce GPU should not be able to do that. Here's what I do:

INITIALIZATION:

- Create a VBO containing 36 cube position vertices and 36 cube normal vertices, interleaved
- Set up a simple shader that takes positions, normals, color, MV matrix, MVP matrix, light position
- Connect the VBO to the shader's position and normal attribute respectively

EACH FRAME:

a] Movement (for each cube)

- calculate scaling matrix, rotation matrix A, translation matrix, rotation matrix B
- multiply all of the above matrices to obtain model matrix
- multiply model matrix and view matrix to obtain MV matrix
- multiply MV matrix and projection matrix to obtain MVP matrix

b] Draw (for each cube)

- hook up cube's MV matrix with shader (glUniformMatrix4fv)
- hook up cube's MVP matrix with shader (glUniformMatrix4fv)
- hook up cube's color constant with shader (glVertexAttrib4f)
- draw cube (glDrawArrays)

I have done a lot of profiling and timing analyzation, so I don't think I have any unintended performance leaks in my code. Rather, I believe there is a more general design flaw, and I hope someone can help me improve it.
0

Share this post


Link to post
Share on other sites
Do you have any profiling tools that allow you to measure CPU and GPU timings independently? The first step will be determining which processor is the bottleneck, so you can focus your optimisations usefully.

That said, a solution will probably involve call glDraw less often than once-per-cube.
On the CPU side, every "batch" of geometry has a certain amount of overhead, so you want to reduce the total amount of [font=courier new,courier,monospace]gl*[/font] calls, particularly [font=courier new,courier,monospace]glDraw*[/font] calls.
On the GPU side, you want every [font=courier new,courier,monospace]glDraw*[/font] "batch" to contain as many vertices and as many pixels as possible. It seems like many of your cubes cover hardly any pixels, which may greatly exaggerate the per-draw overheads.
1

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1353758793' post='5003722']That said, a solution will probably involve call glDraw less often than once-per-cube.[/quote]

True, but [i]how[/i] ? Since every cube needs its own scaling, rotation and translation, how can I combine glDrawArrays() calls?
0

Share this post


Link to post
Share on other sites
[quote name='space_cadet' timestamp='1353759859' post='5003725']
[quote name='Hodgman' timestamp='1353758793' post='5003722']That said, a solution will probably involve call glDraw less often than once-per-cube.[/quote]

True, but [i]how[/i] ? Since every cube needs its own scaling, rotation and translation, how can I combine glDrawArrays() calls?
[/quote]

Option 1: Software transform the vertices. That is, do the matrix multiply on the CPU, then you can send all the cubes in one go.
Option 2: 'Hardware skinning' style solution. Instead of doing one cube at a time, put 16* cubes into your VBO. The vertices for each cube have indices, which you use in your vertex shader to look up into an array of matrix uniforms.

From experience doing similar things on iOS, I'd expect option 1 to be the better choice.

*Probably you'll want this number to be as large as possible within the constaints of the max amount of uniform space your GPU supports. Edited by C0lumbo
2

Share this post


Link to post
Share on other sites
you don't need to do matrix mult to translate for example
1D, 2D or 3D translation is 3, 6 and 9 flops respectively

rotation is harder to optimize, but a 2D rotation is alot cheaper
0

Share this post


Link to post
Share on other sites

I know this thread is a month old, but I have invested serious thought and work into the project, and I'd like to post an update to show that I aprecciate your answers, and to help other people with similar issues.

 

 

PROFILING

 

 

Do you have any profiling tools that allow you to measure CPU and GPU timings independently? The first step will be determining which processor is the bottleneck, so you can focus your optimisations usefully.

 

 

 

I believe that you have a very good point here; I have mostly been "optimizing blindly", which is considered bad practice. I have tried / considered the following options:

 

 

1. Android SDK Tools: the profiler shipped with the SDK shows CPU time, but not GPU time. Also, it profiles my own application, but I would like to see what's going on in the whole system. Google has recognized this and published a tool for system-wide profiling called systrace, but it's only available for Jelly Bean. The same goes for dumpsys gfxinfo which in combination with the Jelly Bean developer option "Profile GPU Rendering" outputs a stat about how much time is spent processing, drawing and swapping UI. See Chet Haase and Guy Romain's excellent presentation about Android UI performance for more information about those tools. For me, they are not an option, I am stuck with Honeycomb for various reasons.

 

 

 

2. Log output: yes I know it is stone age, but I thought it would be interesting to see how much time my application spends in my move() (CPU) and draw() (GPU) methods. The results are not very conclusive; I guess this has to to with multithreading and the way Android handles vsync.

 

 

3. NVIDIA Tools: there is a tool for Tegra 2 platforms called PerfHUD ES that looks very promising: detailed information about draw calls and lots of other GPU-related information. I am currently trying to get this running on honeycomb. Any help aprecciated.

 

 

OPTIMIZING

 

 

 

Option 1: Software transform the vertices. That is, do the matrix multiply on the CPU, then you can send all the cubes in one go.
Option 2: 'Hardware skinning' style solution. Instead of doing one cube at a time, put 16* cubes into your VBO. The vertices for each cube have indices, which you use in your vertex shader to look up into an array of matrix uniforms.

 

 

 

Both of your options seem very reasonable approaches to take. I decided to implement option 2 first. The OpenGL ES specification calls this method "Dynamic Indexing".  It took me an hour to rearrange my application accordingly, and a whole day to find out how to get hold of the vertex index inside the shader and use it to address my transformation matrices. It's not straightforward on OpenGL ES 2.0 because for some fucking reason they decided to leave out the crucial gl_VertexID variable there. Sorry, but this tiny little detail really drove me mad. Anyways, the solution is quite simple, once you know how to do it. Anton Holmquist has a short, to-the-point blog post about it, which I wish I'd found earlier.

 

The one big drawback about this method is, like you pointed out, the limited uniform space. For those who don't have a clue what that is (like I did): it is the space available for declaring uniform variables in the shader. I read somewhere that this space relates to the amount / size of registers the GPU has - correct me if I'm wrong here. For anyone interested, calling glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS) will return a number that says how much uniform space you have on your system. The specification for OpenGL ES 2.0 says it has to be at least 128. The number is expressed in vectors, and since each matrix has 4 vectors, that means you could declare a maximum of 32 matrix variables or, in my case, two arrays of 16 matrices. In other words, I can batch a maximum of 16 cubes now. 

 

 

NEXT

 

Dynamic indexing has certainly improved performance, but I am not entirely happy yet. I will implement the abovementioned option 1, hoping to improve performance by shifting work from the GPU to the CPU and, as a next step, parallize the move() and draw() operations.

0

Share this post


Link to post
Share on other sites

Doing the the matrix calculations in software shouldn't be too bad. But if you are CPU limited (maybe the case on Android) then here is an alternative that does the matrix calculation on the GPU:

 

Pass a vec4 Rotation (rotX, rotY, rotZ, angle) to your vertex shader. Then calculate the rotation matrix in your shader:

 

[code]mat4 transform = mat4(1.0); //identity   ... make rotation matrix from axis and angle ...   gl_Position = projection * view * transform * a_position;[/code]

 

Theoretically you could put the Position and Normal attributes into a separate static VBO since they are unchanged (and update the view matrix instead). If you fill all your instance data in one go, you could end up with a single draw call per frame.

1

Share this post


Link to post
Share on other sites
I do think the software approach will beat the vertex shader approach, so you should probably go ahead and give that a shot.

But - I think you should be able to manage more than 16 cubes per batch. Firstly, you don't need a full 4x4 matrix - you can switch to 4x3 matrices and implicitly assume that the last row is 0, 0, 0, 1. You might need to transpose your matrices to achieve this.

Also, I don't think you need two arrays of matrices. I assume one of the matrices is for your normals, and one for the positions. But you can usually use the same matrix for your positions and your normals and simply ignore the position for the normals.

So, by my reckoning you should be able to manage 128/3=42 cubes each batch. Your GLSL code might end up looking a bit like this (untested, not compiled):

uniform float4 g_vMatrices[42*3];

...

vWorldPos.x = dot(g_vMatrices[iCubeIndexAttribute*3], float4(vPositionAttribute, 1.0));
vWorldPos.y = dot(g_vMatrices[iCubeIndexAttribute*3+1], float4(vPositionAttribute, 1.0));
vWorldPos.z = dot(g_vMatrices[iCubeIndexAttribute*3+2], float4(vPositionAttribute, 1.0));
vWorldNormal.x = dot(g_vMatrices[iCubeIndexAttribute*3], float4(vNormalAttribute, 0.0));
vWorldNormal.y = dot(g_vMatrices[iCubeIndexAttribute*3+1], float4(vNormalAttribute, 0.0));
vWorldNormal.z = dot(g_vMatrices[iCubeIndexAttribute*3+2], float4(vNormalAttribute, 0.0));


Oops - just realised you'd then need to transform the positions by the viewproj matrix which will take up a few more uniforms, so you'll end up with only 41 cubes per batch. Edited by C0lumbo
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By recp
      Hi,
      I'm working on new asset importer (https://github.com/recp/assetkit) based on COLLADA specs, the question is not about COLLADA directly
      also I'm working on a new renderer to render (https://github.com/recp/libgk) imported document.
      In the future I'll spend more time on this renderer of course, currently rendering imported (implemented parts) is enough for me
      assetkit imports COLLADA document (it will support glTF too),
      importing scene, geometries, effects/materials, 2d textures and rendering them seems working
      My actual confusion is about shaders. COLLADA has COMMON profile and GLSL... profiles,
      GLSL profile provides shaders for effects so I don't need to wory about them just compile, link, group them before render

      The problem occours in COMMON profile because I need to write shaders,
      Actually I wrote them for basic matrials and another version for 2d texture
      I would like to create multiple program but I am not sure how to split this this shader into smaller ones,

      Basic material version (only colors):
      https://github.com/recp/libgk/blob/master/src/default/shader/gk_default.frag
      Texture version:
      https://gist.github.com/recp/b0368c74c35d9d6912f524624bfbf5a3
      I used subroutines to bind materials, actually I liked it,
      In scene graph every node can have different program, and it switches between them if parentNode->program != node->program
      (I'll do scene graph optimizations e.g.  view frustum culling, grouping shaders... later)

      I'm going to implement transparency but I'm considering to create separate shaders,
      because default shader is going to be branching hell
      I can't generate shader for every node because I don't know how many node can be exist, there is no limit.
      I don't know how to write a good uber-shader for different cases:

      Here material struct:
      struct Material { ColorOrTexture emission; ColorOrTexture ambient; ColorOrTexture specular; ColorOrTexture reflective; ColorOrTexture transparent; ColorOrTexture diffuse; float shininess; float reflectivEyety; float transparency; float indexOfRefraction; }; ColorOrTexture could be color or 2d texture, if there would be single colorOrTex then I could split into two programs,
      Also I'm going to implement transparency, I am not sure how many program that I needed

      I'm considering to maintain a few default shaders for COMMON profile,
      1-no-texture, 2-one of colorOrTexture contains texture, 3-........

      Any advices in general or about how to optimize/split (if I need) these shaders which I provied as link?
      What do you think the shaders I wrote, I would like to write them without branching if posible,
      I hope I don't need to write 50+ or 100+ shaders, and 100+ default programs

      PS: These default shaders should render any document, they are not specific, they are general purpose...
             I'm compiling and linking default shaders when app launched

      Thanks
    • By CircleOfLight97
      Hi guys,
      I would like to contribute to a game project as a developer (open source possibly). I have some experiences in C/C++ in game development (perso projects). I don't know either unreal or unity but I have some knowledges in opengl, glsl and shading theory as I had some courses at university regarding to that. I have some knowledges in maths and basic in physics. I know a little how to use blender to do modelling, texturing and simple game assets (no characters, no animation no skinning/rigging). I have no game preferences but I like aventure game, dungeon crawler, platformers, randomly generated things. I know these kind of projects involve a lot of time and I'd be really to work on it but if there are no cleary defined specific design goals/stories/gameplay mechanics I would like to not be part of it x) and I would rather prefer a smaller but well defined project to work on that a huge and not 'finishable' one.
      CircleOfLight97
    • By gamesthatcouldbeworse
      Hi, I finally released KILL COMMANDO on gamejolt for free. It is a retro-funsplatter-shooter with C64 style. Give it a try.
    • By phil67rpg

      void TimerFunction(int value) {  glutPostRedisplay();  glutTimerFunc(1000, TimerFunction, 1); } void drawScene() {  glClear(GL_COLOR_BUFFER_BIT);      drawScene_bug();  TimerFunction(1);  eraseScene_bug(); // drawScene_bug_two(); // eraseScene_bug_two(); drawScene_ship(); drawScene_bullet();  glutSwapBuffers(); }
  • Popular Now