Jump to content

  • Log In with Google      Sign In   
  • Create Account

Only 5.000 Sprites


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 08 April 2011 - 05:52 PM

Topic says it.
I tried to get the maximum out of my Library and just created insane amounts of sprites wandering over the screen.
With 5000 Sprites I got down to 15-20fps which is the bottom line of a playable Game.
So, I need some performance Tipps.

Here is the drawing Code:


void NLSpriteList::renderObject()
{
	m_texture->attach();
	m_shader->attach();	

	glBindVertexArray(m_vao);
	glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

	// Enable Attribute Sets
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	// Draw
	glDrawArrays(GL_TRIANGLES, 0, m_list.size()*6);

	// Disable Attribute Sets		
	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);

	// Unbind
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);

	m_shader->detach();
	m_texture->detach();
}

void NLSpriteList::update(u32 delta, u32 time)
{
	if ( m_vao == 0 || m_vbo == 0 )
		this->createBatch();

	//m_list.sort(NLBatchedSprite::OrderByZ());

	// Update data
	NLVertexData* data = createData(delta, time);

	// Bind
	glBindVertexArray(m_vao);
	glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

	// Enable Attribute Sets
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	// Send Vertex data
	glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

	// Disable Attribute Sets		
	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);

	// Unbind
	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	// Delete buffer
	delete [] data;
}

NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
	NLVertexData* buffer = new NLVertexData[m_list.size()*6];
	memset(buffer, 0, sizeof(buffer));
	TSpriteList::iterator it = m_list.begin();

	int i = 0;
	for ( it; it != m_list.end(); it++ )
	{
    	NLBatchedSprite& s = *it;
    	s.update(delta, time);
		memcpy(&buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
		i += 6;
	}

	return buffer;
}
As you can see, I send the vertices each frame. Okay, in this case it is needed since I have transformations every frame and I do transforms on the cpu.
Any hints? :)
Oh and there are no texture-/shaderchanges during the rendering, OpenGL Calls are constant 31 per Frame and no glGet/Redundant state changes.
Picture was taken on an AMD 2600+ DualCore with ATI HD4890 with 11.4 drivers.

Posted Image

Attached Thumbnails

  • gdebug.png

If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/

Sponsor:

#2 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 08 April 2011 - 06:14 PM

Okay, I was dumb enough to do this with a debug executable.
In Release Mode I can get up to 30.000 Sprites.
But if anyone sees some Room for improvements, I am open to suggestions.
If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/

#3 karwosts   Members   -  Reputation: 840

Like
0Likes
Like

Posted 08 April 2011 - 06:16 PM

How about an image of your game, so that we may see in what way you are using the sprites?

Not that it will make your game run much faster, but this is pointless, you have no need to modify attribArrays to send bufferdata.

// Enable Attribute Sets
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

// Send Vertex data
glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

// Disable Attribute Sets
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

You probably don't need to bind/unbind VAO either, but I don't work with VAO that much so I can't be sure.
My Projects:
Portfolio Map for Android - Free Visual Portfolio Tracker
Electron Flux for Android - Free Puzzle/Logic Game

#4 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 08 April 2011 - 06:28 PM

Thanks for the reply. Well, in this case it is only a lot of sprite wandering from left to right and back. Nothing fancy. I just stress test my code.
Removing the Attribute Sets was fine and gave me maybe 1-2 fps.
About the binds: I bind/unbind at the end of every function because I want to leave the OpenGL StateMachine in the state it was before.
Maybe this is a bad strategy?
The class used here is a batcher class which does nothing but batching the sprites you feed to it. One batcher is required per SpriteSheet.
There are also sprites which take a single texture, they cannot be batched. So I am nevery sure if my objects are still bound. A glGet is probably
more expensive than binding it? Or would you buffer the OGL State here?

On the other Hand: Who makes 2D Games with more than 200 Sprites visible at once... and I still have to do Point Sprites for a Leightweight Particle-Engine, so that goes extra.
The current Sprites are 2 Triangles which are making up a quad.
Maybe I get lost in micro-optimisations here?

