So, i don’t know how graphics hardware works, but from SDL knowledge i know that a texture uses the memory of the GPU for faster performance. So every time i use CreateTextureFromSurface() i will probably exhaust the memory of the GPU, or if someone else makes sure to handle this i will still probably cause some performance issues.
In my game engine i have a sprite class that can have the following rules:
You can make clones of this sprite.
On scene initialization, multiple sprites can load a texture from the same path (image).
So what if n sprites load the same image? I will have n copies of the same texture? This applies also when i clone the sprite.
So this is my solution:
I will create a tree (in main memory) that will use the path (of an image) as the key. This tree will store 3 things, the path , a reference to the texture and a reference counter.
Every time a sprite tries to load a texture, first it will search in the tree to see if the path of the image is already registered. If it is then it will take a copy of the texture’s reference and it will increase the ref counter, else it will load the texture and add a new node into the tree.
Also each sprite object will have a reference to its relative node so when the sprite object is destroyed, will decrease the ref counter. When the ref counter reaches zero we delete the node from the tree and we also call SDL_DestroyTexture() to destroy the texture.
So if we have 500 sprites that uses the same image, only one texture will be rendered!
This might be similar to garbage collection but its a lot faster!!!
The only think i’m loosing is Ram (for the tree) and some speed (when i search in the tree) but still if i make sure that this tree is balanced the search algorithm will be very fast.
Also all of this will probably only happen at scene loading except when at run time the player creates clones of a sprite (like bullets from a gun).
I think this is a good solution, but because i don’t really know how textures and graphics hardware works, i want your advice.
Thanks.