There is the following code. The desired result is that a window is created and a filled circle is drawn:
#include <SDL2/SDL.h>
#include <iostream>
#include <SDL2/SDL2_gfxPrimitives.h>
int main()
{
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "Could not initialise" << std::endl;
return 1;
}
window = SDL_CreateWindow("MyGame",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
480,
SDL_WINDOW_SHOWN);
if(!window)
{
std::cout << "Could not create the window" << std::endl;
return 1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderClear(renderer);
Sint16 circleR = 100;
Sint16 circleX = 300;
Sint16 circleY = 300;
SDL_Surface* windowSurface = SDL_GetWindowSurface(window);
Uint32 circleColour = SDL_MapRGB(windowSurface->format, 255, 0, 0);
int result = filledCircleColor(renderer, circleX, circleY, circleR, circleColour);
std::cout << "drawing the circle r " << circleR << " x " << circleX << " y " << circleY << " circleColour " << circleColour << std::endl;
std::cout << "draw circle result " << result << std::endl;
SDL_RenderPresent(renderer);
bool run = true;
while(run)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
{
run = false;
}
}
}
SDL_Quit();
return 0;
}
The problem is that the circle is not drawn - the window is all black.
The output:
drawing the circle r 100 x 300 y 300 circleColour 16711680
draw circle result 0
filledCircleColor returns 0 what should mean that there's no error.
What should be done so that the circle is drawn? I'm using SDL 2.0.2 on Ubuntu with SDL2 gfx extension.
About SDL_GetWindowSurface, the documentation says : "You may not combine this with 3D or the rendering API on this window."
For me, in your example, SDL_GetWindowSurface returns null.
The filledCircleColor() function takes a color of the form 0xRRGGBBAA.
It works after removing the surface part, and changing to :
int result = filledCircleColor(renderer, circleX, circleY, circleR, 0xFF0000FF);
Related
This is my .cpp file:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
bool runningOnEmpty = false;
const char* title;
int xpos, ypos, width, height;
bool fullscreen = false;
SDL_Window *window;
SDL_Renderer *renderer;
void init(){
int flags = 0;
if(fullscreen){
flags = SDL_WINDOW_FULLSCREEN;
}
if(!SDL_Init(SDL_INIT_EVERYTHING)){
std::cout << "Sdl initialised!!\n";
window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
if(window){
std::cout << "window created!!\n";
}
renderer = SDL_CreateRenderer(window, -1, 0);
if(renderer){
std::cout << "renderer created!!\n";
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
}
runningOnEmpty = true;
} else {
runningOnEmpty = false;
}
if(TTF_Init()==-1) {
std::cout << "cannot init TTF: " << TTF_GetError() << "\n";
} else {
std::cout << "TTF initialized!" << "\n";
}
}
void render(){
SDL_RenderClear(renderer);
TTF_Font* rFont = TTF_OpenFont("./fonts/roboto.ttf", 20);
if(!rFont){
std::cout << "Cannot open font: " << TTF_GetError() << "\n";
}
SDL_Color White = {0, 0, 0};
SDL_Surface* surfaceMessage = TTF_RenderText_Solid(rFont, "Score: ", White);
if(surfaceMessage == NULL)
std::cout << "Cannot make surface!" << SDL_GetError() << "\n";
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_Rect mr;
mr.x = 50, mr.y = 50, mr.w = 100, mr.h = 100;
if(Message = NULL)
std::cout << "Cannot make texture!" << SDL_GetError() << "\n";
if(SDL_RenderCopy(renderer, Message, NULL, &mr))
std::cout << "Cannot render text!" << SDL_GetError() << "\n";
SDL_FreeSurface(surfaceMessage);
SDL_RenderPresent(renderer);
}
void clean(){
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
std::cout << "Game cleaned!\n";
}
void handleEvents(){
SDL_Event event;
SDL_PollEvent(&event);
switch(event.type){
case SDL_QUIT:
runningOnEmpty = false;
break;
default:
break;
}
}
int main(){
title = "Test";
xpos = SDL_WINDOWPOS_CENTERED;
ypos = SDL_WINDOWPOS_CENTERED;
width = 800, height = 900;
fullscreen = false;
init();
render();
while(runningOnEmpty){
handleEvents();
}
clean();
return 0;
}
It compiles without error, and when I run the executable it renders a white window, with no text on it(even if it should have some text).
The error comes when I try to use SDL_RenderCopy, and as I acknowledged using SDL_Error(), apparently the texture is invalid, even if I check it before using it.
This is the exact thing that I get in the console when running the code:
Sdl initialised!!
window created!!
renderer created!!
TTF initialized!
Cannot render text!Invalid texture
Game cleaned!
if(Message = NULL) is an assignment, not comparison, so your previous value of Message is lost and it is NULL after that, and that result is used as logic value (NULL == 0 == false, for that matter). Enabling compiler warnings should produce a message pinpointhing this specific problem, e.g. -Wall for gcc gives
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
if(Message = NULL)
To compare values, use == operator.
Also your texture goes out of scope without DestroyTexture, which is clearly a resource leak.
I'm trying to open a window with SDL2 in visual studio 2015. I've set a .bmp image in my code to display to the screen in a window, but when I run my code the program returns 0 and closes without a window. The .bmp image is in the project folder. How do you display the window?
#include <SDL.h>
#include <iostream>
int main(int argc, char* args[])
{
SDL_Window *window = nullptr;
SDL_Surface *windowSurface = nullptr;
SDL_Surface *imageSurface = nullptr;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
std::cout << "Game Initialization error: " << SDL_GetError() << std::endl;
{
window = SDL_CreateWindow("Contrast Beta 0.0.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 920, SDL_WINDOW_HIDDEN | SDL_WINDOW_FULLSCREEN);
if (window == NULL)
std::cout << "Window Creation Failed, Error: " << SDL_GetError() << std::endl;
else
{
//Window Created
windowSurface = SDL_GetWindowSurface(window);
imageSurface = SDL_LoadBMP("Background.bmp");
if (imageSurface == NULL)
std::cout << "Error loading background: " << SDL_GetError() << std::endl;
else
{
SDL_BlitSurface(imageSurface, NULL, windowSurface, NULL);
SDL_UpdateWindowSurface(window);
SDL_Delay(2000);
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Remove SDL_WINDOW_HIDDEN; that's all.
I'm trying to get an SDL window to appear, but it doesn't seem to be working. The program will run, and the function to show the window will run with no errors, but nothing shows up on my screen. I only have an icon in the dock that says that the program is not responding. Here's my code:
int main(int argc, const char * argv[]) {
MainComponent mainComponent;
mainComponent.init();
char myVar;
cout << "Enter any key to quit...";
cin >> myVar;
return 0;
}
void MainComponent::init() {
//Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("My Game Window", 100, 100, 100, 100, SDL_WINDOW_SHOWN);
cout << screenWidth << " " << screenHeight << endl;
if(window == nullptr) {
cout << "Error could not create window" << SDL_GetError() << endl;
}
SDL_Delay(5000);
}
Here's a screenshot of the icon on the dock https://www.dropbox.com/s/vc01iqp0z07zs25/Screenshot%202016-02-02%2017.26.44.png?dl=0
Let me know if there's something I'm doing wrong, thanks!
SDL_Renderer should be initialized to handle the rendering. This is explained in detailed here What is a SDL renderer?.
Here's a modified code above with an initialized renderer;
#include <SDL2/SDL.h>
#include <iostream>
using namespace std;
class MainComponent
{
public:
void init();
~MainComponent();
private:
SDL_Window *window;
SDL_Renderer* renderer;
};
MainComponent::~MainComponent()
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
void MainComponent::init() {
//Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
int screenWidth = 400;
int screenHeight = 300;
window = SDL_CreateWindow("My Game Window", 100, 100, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, 0);
cout << screenWidth << " " << screenHeight << endl;
if(window == nullptr) {
cout << "Error could not create window" << SDL_GetError() << endl;
}
//change the background color
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
// Clear the entire screen to our selected color.
SDL_RenderClear(renderer);
// Up until now everything was drawn behind the scenes.
// This will show the new, red contents of the window.
SDL_RenderPresent(renderer);
SDL_Delay(5000);
}
int main(int argc, const char * argv[]) {
MainComponent mainComponent;
mainComponent.init();
char myVar;
cout << "Enter any key to quit...";
cin >> myVar;
SDL_Quit();
return 0;
}
This should compile and run properly.
Hope that helps.
Stack Trace :
So, I'm trying to create a 2D game and right now I'm trying to display and move a image, however when I Debug the game/run it, visual studio and the game freezes and can't quit, not even when using the task manager to kill it.
The only way to unfreeze it is by logging off or restarting the pc which forces both of them to close.
I also get some weird error :
Unhandled exception at 0x71002A95 (SDL2_ttf.dll) in SDLGame.exe: 0xC0000005: Access violation reading location 0x00000000.
I have no idea what it means and how to fix it, but I'm guessing it has something to do with my code that I need to change.
Here's my code :
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
// Macros
#define pause system("PAUSE"); // Works on windows only, removed in alpha / beta versions.
// Pre "init" of functions
void QuitGame();
int InitGame();
void processInput();
void InitRects();
// Variables
int FramesPassed = 0;
int FramesPerSecond = 0; // Not used yet
SDL_Renderer* renderer = nullptr;
SDL_Window* window = nullptr;
SDL_Event evnt;
SDL_Rect sprite1_Rect;
SDL_Rect FPS_Text_Rect;
TTF_Font* Sans = TTF_OpenFont("Fonts/Aaargh.ttf", 40);
SDL_Color Color_White = { 255, 255, 255 };
SDL_Surface* FPS_Text_Surface = nullptr;
SDL_Texture* FPS_Text = nullptr;
SDL_Texture* testImg = nullptr;
static bool isRunning = true;
int SDL_main(int argc, char* argv[])
{
InitGame();
InitRects();
std::cout << "Displaying text on screen using SDL TTF doesn't work" << std::endl;
std::cout << "This happens when the TTF Surface is being rendered on screen" << std::endl;
std::cout << "check line : 123 and 124." << std::endl;
while (isRunning)
{
FramesPassed++;
processInput();
SDL_RenderClear(renderer); // Clears the last/current frame?
// Render testImage on screen. (needs to be between render present and clear.)
SDL_RenderCopy(renderer, testImg, NULL, &sprite1_Rect);
SDL_RenderCopy(renderer, FPS_Text, NULL, &FPS_Text_Rect);
SDL_RenderPresent(renderer); // Pretty much draws everything again.
}
return 0;
QuitGame();
}
int InitGame()
{
std::cout << "Game Initializing..." << std::endl;
std::cout << "TTF SDL Initializing..." << std::endl;
if (TTF_Init() < 0)
{
std::cout << "SDL TTF Failed To Initialize : " << TTF_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL TTF Initialized Successfully" << std::endl;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "SDL Initialization Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initializing" << std::endl;
window = SDL_CreateWindow("Game Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 720, SDL_WINDOW_SHOWN);
if (window == NULL)
{
std::cout << "Window Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initialized Successfully" << std::endl;
std::cout << "Renderer Initializing..." << std::endl;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
std::cout << "Renderer Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "Renderer Initialized Successfully" << std::endl;
// This line (under) crashes game, and crashes visual studio...
FPS_Text_Surface = TTF_RenderText_Solid(Sans, "Frames Passed : " + FramesPassed, Color_White);
testImg = IMG_LoadTexture(renderer, "images/test.bmp");
FPS_Text = SDL_CreateTextureFromSurface(renderer, FPS_Text_Surface);
}
}
}
}
std::cout << "Game Has Successfully Initialized!" << std::endl;
return 0;
}
void InitRects()
{
sprite1_Rect.h = 32;
sprite1_Rect.w = 32;
sprite1_Rect.x = 10;
sprite1_Rect.y = 10;
FPS_Text_Rect.h = 100;
FPS_Text_Rect.w = 50;
FPS_Text_Rect.x = 2;
FPS_Text_Rect.y = 2;
}
void processInput()
{
if (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
QuitGame();
break;
case SDL_KEYDOWN:
switch (evnt.key.keysym.sym) {
case SDLK_a:
sprite1_Rect.x -= 1;
break;
case SDLK_d:
sprite1_Rect.x += 1;
break;
case SDLK_w:
sprite1_Rect.y-= 1;
break;
case SDLK_s:
sprite1_Rect.y += 1;
break;
}
break;
}
}
}
void QuitGame()
{
isRunning = false;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
The problem is that you have the font as a global variable and load it straight away!
You need to call TTF_Init() first and load the font after!
By using a global vairable your loading it before initializing SDL_TTF, and this way TTF_OpenFont() will return a nullptr and if you try to read a nullptr gives an Access violation reading location 0x00000000 error!
Just call TTF_OpenFont() in a function and after TTF_Init() and it will work!
Just a tip you should check that Sans isn't a nullptr before using it!
I'm developing in VS2013 on a Windows 8.1 machine. The window flashes briefly on the screen (despite having a 2 second delay in the code).
Here is all the code:
#include <SDL.h>
#include <iostream>
int main(int argc, char **argv)
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 4;
}
//open a window
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 3;
}
//renderer
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
return 2;
}
//load bitmap
SDL_Surface *bmp = SDL_LoadBMP("helloworld.jpg");
if (bmp == nullptr){
std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
return 6;
}
SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
SDL_FreeSurface(bmp);
if (tex == nullptr){
std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
return 5;
}
SDL_RenderClear(ren);
SDL_RenderCopy(ren, tex, NULL, NULL);
SDL_RenderPresent(ren);
SDL_Delay(2000);
return 0;
}
It exits with a code 6. I was thinking it couldn't find the helloworld.jpg file. But, its there. I moved it from location to location hoping I was just an idiot. No luck. Its currently in the same directory as the .exe file.
SDL_LoadBMP will only load BMP formatted pictures, and guessing by the extension you have chosen you look to be using a JPEG formatted image, and your program is refusing to load it.
see SDL_Image for one possible solution.