SFML Texture memory management - c++

This is a C++ memory management problem thus I chose to ask here.
I am creating a game in SFML. I have used SDL before and managing my Textures was very straightforward but SFML works differently.
My project setup is something like so:
class Game
//create window and initialize game stuff
class Character
/*initializes its own textures and is also responsible for updating itself
as well as drawing itself*/
int main()
/*create an instance of Game -> Create an instance of Character and
runGame. I will implement the drawing and updating properly when I
implement a scene graph and scene nodes but for now updating and drawing is
done via global functions called by the Game Class*/
The challenge I faced was that using an sf::Texture in the Character class for the Sprite image results in a white rectangle being drawn. So the Character Sprite loses its Texture link and SFML just draws a white rectangle. To solve this I created a raw Texture pointer and Initialize it in the Character constructor. This works and the Sprite is drawn correct.
//inside character.hpp
sf::Texture *texture;
//in Character constructor
texture= new (sf::Texture);
This means I have to manage the memory and the code feels ugly.
I have tried this to manage the memory allocated (I think) to prevent a memory leak:
Character::~Character()
{ delete texturePtr; }
but that is wrong obviously.
I also tried to delete character.Texture at the end of main() when I exit the application but that causes an error also.
I then tried to do use a uinque_ptr inside the Character constructor:
std::unique_ptr<sf::Texture> texture(new sf::Texture);
//load Texture from Resource Manager instance
and this draws a nice navy blue-black rectangle instead of the Sprite Texture. I am not sure how or if I can declare and then later initialize a unique_ptr.
I think I am leaking memory and if so, how do I correctly use the smart pointers or manage my own memory properly?
I have added a bit more detail and code as I realized I was being vague. Also, I am querying the texture and using it to set the Sprite Rect dimensions so it is definitely being loaded, but just to be safe, I have a logger function that checks if any resource I call is loaded or not.

If the sf::Texture is a member of Character then it will not go out of scope until your Character instance does.
Use the debugger break points to follow what happens. Throw a break point in the destructor of Character and sf::Texture and walk through your startup and shutdown sequences. Or use Log to print messages like: "Character::~ called."
I think I am leaking memory and if so, how do I correctly use the smart pointers or manage my own memory properly?
Question all assumptions, including the one that you are loading the texture properly. Until you see the texture draw on screen, you don't have evidence that you have loaded it. (Unless you want a navy-blue rect. I don't know what you are trying to draw. I assume a character sprite.)
From SFML Docs:
The loadFromFile function can sometimes fail with no obvious reason. First, check the error message that SFML prints to the standard output (check the console). If the message is unable to open file, make sure that the working directory (which is the directory that any file path will be interpreted relative to) is what you think it is: When you run the application from your desktop environment, the working directory is the executable folder. However, when you launch your program from your IDE (Visual Studio, Code::Blocks, ...) the working directory might sometimes be set to the project directory instead. This can usually be changed quite easily in the project settings.
Until you see a leak in a leak detector, you really can't assume that you are leaking memory. There are 3rd party memory trackers you can add to your program.
Again, use a debug break point in sf::Texture destructor to stop execution and see exactly where you are deallocating (if this turns out to be the problem).
You really should read and follow Minimal, Complete, and Verifiable example. For all we know you could be doing something like this:
class Character{
sf::Sprite mySprite;
public:
Character(){
sf::texture aTex;
aTex.loadFromFile("c:\users\noob\Desktop\myawesomegame\stripper.png");
mySprite.setTexture(aTex);
}
}
// attempt 2
class Character{
sf::Sprite mySprite;
public:
Character(){
std::unique_ptr<sf::Texture> texture(new sf::Texture);
texture->loadFromFile("c:\users\noob\Desktop\myawesomegame\stripper.png");
mySprite.setTexture(*texture);
}
}
And the error would be obvious.

Related

C++/SDL2 IMG_Load Error (Out of memory)

