Precache/preloading images

Started by
1 comment, last by Captain P 17 years ago
Yello, I find myself at an impasse in writing a simple sprite based game in SDL in that I cant figure out the best way to preload all the images I need upon loading the level. The fact that I cant find any tutorials or other posts on it makes me think it's really simple and just hasnt occured to me, or I just missed them all, but a bit of help would be appreciated. From what I can see the easiest way would be to put every image or sprite set into a new SDL surface, but I dont know how SDL intends surfaces to be used and whether or not this would waste a lot of RAM. I've been using surfaces quite sparsely and specifically thus far. Like screen, background, foreground, status bar and temp. On the other hand I thought I could load every image into 1 or 2 surfaces and store their coordinates somewhere but those would get kind of big would they not? At the very least a tad unruly to use. I also recall reading somewhere about using malloc() but this seems to be quite a roundabout way of doing it. Is there another easy way of doing it or was I on the right track with the surface thing?
Advertisement
While you certainly should not make a 1024x1024 surface for each and every tiny cell in your sprite sheets [thus wasting all the rest of the space], you do not have to be so careful with your surface creation as to restrict your ability to do what you need to do. Go ahead and create the surfaces you need, just don't be silly about it. Unless you already know that you're going to have a real restriction on memory, you don't have to worry about filling every little air hole in your image sheets either. Generally, it is perfectly okay to group interdependant images [like cells in a sprite sheet] into one image file, and create another surface for each of those image files you load.

Squeezing an optimal number of images into a minimum number of surfaces at run time is complicated [very] and very often completely unnecessary to meet your goals. It might increase your run-time performance slightly if you do everything perfectly, but it will add substantial load time.

Go with what is easy without being REALLY wasteful, and you will be fine.
Just a tip: sometimes it's good to just go wild and see what happens. Try loading some images a 1000 times, for example, and see what happens. Sometimes, the things you worried about turn out to be fine, and you may find out about other problems that you didn't anticipate.

As a thumbrule for images: they generally take their size, multiplied by their bytes per pixel, in memory. That is, a 32 bpp, 256 * 512 image will take 0.5 MB. And since a surface is just a chunk of memory containing an image, with maybe some additional information attached to it, you shouldn't worry much about this.
Create-ivity - a game development blog Mouseover for more information.

This topic is closed to new replies.

Advertisement