calccrypto
calccrypto

Reputation: 8991

SDL make image before screen not working

I'm messing around with SDL, and I decided to make a program that opens images as the background to the main 'screen', and make it dynamic, so different sized images will result in different sized screens. The problem is, I can't figure out why it's not letting me. I can compile, but the program will error when I try to create the screen because the background image was nulled for some unknown reason. Any idea why?

The program is pretty small:

#include <iostream>
#include "SDL/SDL.h"
#define bpp    32

int init(){
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
        return 1;
    // will init ttf later
    return 0;
}

SDL_Surface * open_image(std::string image_name){
    SDL_Surface * loaded_image = SDL_LoadBMP(image_name.c_str());
    if (loaded_image){
        SDL_Surface * optimized_image = SDL_DisplayFormat(loaded_image); // becomes NULL
        SDL_FreeSurface(loaded_image);
        return optimized_image;
    }
    return loaded_image;
}

int main(int argc, char * argv[]){
    if (init())
        return 1;

    SDL_Surface * background = open_image("hello.bmp");
    SDL_Surface * screen = SDL_SetVideoMode(background -> w, background -> h, bpp, SDL_SWSURFACE); // erroring here

    SDL_BlitSurface(background, NULL, screen, NULL);
    if (SDL_Flip(screen) == -1)
        return 1;   
    bool quit = false;
    SDL_Event event;
    while (!quit)
        while (SDL_PollEvent(&event))
            if (event.type == SDL_QUIT)
                quit = true;
    return 0;
}

I'm getting error 3, which is apparently accessing values that don't exist. In this case, it is w and h from background, since background is NULL, even though it shouldn't be

Upvotes: 0

Views: 300

Answers (1)

Andr&#233; Puel
Andr&#233; Puel

Reputation: 9179

You cant invoke SDL_DisplayFormat without invoking SDL_SetVideoMode once before.

I fixed your code:

    SDL_Surface * screen = SDL_SetVideoMode(512, 512, bpp, SDL_SWSURFACE);
    SDL_Surface * background = open_image("hello.bmp");
    screen = SDL_SetVideoMode(background -> w, background -> h, bpp, SDL_SWSURFACE);

Upvotes: 2

Related Questions