Search code examples
csfml

CSFML Background not loading


I'm trying to learn how to use CSFML. And i created this basic window:


my_window_t *init_window(void)
{
    my_window_t *temp = malloc(sizeof(my_window_t));
    sfTexture *texture = sfTexture_createFromFile("background.jpeg", NULL);
    sfSprite *sprite = sfSprite_create();

    temp->font = font;
    temp->bg_sprite = sprite;
    return temp;
}

void main(void)
{
    sfVideoMode mode = {960, 540, 32};
    sfEvent event;
    my_window_t *screen = init_window();
    sfRenderWindow *window;

    window = sfRenderWindow_create(mode, "Test_CSFML", sfClose, NULL);
    sfRenderWindow_setPosition(window, (sfVector2i){0, 0});
    sfRenderWindow_setFramerateLimit(window, 60);
    while (sfRenderWindow_isOpen(window)) {
        while (sfRenderWindow_pollEvent(window, &event))
            main_event(window, &event, screen);
        sfRenderWindow_clear(window, sfBlack);
        sfRenderWindow_drawSprite(window, screen->bg_sprite, 0);
        sfRenderWindow_display(window);
    }
    sfRenderWindow_destroy(window);
}

Here is my structure:

typedef struct my_window_t {
    sfSprite *bg_sprite;
    sfSoundBuffer *music_buffer;
    sfSound *music_sound;
    sfFont *font;
}my_window_t;

All the other element in my structure are loaded in another part

I tried to change the name of the texture, switched with a png file but nothing is loading and I just have a black screen.

I didnt find anything in the CSFML Documentation


Solution

  • You are creating a Sprite and a a texture but you never keep the texture in a variable or add it to the sprite.

    The sprite you create dont have any texture, in order to fix that i recommend doing something like this.

    typedef struct my_window_t {
        sfSprite *bg_sprite;
        sfTexture *bg_texture
        sfSoundBuffer *music_buffer;
        sfSound *music_sound;
        sfFont *font;
    }my_window_t;
    
    my_window_t *init_window(void)
    {
        my_window_t *temp = malloc(sizeof(my_window_t));
        sfTexture *texture = sfTexture_createFromFile("background.jpeg", NULL);
        sfSprite *sprite = sfSprite_create();
    
        temp->font = font;
        //Store in the structure in order to destroy it after
        temp->bg_texture = texture;
        //Adding a texture to the sprite
        sfSprite_setTexture(sprite, temp->bg_text, 0);
        temp->bg_sprite = sprite;
        return temp;
    }
    
    

    With this modification, it supposed to work, if you have any other problem i will be happy to help you.

    Also check the CFML documentation, you will have more information that in the SFML documentation