Is it okay to have a SDL_Surface and SDL_Texture for each sprite?

Viewed 256

I'm trying to build a gameengine in SDL2 with cpp. I have a class called 'entity' which has some data for movement and also some pointers to a surface and a texture. A function "render" is called inmass to render each sprite based on the g_entities vector.

class entity {
    ...
    SDL_Surface* image;
    SDL_Texture* texture;

    entity(const char* filename, SDL_Renderer * renderer, float size) {
        image = IMG_Load(filename);
        width = image->w * size;
        height = image->h * size;
        texture = SDL_CreateTextureFromSurface(renderer, image);
        g_entities.push_back(this);
        
    }

    ~entity() {
        SDL_DestroyTexture(texture);
        SDL_FreeSurface(image);
        //TODO remove from g_entities
    }

    void render(SDL_Renderer * renderer) {
        SDL_Rect dstrect = { x, y, width, height };
        SDL_RenderCopy(renderer, texture, NULL, &dstrect);
    }
    ...
}

So the program makes a new texture and surface for each sprite. Is this okay? Is there a faster way?

If so, I'd like to clean that up before it becomes a bigger mess.

I made a testlevel with 96 sprites that each take up 2% of the screen with tons of overdraw and ft is 15ms (~65fps)at a resolution of1600x900

1 Answers

Yes but actually, no. If the same sprite will be used many times without modification, its most efficient for those objects to have pointers to the same SDL_Texture. Additionally, the image can be freed after the texture is generated. Furthermore, loading these in the constructor may be a bad idea since objects made on-the-fly will require disk-reading.

I set up a system where entities are given another variable on construction, and if it is positive, the entity will check and see if any other entity used the same file for it's sprite, and if so, just use that same reference.

That means that objects like bullets that are spawned and destroyed can be handled efficiently by spawning a single bullet in the level.

https://www.reddit.com/r/sdl/comments/lo24vt/is_it_okay_to_have_a_sdl_surface_and_sdl_texture/

Related