I am making a shoot'em up game and have been coming into a problem where the sprites won't load at all after a certain amount of time and continuously shooting. In my console, an error prints out:
"IMG_LOAD_ERROR : Out of memory" (The "IMG_LOAD_ERROR : " was my own thing)
I also use text (SDL_ttf) to display an ammo count.
The hypothesis I have now is that I always call the IMG_load function in the constructor of every enemy that is spawned, but I'm not even sure if that's what's causing it. There are quite a few more possibilities I can think of.
Also, I do free the textures when they are destroyed (when the enemy is out of health or leaves the screen).
Can someone help me understand this and help me fix it?
It seems that you are not destroying textures/images or renderes that you are not need.
SDL_DestroyTexture(img);
SDL_DestroyRenderer(renderer);
Simple example of drawing image, which i found https://gist.github.com/armornick/3434362.
My advice: You should load all textures or begin of application or when is needed, but it must be once. You must reuse every same image.
It would be nice to see code to find out, what is wrong with code.

Memory Issue in cocos2dx

Thanx in advance..I have a problem , how we release memory in cocos2dx ??
In my game, my first scene takes a lot of memory because there are so many animations run at a single time on this scene,there are so many animations , so i am satisfied with this but when we go to next scene, it does not release previous memory used,this is my problem so how we release memory used by previous scene when we change the scene?
To go between scenes you can either call pushScene or replaceScene.
Push Scene
If you're pushing between scenes then I recommend that you have a loading scene in between. It should be lightweight so that you have a chance to release everything from your old scene. This is where the onEnter(DidFinish) and onExit(DidStart) methods come in handy.
The chain of calls would be:
oldScene->onExitDidStart()
loadScene->onEnter()
oldScene->onExit() <-- this is where you release everything
loadScene->onEnterDidFinish() <-- this is where you load up the new scene
newScene->onEnter()
and so on... If you've managed your memory correctly then you shouldn't have 2 heavy scenes at once.
Replace Scene
This is a much easier scenario. You simply need to make sure that for the new scene you load as little as possible until the old scene has completely disappeared. I.e. when onEnterDidFinish() is called, or even 1 frame after it.
Cocos2d-x supports auto release memory. For example, when you create a sprite by calling Sprite::create() it will add this sprite to the auto-release pool. If you don't add this sprite to become the child (or n-th leveled child) of the current scene, it will be released.
Do not create an object using new,use create() instead when you call the next scene, everything from the last scene are released.

Board Game using SDL

I am building a board game in SDL and here is the problem I am currently facing.
I have a pawn on square 1 and I roll the dice. Based on the value I get on the dice the pawn moves to another square. I am bale to move the pawn after i read the SDL tutorials online. But the problem I am facing is that after moving the pawn to a new location the old pawn still stays at the old location. The tutorials I found on the internet moves a dot but also refreshes the background to cover up the old dot. But I cant do that as my game board is intricate and there are pawns from other players sitting there.
Is there a way in SDL that I could really move a pawn instead of having to create a new pawn at the new location and covering up the old pawn?
The fundamental concept of sprites: Before you insert the sprite, you save a copy of the original screen content. When you need to remove the sprite, you just paste the stored old content back in.
You will have to process all your objects in the correct order (LIFO) for this to work. Since you'll usually be double-buffered, this happens on the cold buffer, so this isn't an issue.
No, your code will need to be able to redraw that board position with the pawn missing. There isn't any way for the computer to automatically reconstruct what the board should look like without the pawn.
It sounds like your render code is mixed in with your game logic. You ought to separate rendering so that you can redraw the complete game scene with a single function call, which you can then use whenever a visible change is made to the game state.

Pointers in C++ Class are getting scrambled

