# OpenGL Optimize drawing lots of objects

This topic is 4648 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm working on a 2D project in OpenGL and now trying to optimize it, and basically I wondered if you could take a look at the code and tell me if there are any faster ways of doing it. I think it's the drawing that is time consuming and that's why I posted it here in the OpenGL department. The part that I am interested in handles the units, I have a chain where every unit knows the adress to the previous and the next unit, and one controller that knows the adress to the first and last unit. Every frame the controller tells the first unit to update itself, then the first unit tells the next unit to update, etc etc. For example I tried removing the glLoadIdentity() and positioning the unit relative to the last unit, but that was no success. Here is the code that every unit executes:
void unit::Update()
{

//calculate the direction to the target

if (TC.tank1->getX() > x)
dir = atanf((y - TC.tank1->getY()) / (TC.tank1->getX() - x));
else
dir = pi - atanf((y - TC.tank1->getY()) / (x - TC.tank1->getX()));

x += v*cosf(dir);
y -= v*sinf(dir);

//////////////////////////////////////
//	Perform collision detection //
//////////////////////////////////////
float r=18.0f;
if ((TC.tank1->getX() - x) < r && (TC.tank1->getX() - x) > -r)
if (TC.tank1->getY() - y < r && TC.tank1->getY() - y > -r)
{
//the unit is inside the tank quad
}

//////////////////////////////////////
//         Draw the unit	    //
//////////////////////////////////////
glTranslatef(x,y,-1.0f);

glRotatef(-dir*57.29577, 0, 0, 1);

//	glNormal3f( 0.0f, 0.0f, 1.0f);

glTexCoord2f(0.0f, 0.0f); glVertex3f(-16.0f, -16.0f,  0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(16.0f, -16.0f,  0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(16.0f, 16.0f,  0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-16.0f, 16.0f,  0.0f);

glEnd();

// if there are more units, update them too
if (unit_next != 0)
unit_next->Update();

delete this;
}


Here is the class declaration (not really important?):
class unit
{
public:
float getX();
float getY();
unit *unit_next;		//keeps the adress to the next unit, creates one big chain of units
unit *unit_previous;	//keeps the adresss to the previous....

void Update();
private:
float x;
float y;
float dir;		//the current direction to target
float v;		//velocity

};



##### Share on other sites
You could use a Display list to draw the quad. That is if you are drawing a lot of them.

##### Share on other sites
Quote:
 Original post by nefthyYou could use a Display list to draw the quad. That is if you are drawing a lot of them.

Every unit consists of one textured quad so I guess display lists wont help much.

##### Share on other sites
This may be a little too common sense, but sometimes it is overlooked, just make sure you aren't rendering units you can't see. Back when I was using OpenGL for 2d, I just brute force drew everything and got a FPS of 50ish, which is passable, but when I culled out everything that isn't visible, I was got an FPS of 500.

The one thing that also could be slowing down your rendering is using OpenGL's immediate mode. You could dump the units into a VB and render from that, that could give you a boost.

##### Share on other sites
Quote:
 Original post by PureWHi, I'm working on a 2D project in OpenGL and now trying to optimize it, and basically I wondered if you could take a look at the code and tell me if there are any faster ways of doing it. I think it's the drawing that is time consuming and that's why I posted it here in the OpenGLdepartment.

dont guess, profile.
Also, what kind of speeds are you getting right now on what kind of machine?

##### Share on other sites
JohnnyCasil: The units are visible at all times so that wont work.

_the_phantom_: I acctually tried drawing the units in one frame out of ten, wich resulted in higher speeds and a flickering screen.
At the moment I can draw approximately 4000 units on the screen with 100fps (I think it's 100fps, since my monitor runs with 100hz and v-sync seems to be enabled) before the cpu reaches 100%.

##### Share on other sites
confirm the fps first without vsync on, then use some kind of profiler (either a proper external program or your own in built code to time different sections of the game), both with and without vsync.
If the rendering isnt the bottle neck all the improvememts in the world wont help you

##### Share on other sites
OpenGL has a relatively low overhead for draw calls. But assuming that you are being limited by draw calls, try doing this,

//called 1000+ times
draw(unit);

draw(Unit* u)
{
}

At the end of all your draw calls,
call something like submitBuffer();

submitBuffer()
{
glVertexPointer(...);
glTexCoordPointer(...);
glDrawArrays(.., vertexArray.data);
}

Basically the idea is to buffer all your quads and draw them throught 1 big vertex array to minimise draw calls. this is the approach i use for my fonts. Also i am assuming that all your units are using the same texture. Otherwise you will have to make seperate buffers for different textures. To minimise this, you should try to use 1 big texture containing all your sprites instead of 1 small texture for each sprite.

##### Share on other sites
One thing you can do to reduce your CPU overhead is to make a sin/cos/atan table. I noticed you're doing a lot of trig on each unit every frame, and these are pretty expensive calls. Especially since today's memory is so big, it's worthwhile to make a table of all sin/cos/atan values. You'll probably want to experiment with the step size to find something that gives you good results, then all you have to do each frame is round to the nearest step and look it up in a table...much faster.

If you were just computing a new camera position, this wouldn't be an issue, but since you're doing trig on each of 4000 objects, it really adds up.

You may not see a significant framerate increase, but I promise you'll be clearing up CPU cycles for the rest of your engine that you'll need later!

##### Share on other sites
the only time u would want to maybe use the tables is inside a tight loop that uses those functions, the above doesnt adhere to that.

to the OP the best way to speed it up would be to do all the math yourself, ie loop first through all the units and workout the 4 corners of the quad. and then once u have all the units sussed draw them in one fell swoop

itll save in calling the following commands for every unit
glTranslatef(x,y,-1.0f);
glRotatef(-dir*57.29577, 0, 0, 1);

##### Share on other sites
now adays its probably faster to perform the maths than use lookup tables, the biggest source of latancy on anything past a P2 is more likely to be memory than a cos/sin operation, latancy on a memory lookup is in 100s of intructions, a sin/cos instruction is going to take much less time over all (factor in out of order execution and pipelining and instructions are going to win 99 times out of 100)

##### Share on other sites
Quote:
 Original post by GamerSgOpenGL has a relatively low overhead for draw calls. But assuming that you are being limited by draw calls, try doing this,//called 1000+ timesdraw(unit);draw(Unit* u){vertexArray.addVerticesFrom(u);}At the end of all your draw calls,call something like submitBuffer();submitBuffer(){glVertexPointer(...);glTexCoordPointer(...);glDrawArrays(.., vertexArray.data);}Hope this is helpful.

Quote:
 Original post by zedzeekthe only time u would want to maybe use the tables is inside a tight loop that uses those functions, the above doesnt adhere to that.to the OP the best way to speed it up would be to do all the math yourself, ie loop first through all the units and workout the 4 corners of the quad. and then once u have all the units sussed draw them in one fell swoopitll save in calling the following commands for every unitglLoadIdentity();glTranslatef(x,y,-1.0f);glRotatef(-dir*57.29577, 0, 0, 1);glBegin(GL_QUADS);

Is this the same thing?

##### Share on other sites
If you want to get rid of the glLoadIdentity then you can rotate and translate after drawing the quad to restore yourself to the initial position. ie:

glTranslatef(x,y,-1.0f);
glRotatef(-dir*57.29577, 0, 0, 1);

; draw polies

glRotatef(dir*57.29577, 0, 0, 1);
glTranslatef(-x,-y,1.0f);

And obviously if you introduce scaling then you'll need to scale by 1/x,1/y afterwards. This is what I do in my 2D opengl program and I get decent speed. Another thing is obviously to minimise texture changes, so I pre-sort all my units and place those with different textures at different z-depths so that when I draw them in order I have the bare minimum texture changes and that helps speed things up a lot.

• 12
• 10
• 10
• 11
• 18
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?