And here is the requested image:
http://www.abload.de.../sample47kb.png
If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/

#5 Ezbez   Crossbones+   -  Reputation: 1164

Like
0Likes
Like

Posted 08 April 2011 - 06:38 PM

On the other Hand: Who makes 2D Games with more than 200 Sprites visible at once... and I still have to do Point Sprites for a Leightweight Particle-Engine, so that goes extra.


More to the point, are you making such a game? "You ain't gunna need it" is the rule of thumb to follow here.

#6 Danny02   Members   -  Reputation: 275

Like
1Likes
Like

Posted 08 April 2011 - 06:53 PM

First of,
you using VAOs wrong, making them useless in your case.
1. in the render function, get rid of all the client state en/disables and the buffer binds.
You need this only while initialization.
2. in the update function, you don't need to bind the VAO just the buffer.

when a VAO is bound all of these specific OpenGL stats are stored in the VAO instead of the "standard" context(VAO, glBindVertexArray(0);)

also, it don't make any sens to "unbind" a shader, its just extra work. In many case also true for the textures.


Finaly there is something what u can optimize, in your update function.
Instead of your simple glBufferData use this
glBufferData(GL_ARRAY_BUFFER,  size, null, GL_STREAM_DRAW);
glSubBufferData(GL_ARRAY_BUFFER, 0,  size, data);

this lets the driver optimize the upload better and can reduce stalls

#7 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 08 April 2011 - 07:19 PM

Thanks for all the replies.

@Ezbez
I am developing a multi purpose Library and just trying to make it as good as I can.
But I feel already pretty comfortable with this drawable amount of sprites.

@Danny02

Could go into detail with the VAO? I have the OpenGL Superbible and some Tutorials on OpenGL3, but Articles about it are really rare and reading the specs is not a good documentation for me. "Too technical" if you can understand what I mean.
If I get rid of all the glEnableVertexAttrib()-binds in the render function, nothing is displayed at all. Thats not the only place I am using a VAO/VBO.
About glBufferSubData:
Does not yield any performance gain. I already tell OpenGL that I will throw away the content of the VBO by using GL_STREAM_DRAW. glBufferSubData yields some problems regarding updating the sprites, esp. dynamic Text like FPS Display.

But well, I think 30.000 Sprites at once are pretty good in Release Mode. But that there is such a huge difference in performance of 25.000 Sprites between Debug and Release is astounding.

Here is my updated code so far:


void NLSpriteList::renderObject()
{
	m_texture->attach();
	m_shader->attach();	

	glBindVertexArray(m_vao);

	// Enable Attribute Sets
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	// Draw
	glDrawArrays(GL_TRIANGLES, 0, m_list.size()*6);

	// Disable Attribute Sets		
	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);

	// Unbind
	glBindVertexArray(0);

	m_shader->detach();
	m_texture->detach();
}

void NLSpriteList::update(u32 delta, u32 time)
{
	if ( m_vao == 0 || m_vbo == 0 )
		this->createBatch();

	//m_list.sort(NLBatchedSprite::OrderByZ());
 
	// Update data
	NLVertexData* data = createData(delta, time);

	// Bind
	glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

	// Send Vertex data
	glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

	// Unbind
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	// Delete buffer
	delete [] data;
}

NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
	NLVertexData* buffer = new NLVertexData[m_list.size()*6];
	memset(buffer, 0, sizeof(buffer));
	TSpriteList::iterator it = m_list.begin();

	int i = 0;
	for ( it; it != m_list.end(); it++ )
	{
    	(*it).update(delta, time);
		memcpy(&buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
		i += 6;
	}

	return buffer;
}


If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/

#8 Danny02   Members   -  Reputation: 275

Like
1Likes
Like

Posted 09 April 2011 - 02:47 AM

Ok, VAOs are a special kind of OpenGL object. Instead of saving data they save state.
In order to draw something with BOs u normally have to set up a lot of state, like enabling vertex attributes, setting the attribute settings and specifying an element buffer.

