If I draw a texture using SpriteBatch that is not visible to the camera or viewport, does it still render and use my GPU?
a little something like:
batch.draw(img, 9999999f, 9999999f, 1f, 1f)
or do I have to check if it's out of frame and not draw it in the first place?
CodePudding user response:
It does draw it. So the vertex shader will run for the four vertices of the texture or texture region. Since the vertex shader projects it to somewhere outside the visible space, the fragment shader will not be run.
For each sprite drawn, the vertex shader program is run four times regardless of whether the sprite is visible and the fragment shader program is run roughly once for every pixel of the sprite that appears on screen. A modern low end phone can easily handle hundreds of “wasted” sprites being drawn off-screen.
It’s up to you to decide whether it is worth calculating if it will be visible and skip drawing it. If you do this for each individual sprite, it will be costly on the CPU for a comparatively small savings of GPU. If you think about it, checking an individual sprite based on whether any of its four corners is visible is running your own copy of the vertex shader program on the CPU redundantly just in case it saves you from having to repeat that program on the GPU. And the GPU is far more optimized for this kind of thing. (If you're using orthographic projection, the CPU's version can at least be simpler than the GPU version because it becomes a simple 2D comparison.)
For that reason, if you’re going to check them first, you would check groups of them at a time. So you might organize your game world into sections and check the outer bounds of a whole section before deciding to draw all or none of that section's sprites. For it to be worthwhile, each section should be big enough to encompass a least a couple hundred sprites.