Advertisement

SDL2 Preparing Background with Tiles Surface is empty

Started by February 24, 2017 06:37 PM
2 comments, last by Alberth 8 years ago

Hello Guys I need help.

I want to prepare a Surface with Background tiles once. Because I dont want to write all the tiles on every gameloop. It would waste cpu.

My Idea is, to create a Surface with static tiles and copying this surface inside the gameloop to the texture memory and then paint all the additional graphics and sprites.

In my test I got a black screen without the tile background. No Compile error.

What I'm doing wrong?


#include "SDL2/SDL.h"
#include "SDL2/SDL_timer.h"
#include "SDL2/SDL_image.h"
#include <stdio.h>
#include <stdbool.h>
/*
gcc bgtiles_test.c -o bgtiles_test.exe -lmingw32 -lSDL2main -lSDL2 -lSDL2_image
*/
int main( int argc, char *args[] )
{
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER);
	SDL_Window *win = SDL_CreateWindow("B_Game 0.001",
				SDL_WINDOWPOS_CENTERED,
				SDL_WINDOWPOS_CENTERED,
				1280,720,0);
	//Uint32 render_flags = SDL_RENDERER_ACCELERATED;
	SDL_Renderer *rend = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
	SDL_Surface *bg_tile = SDL_LoadBMP("assets/tiles/water.bmp");
	SDL_Surface *bg_surface = NULL;
	SDL_Rect size_bg_tile = {0,0,64,64};
	SDL_Rect coord = {0, 0, 64, 64};
	
	const Uint8 *keys = SDL_GetKeyboardState(NULL);
	SDL_Event e;
	bool quit = false;
	int x = 0;
	int y = 0;
	
	//fill surface 1024x1024 with background tiles 64x64
	for(y=0;y<1024;y+=64){
		for(x=0;x<1024;x+=64){
			coord.x = x;
			coord.y = y;
			//blitting bg tiles into bg_surface
			SDL_BlitSurface(bg_tile, &size_bg_tile, bg_surface, &coord);
		}
	}
	//copy bg_surface to gfx memory
	SDL_Texture *text_bg_surface = SDL_CreateTextureFromSurface(rend, bg_surface);
	while(!quit){
		while (SDL_PollEvent(&e)){
			if (keys[SDL_SCANCODE_A]){
				quit = true;
			}
		}
		SDL_RenderClear(rend);
		SDL_RenderCopy(rend, text_bg_surface, NULL, NULL);
		/*
		add additional graphics
		later
		*/
		SDL_RenderPresent(rend);
		SDL_Delay(5);
	}
	SDL_FreeSurface(bg_tile);
	SDL_FreeSurface(bg_surface);
	SDL_DestroyTexture(text_bg_surface);
	SDL_DestroyRenderer(rend);
	SDL_DestroyWindow(win);
	SDL_Quit();
	return 0;
}

Life is short, break the rules

SDL_Surface *bg_surface = NULL;

You didn't allocate `bg_surface`. It's null through entire program, and you didn't check error codes from SDL_BlitSurface() and the rest.

Advertisement

Thank you very much.

I wrote this line and it works.

SDL_Surface *bg_surface = SDL_CreateRGBSurface(0,1024,1024,32,0,0,0,0);

I do error handling now. It was only a test. :D

Life is short, break the rules

Especially with tests, check everything, and make failures loud. It costs a few minutes, but it sometimes saves you hours to days of fruitless searching at the wrong place

This topic is closed to new replies.

Advertisement