Question

I am pretty new to SDL and was making a program that would do some basic image blitting.

The program runs without errors, but the image is not being displayed in the window I created. Here is the code:

#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <string>

bool quit = false;
SDL_Event xOut;

const int screenW = 640;
const int screenH = 480;
const int screenBPP = 32;

SDL_Surface *window = NULL;
SDL_Surface *background = NULL;
SDL_Surface *backgroundOPT = NULL;

SDL_Surface *loadIMG(std::string filename, SDL_Surface *image, SDL_Surface *imageOPT)
{
    image = IMG_Load(filename.c_str());
    imageOPT = SDL_DisplayFormat(image);

    SDL_FreeSurface(image);

    return imageOPT;
}

void applyIMG(int x, int y, SDL_Surface *screen, SDL_Surface *imageBlit)
{
    SDL_Rect imgPosition;
    imgPosition.x = x;
    imgPosition.y = y;

    SDL_BlitSurface(imageBlit, NULL, screen, &imgPosition);
}

int main(int argc, char* args[])
{
    SDL_Init(SDL_INIT_EVERYTHING);

    window = SDL_SetVideoMode(screenW, screenH, screenBPP, SDL_SWSURFACE);

    while(quit == false)
    {
        loadIMG("arena.png", background, backgroundOPT);

        applyIMG(0, 0, window, backgroundOPT);

        SDL_Flip(window);

        SDL_PollEvent(&xOut);

        if(xOut.type == SDL_QUIT)
        {
            quit = true;
        }
    }

    SDL_FreeSurface(backgroundOPT);

    SDL_Quit();

    return 0;
}

Any help would be appreciated.

Was it helpful?

Solution

In your function

SDL_Surface *loadIMG(std::string filename, SDL_Surface *image, SDL_Surface *imageOPT);

the pointer imageOPT is being copied at function call here :

loadIMG("arena.png", background, backgroundOPT);

This mean you're not setting backgroundOPT, but a copy of it.

Simply do something like that :

backgroundOPT = loadIMG("arena.png", background, backgroundOPT);

Or change your function prototype to :

SDL_Surface *loadIMG(std::string filename, SDL_Surface *image, SDL_Surface **imageOPT);

and call it like that :

loadIMG("arena.png", background, &backgroundOPT);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top