Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent drawing XNA component when it is off-screen?

I'm making a 2d game in XNA. When using drawable game components which one is better for performance?

1.When a component is not onscreen remove it from the components list and when its onscreen add it.

2.When its offscreen dont run its draw function (by using an "awake" bool field and an if statement around everything in the draw function)

I'm using method 2 at the moment and it works fine. Its handy cus the draworder of components wont change (if I remove and re-add them it will, and I'll need more code to manage that) In fact it just occured to me that if its not in the components list it wont update and I'll need something else to keep track of whether its onscreen or not..

Also I dont have the fancy version of visual studio with the profiler so I'm just asking here what do people think from their experience

like image 361
Guye Incognito Avatar asked Jan 23 '13 21:01

Guye Incognito


1 Answers

A sometimes overlooked concept of CPU performance while using SpriteBatch is how you go about batching your sprites. And using drawable game component doesn't lend itself easily to efficiently batching sprites.

Basically, The GPU drawing the sprites is not slow & the CPU organizing all the sprites into a batch is not slow. The slow part is when the CPU has to communicate to the GPU what it needs to draw (sending it the batch info). This CPU to GPU communication does not happen when you call spriteBatch.Draw(). It happens when you call spriteBatch.End(). So the low hanging fruit to efficiency is calling spriteBatch.End() less often. (of course this means calling Begin() less often too). Also, use spriteSortMode.Imediate very sparingly because it immediately causes the CPU to send each sprites info to the GPU (slow)).

So if you call Begin() & End() in each game component class, and have many components, you are costing yourself a lot of time unnecessarily and you will probably save more time coming up with a better batching scheme than worrying about offscreen sprites.

Aside: The GPU automatically ignores offscreen sprites from its pixel shader anyway. So culling offscreen sprites on the CPU won't save GPU time...

like image 87
Steve H Avatar answered Oct 12 '22 10:10

Steve H