These states are set through the following OpenGL commands:
  • glEnableClientState , glDisableClientState
  • all the gl*Pointer functions
  • binding the GL_ELEMENT_ARRAY_BUFFER buffer
good overview over the data structure http://www.opengl.org/wiki/Vertex_Array_Object


If I get rid of all the glEnableVertexAttrib()-binds in the render function, nothing is displayed at all. Thats not the only place I am using a VAO/VBO.


Have u put that code in your VAO initialization? The same spot where u set up all the Attribute info.



#9 haegarr   Crossbones+   -  Reputation: 4582

Like
1Likes
Like

Posted 09 April 2011 - 03:40 AM

Although you're right that 30.000 sprites should be enough, here are some points for discussion:

About glBufferSubData:
Does not yield any performance gain. I already tell OpenGL that I will throw away the content of the VBO by using GL_STREAM_DRAW. glBufferSubData yields some problems regarding updating the sprites, esp. dynamic Text like FPS Display.

When OpenGL enqueues commands for later execution, you don't know whether the VBO is already available (i.e. there is no commands pending that requires access to that VBO). You would know if you do synchronization, but that obviously wastes some time. If you "blindly" write to the VBO memory the driver may defer your routine until no pending command requires the VBO anymore. Hence the trick is to do double buffering for vertices, and that is why

glBufferData(GL_ARRAY_BUFFER,  size, null, GL_STREAM_DRAW);
glSubBufferData(GL_ARRAY_BUFFER, 0,  size, data);
is used, because that "null" allows the driver to allocate a second memory area, leaving the 1st memory area until no pending commands require it anymore while you are writing to the 2nd one. So using GL_STREAM_DRAW by itself isn't sufficient to gain advantage from double buffering.

There is no guarantee though that the driver behaves this way, but it is the best you can do in situations where you need to be compatible. In OpenGL 3 / the ARB_map_buffer_range extension there is glMapBufferRange which allows an explicit double buffering.


Moreover, how looks your vertex layout? It is probably best if multiples of vertex data boundaries lie on 32 byte boundaries. E.g. a vertex occupying 16 bytes would be fine. My current development uses 3 floats for position and 2 shorts for (u,v) with auto-normalizing the (u,v) pair in the input pipeline. But I have no performance comparisons made yet.


At least, using vertex indices may be of benefit. Assuming you need 16 bytes per vertex and each sprite is mapped on a quad (i.e. 2 triangles), then you need
6 * sizeof(Vertex) = 6 * 16 bytes = 96 bytes
for each sprite. If you use INT indices (at least for the stress test), then you need
6 * sizeof(INT) + 4 * sizeof(Vertex) = 6 * 4 bytes + 4 * 16 bytes = 88 bytes
for each sprite. If you use SHORT indices (obviously allowing for >10.000 sprites), then you need
6 * sizeof(SHORT) + 4 * sizeof(Vertex) = 6 * 4 bytes + 4 * 16 bytes = 76 bytes
for each sprite. It may be that the sprites all together live long enough so that the index buffer need not be rebuild every frame, reducing the transfer amount asymptotically to 64 bytes.

Advantages are:
1. Using less bandwidth (okay, the difference between 96 and 88 may be eaten by the additional mapping; you have to try).
2. Allowing the GPU to use the vertex cache for 2 of the 6 vertices of a sprite.

#10 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 09 April 2011 - 09:05 AM

My Vertex Layout is:


#pragma pack(push, 1)
/**
 * \brief Vertex coords for storage in OpenGL
 *
 *
 * A normal user does not need to care about them.
 */
struct NLVertexData
{
	/// \brief Constructor
	NLVertexData()
		: x(0), y(0), z(0),
		r(1), g(1), b(1), a(1), 
		s(0), t(0)
	{}

	/// \brief X
	f32 x;

	/// \brief Y
	f32 y;	

	/// \brief Z
	f32 z;

	/// \brief Red
	f32 r;

	/// \brief Green
	f32 g;

	/// \brief Blue
	f32 b;