I've got a lot of code that's driving me really crazy right now.
I'm working with OpenGL, building a GUI framework which utilizes several different types of objects. I have Image classes which load *.png files and store image information in the form of a GLuint texture reference. I have Panel and Button classes with pointers to the image classes they should be displaying. I have a Hud class with std::vectors of Panel and Button pointers. Finally, I have an Engine class that contains one Hud class, all my Button and Panel classes, and Image pointers. When the constructor is run, each of the Image pointers is initialized using:
imgMy = new Image;
Once all the images have been initialized, I run my load functions:
imgMy->loadImage("imgMy.png");
Of course, I delete the Images when I close the program.
My problem is that some of the images are getting "crossed." I have about thirty images right now, and a couple of the buttons are apparently pointing to the wrong images. I have checked my code thoroughly, and it appears to be solid. I believe this is a memory bug since the buttons which display the incorrect images are inconsistent. Sometimes they display the correct images, sometimes different buttons are displaying the wrong images. I wish I could show my code here, but it's pretty massive.
The reason I'm using Image pointers in my Engine class instead of actual Image objects is that I'm afraid of the Buttons pointing to invalid memory if the Engine class is resized, or its memory rearranged. I suspect there's a much better approach to what I'm trying to accomplish, and I'd appreciate any advice along those lines.
Use a debugger that lets you put a watchpoint on the relevant imgMys, and then the debugger will tell you where they're being modified. That is probably the easiest way to track it down.
You may also want to try valgrind, but this doesn't sound like the type of problem valgrind will find.
Firstly, you should not use two-phase initialization without a really good reason. This is not a really good reason. Pass the filename in the constructor. Also, always use smart pointers.
You could simply use const to enforce it.
class Button {
const std::unique_ptr<Image> img;
public:
Button(std::string filename)
: img(new Image(filename)) {}
};
Secondly, I don't quite grok your overriding architecture, as you don't describe it in any real detail, but I'm unsure of the need of new here.
Sounds like memory corruption. You should consider using some memory debugger like valgrind or some other alternative. If you have any issues using pointers, those tools will help you track them down.
I suspect that you're keeping a list of button references and a list of image references somehow and that they are not always created in the same order, hence the cross over images.
Strictly speaking you should create your a button and it's image in order, assigning the image file at creation time.

Game screen management

I am working on a screen manager for a miniature game engine, and so far I cannot find a proper solution to managing screen objects without using the 'blob' for each one of the screens. Is blob tolerable in such circumstances where I need a list of renderable objects in one controller?
I would consider using the MVC pattern in this situation. Otherwise, if you're not careful, it's very easy to end up with a bunch of spaghetti code where the screen code is reaching into the game code, and vice versa.
I have recently coded something you might call a "screen manager".
I started with the idea that, whatever game I make, the render system is going to be pretty much the same in terms of how to render (how to manage the hardware). The thing that changes is what is rendered, and how to draw it (do I want a box or a circle or a bitmap.. representing what... etc).
So basically the "game state" is responsible for knowing how to render itself, and should do so when given a render surface from the screen manager or graphics system (It should also be responsible for other things like knowing how input, physics, etc act upon itself).
I implemented it with a singleton for the GraphicsSystem object, which was called something like this:
GameState gs;
Graphics::System().Init(DOUBLE_BUFFER, 640, 480);
...
while(still_looping) {
...
// When it is time to render:
Graphics::System().RenderGameState(&gs);
}
And how, you ask, does the Graphics::System() singleton know how to render the game state? It knows because the game state is inherited from a listener exposed by the graphics system...
//within GraphicsSystem.h...
class BaseRenderer
{
public:
virtual void Render(BITMAP *render_surface) = 0;
};
//GameState defined with:
class GameState : public BaseRenderer
{
public:
void Render(BITMAP *render_surface);
...
You can do this with nearly all the subsystems... (probably not timing, as it is needed in the game loop).
Why singletons? Well, it is C++ and I'm assuming there is only 1 screen, or graphics subsystem to render with. I'm not sure if you are using multiple screens, or a mobile phone or a console. The other way I would do it is to have the graphics system as static global variables in a separate file, giving them file scope only, and having accessor functions in that file (my old C way of doing things).
The key though is encapsulation. Let your screen manager manage the hardware. Let your game state dictate how itself should be expressed.
If this misses the point, please clear up your question and I can edit the answer.