First and foremost, I'm in the process of learning C++ & SDL2 coming from a C# background. I'm getting an unhandled exception which should be contained within a try/catch but the line of code should from other examples should execute successfully. The exception is happening at the SDL_RenderCopy()
function.
Any help/direction would be most appreciated in my long journey of C++!
Gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include "GenericEntity.h"
#include "GameboardParameters.h"
#include "Piece.h"
#include <iostream>
// Board witdh & height in pieces
#define BOARD_WIDTH 6
#define BOARD_HEIGHT 11
// Piece width & height in pixels
#define PIECE_WIDTH 32
#define PIECE_HEIGHT 32
// Define next pieces buffer
#define NEXT_PIECES 255
class Gameboard : public GenericEntity {
public:
Gameboard(SDL_Renderer *renderer, GameboardParameters parms);
~Gameboard();
void Render(float delta);
void Update(float delta);
void CreateLevel();
public:
float FALL_SPEED = 50;
Piece p1_pieces[BOARD_WIDTH][BOARD_HEIGHT];
Piece next_pieces[NEXT_PIECES];
private:
SDL_Texture *sdlTextureBackground;
SDL_Texture *sdlTextureBackgroundGrid;
SDL_Texture *texTarget;
};
#endif //GAMEBOARD_H
Gameboard.cpp
Gameboard::Gameboard(SDL_Renderer *renderer, GameboardParameters parms) : GenericEntity(renderer) {
SDL_Surface *sdlSurfaceBackground = IMG_Load("resources/backgrounds/SC_S_01.BMP");
sdlTextureBackground = SDL_CreateTextureFromSurface(renderer, sdlSurfaceBackground);
SDL_FreeSurface(sdlSurfaceBackground);
SDL_Surface *sdlSurfaceBackgroundGrid = IMG_Load("resources/backgrounds/GRID-768X1408.PNG");
sdlTextureBackgroundGrid = SDL_CreateTextureFromSurface(renderer, sdlSurfaceBackgroundGrid);
SDL_FreeSurface(sdlSurfaceBackgroundGrid);
}
...
void Gameboard::Render(float delta) {
// Clear screen
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
// Render background
SDL_RenderCopy(renderer, sdlTextureBackground, NULL, NULL);
}
There is likely an error in one of the initialisations. In general you have to assume that resource initialization can fail so you will need to check those errors. SDL offers methods to check for errors.
The documentation for IMG_Load
states that NULL is returned on error. That may be an error source. You should check for null and use IMG_GetError to gain some more insights.
More Tips for your journey:
You can not catch all exceptions using try
/catch
. Here is a jump off point for that information.
In C++ you want to use the RAII Idiom for acquisition.
You should also consider using std::unique_ptr (or the shared variant in some cases) to handle your raw pointers. This also works for C-Style APIs like SDL.
For SDL I would also supplement your studies with Lazy Foos tutorials.
Good Luck.