	/// \brief Alpha
	f32 a;

	/// \brief t
	f32 s;

	/// \brief t
	f32 t;
};

#pragma pack(pop)

And when I use glBufferData(NULL) and then glBufferSubData, I loose around 5 Frames. At least on my ATI.
If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/

#11 Danny02   Members   -  Reputation: 275

Like
1Likes
Like

Posted 09 April 2011 - 10:09 AM

some thoughts
1. frames doesn't tell u anything, use ms to compare stuff.
2. try to test if u are filtrate bound, render the particles without updating them every frame.
3. try to shrink your vertex size
4. can u use point spirits instead of your quads? possible if u don't rotate the particles and they face the camera
4.1. experiment with geometrie shaders
5. use instancing, for particles a texture or with OGL3 transform feedback is probably the best

#12 mhagain   Crossbones+   -  Reputation: 8276

Like
1Likes
Like

Posted 09 April 2011 - 11:08 AM

Your update function is doing a lot of memory allocation and releasing - are you calling this every frame? If so it's going to be a potential bottleneck as the numbers get higher.

I wouldn't use C++ new and delete for this kind of thing at all to be honest. On Windows I'd VirtualAlloc (with MEM_RESERVE) a large-ish pool (16-64 MB, but it depends on how many you want to draw really) and VirtualAlloc (with MEM_COMMIT) as needed, but never release memory so that I could reuse previous allocations from frame to frame. Otherwise I'd create an initial static pool of objects that's large enough to cover most common uses, and only allocate/release when the size needs to change (and even then only when it needs to go up). The key however is to always be able to reuse previously allocated memory instead of having to allocate fresh memory every frame. Memory is cheap and plentiful, performance is not.

I wouldn't use a class either (or even a struct with a constructor) for something that I need to dynamically allocate 10s of 1000s of every frame. Here you're allocating a buffer, you're memset-0'ing, it, you're updating the data, you're memcpy'ing it, then you're glBufferSubData'ing it. This actually needs to update data for each vertex five times - constructor, memset-0, update for real, memcpy, and glBufferSubData. That's a lot of walking over the same data,and a lot of unnecessary value-storing (are the constructor and the memset-0 even necessary?), all for a chunk of data that you just end up throwing away. Just use a simple lightweight C style struct and maintain the count of items for it separately.

The point though is that too much OO at too fine a level can really hurt performance, and that if you want your rendering to really fly you may need to start doing things that you consider less "clean".

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#13 GothSeiDank   Members   -  Reputation: 156

Like
0Likes
Like

Posted 09 April 2011 - 06:12 PM

Thanks for all the good suggestions.
I have eliminated the memset, but I still need the memcpy.
I also eliminated the renundant OpenGL Calls.
I have also eliminated the allocation of the buffer for sending the data to OpenGL and replaced it with a lightweight, but "safe" solution:
NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
	TSpriteList::iterator it = m_list.begin();
	u32 size = m_list.size()*6;
	u32 i = 0;

	// Alloc more space only if there is a need to do so.
	if ( m_buffer_size < size )
	{
    	delete [] m_buffer;
    	m_buffer_size = size;
    	m_buffer = new NLVertexData[m_buffer_size];
	}

	// Create
	for ( it; it != m_list.end(); it++ )
	{
    	(*it).update(delta, time);
		memcpy(&m_buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
		i += 6;
	}
	return m_buffer;
}
This reduces the usage of the new operator greatly, since normally the size of a batcher rarely changes atm. This is dependant of the usage of my library though, but every lib has its "good practice" section in the docs huh? :D

However, I will examine "placement new" to allocate memory ahead for the batcher and also the created sprites on client side. This way I could save some considerable performance. And it is not Platform dependant like VirtualAlloc().
I just don't know yet how to implement it in detail.
Btw I am up to 75.000 objects in release mode with logic update @ 20 FPS and good timings.
So thanks for all the good hints :). I really apreciate it.
If you say "pls", because it is shorter than "please", I will say "no", because it is shorter than "yes"
http://nightlight2d.de/




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS