Cocos2d-x performance optimization with polygon sprites
Learn how to increase the performance of your Cocos2d-x / Axmol game.
Cocos2d-x (version 3.9 and newer) and Axmol implement a feature called "Polygon mesh sprites". Instead of drawing a whole polygon only the non-transparent parts are painted, which increases the frame rate of your game.
With TexturePacker you can create optimized polygon sprites while building your sprite sheets. It also comes with a polygon based packing algorithm.
What you'll get from it:
- Increased performance — using polygon sprites
- Reduced memory usage — using tightly packed sprite sheets
Starting with the most important: Performance. We are running the tests in iPhone 4s. We chose this old device because it's still supported by cocos2d-x, and you should always optimize for the slower devices because they are the performance bottleneck.
The test simply draws 500 sprites, and we measured the performance in Xcode.
What you see is that the GPU load is high in the untrimmed test — 27.4ms of each frame are spent in the GPU, 6.4ms in the CPU.
Rectangular trimming keeps the CPU the same and reduces the GPU load by 14%. It also increases the frame rate from 36 to 42 frames.
This practically means: You should at least use rectangular trimming — simply because it comes for free in terms of CPU. You can only win if you use it.
The polygon trimming takes more load from the GPU — reducing it by 40%. But it comes also with a cost: CPU is increased from 6.5ms to 11.5ms. This increase comes from the additional CPU power required for calculating the vertex positions.
Polygon trimming can dramatically improve your game performance if you have some free CPU cycles to take some load from the GPU.
Using the polygon mesh sprite is simple — you might not even have to change a single line of code.
Load the sprite sheet into your SpriteFrameCache:
Create your sprite using
auto sprite = Sprite::createWithSpriteFrameName("grossini-dance-05.png");
Download the latest TexturePacker from here:
If you are opening an existing project, convert it to Cocos2d-x by using the button next to Data Format and select cocos2d-x. The older cocos2d exporters don't support polygon sprites.
Scroll down and select Trim mode, set it to Polygon outline
You can also enable polygon packing by selecting Algorithm and setting it to Polygon.
The value in Tracer Tolerance gives you control over vertex / triangle count vs overdraw.
Polygon sprites can increase the performance of your game. They are easy to add to your project if you are already using TexturePacker to build your sprite sheets.
As you see from the results above, polygon sprites don't come for free. They trade GPU for CPU. Take a look at the performance values of your game. If you see a high GPU load, but still have resources left on the CPU it's worth testing.
Simply testing the new feature is easy because you might not even have to change your code.