Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Simple Sprite Batcher  (Read 4158 times)

0 Members and 1 Guest are viewing this topic.

Hapax

  • Hero Member
  • *****
  • Posts: 3381
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Simple Sprite Batcher
« on: November 22, 2023, 12:04:04 am »
Multiple sprites drawn mean multiple draw calls. These draw calls can have a detrimental affect to performance so, if possible, they should be reduced. One way to do this is to draw many of those sprites batched together!

This is a "simple" sprite batcher. That is, it's very easy and simple to use and will bring you performance improvements. However, a more dedicated batcher may be able to bring more improvements albeit at the cost of simplicity.

The batcher is a very small class. You simply create it and pass it the texture. Then, you can pass it the sprites to be batched and draw it as often as required.

Basically, it'll look like this:
sf::Texture texture;
// .. set up the texture for the sprites

std::vector<sf::Sprite> sprites;
// .. set up the sprites

SimpleSpriteBatcher batcher;
batcher.texture = &texture;

while (window.isOpen())
{
    // .. event handling

    // .. updates where you would modify vector sprites however you want

    batcher.batchSprites(sprites);

    window.clear();
    window.draw(batcher);
    window.display();
}

You can also batch using a vector of pointers to sprites too so you can easily still use this if your sprites are not in a vector or if you need to order them first! There is an example of how to do this on the wiki page.

Here's a video that shows it in action:

Note that the YouTube compression struggles with the video but it still shows the difference between with and without the batcher.

Wiki page:
https://github.com/SFML/SFML/wiki/Source:-Simple-Sprite-Batcher

GitHub repository (it's a part of SfmlSnippets):
https://github.com/Hapaxia/SfmlSnippets/tree/master/SimpleSpriteBatcher

Example used to create the clips in the above video is included in the repository and also on the wiki page.

Feel free to ask any questions or make any comments.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*