SFML community forums
Help => Graphics => Topic started by: Calmatory on July 21, 2010, 10:11:19 pm
-
Well, I came across this kind of a problem while writing a tetris clone, and I'm kind of stuck with this problem for now.
The first two sprites just draw a white box, I don't know why. As if not all the images in vector seem to be valid for some reason?
This code should well reproduce the problem. block.png should be a png file with 16x16 dimensions.
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <vector>
/* Define global vector to hold all loaded images. */
std::vector<sf::Image> tempVector;
sf::Sprite LoadImage(std::string filename) {
sf::Image tempImage;
if(tempImage.LoadFromFile(filename)) {
sf::Sprite tempSprite;
tempVector.push_back(tempImage);
tempSprite.SetImage(tempVector.back());
return tempSprite;
}
}
int main() {
sf::RenderWindow App(sf::VideoMode(320,240,32), "Bugtest");
sf::Sprite sprite[4];
sprite[0] = LoadImage("block.png");
sprite[1] = LoadImage("block.png");
sprite[2] = LoadImage("block.png");
sprite[3] = LoadImage("block.png");
int i=0;
for(int y=0;y<240;y+=16) {
for(int x=0;x<320;x+=16) {
sprite[i%4].SetPosition(x,y);
App.Draw(sprite[i%4]);
i++;
}
}
App.Display();
sf::Sleep(10.0f);
App.Close();
}
Using linux x86 with SFML 1.6 and gcc version 4.5.0 20100610 (prerelease) (GCC).
-
When the vector needs to grow, it may move its elements elsewhere in memory. This is what invalidates some of the image pointers that the sprites store. You should rather use a container which never invalidates its elements, such as std::list, std::set or std::map.
-
Using std::list solved the problem. Thanks for the info. :) ...and now my journey shall continue.
-
Or, if you need random access, use std::vector<sf::Image*> (I know this isn't perfect Code, remember that you have to release all pointers manually, or use boost::ptr_vector or std::vector< shared_ptr<sf::Image> >.
bye, CBenni::O