C++ SDL2 window not opening - c++

i coded this.
#include <iostream>
#include "SDL.h"
int main(int argc , char** args)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* win = SDL_CreateWindow("my window", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (!win)
{
std :: cout << "Failed to create a window! Error: " << SDL_GetError() << "\n";
}
SDL_Surface* winSurface = SDL_GetWindowSurface(win);
SDL_UpdateWindowSurface(win);
SDL_FillRect(winSurface, NULL, SDL_MapRGB(winSurface->format, 255, 90, 120));
SDL_DestroyWindow(win);
win = NULL;
winSurface = NULL;
return 0;
}
when i compile it, it opens the window, and it immediately closes. But the console doesn't. Here is a screenshot of my console(maybe it could help solving the problem?)
Would there be any solution to get the Window to not close?

Would there be any solution to get the Window to not close?
Start up an event-handling loop and handle some events:
// g++ main.cpp `pkg-config --cflags --libs sdl2`
#include <SDL.h>
#include <iostream>
int main( int argc, char** argv )
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* win = SDL_CreateWindow("my window", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (!win)
{
std :: cout << "Failed to create a window! Error: " << SDL_GetError() << "\n";
}
SDL_Surface* winSurface = SDL_GetWindowSurface(win);
bool running = true;
while( running )
{
SDL_Event ev;
while( SDL_PollEvent( &ev ) )
{
if( ( SDL_QUIT == ev.type ) ||
( SDL_KEYDOWN == ev.type && SDL_SCANCODE_ESCAPE == ev.key.keysym.scancode ) )
{
running = false;
break;
}
}
SDL_FillRect(winSurface, NULL, SDL_MapRGB(winSurface->format, 255, 90, 120));
SDL_UpdateWindowSurface(win);
}
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}

Related

SDL2 empty transparent window in Linux

Here is some sample SDL2 code I tried to run on my Linux computer running Ubuntu 18.04 with KDE Plasma Desktop Environment (I have multiple desktop environments installed in case it is relevant):
#include<iostream>
#include<SDL2/SDL.h>
int main(int argc, char** argv)
{
if(SDL_Init(SDL_INIT_VIDEO) != 0){
std::cerr << "SDL_Init() Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_Window* win = SDL_CreateWindow(
"Hello world",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640,480,
0
);
if(win == nullptr){
std::cerr << "SDL_CreateWindow() Error: " << SDL_GetError() << std::endl;
return 1;
}
//Create and init the renderer
SDL_Renderer* ren = SDL_CreateRenderer(win, -1, 0);
if(ren == nullptr){
std::cerr << "SDL_CreateRenderer() Error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow(win);
return 1;
}
//Render something
SDL_RenderSetLogicalSize(ren,640,480);
//Set colour of renderer
SDL_SetRenderDrawColor(ren,255,0,0,255);
//Clear the screen to the set colour
SDL_RenderClear(ren);
//Show all the has been done behind the scenes
SDL_RenderPresent(ren);
//Delay so that we can see what is on the screen
SDL_Delay(5000);
//Clean Up
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
The red window that is supposed to appear appears only once when I run the program for the first time. All subsequent executions produce an empty transparent window with whatever is in the background. The background image drags along with the window.
I have tried SDL_WINDOW_SHOWN flag in SDL_CreateWindow() as well as SDL_RENDER_ACCELERATED flag for SDL_CreateRenderer().
The only way to produce the red screen again is to reboot the system.
I even compiled and ran this with an IDE (CodeLite) and I still got the same results.
This particular question on SO shows similar problems. But the OP isn't using Linux and the problem isn't exactly the same.
Other posts on this website mention event processing but I haven't gotten that far. If at all it is necessary, I would be grateful for some resources on it as the documentation doesn't explain much.
Update:This program runs fine on another computer running Lubuntu 18.10.
Replace the SDL_Delay() (which blocks all event processing like notifying X11/Wayland & your window manager that your process is still alive) with a loop that calls SDL_PumpEvents() somehow, either directly (like below) or indirectly via SDL_PollEvent()/SDL_WaitEvent():
const Uint32 startMs = SDL_GetTicks();
while( SDL_GetTicks() - startMs < 5000 )
{
SDL_PumpEvents();
//Render something
SDL_RenderSetLogicalSize(ren,640,480);
//Set colour of renderer
SDL_SetRenderDrawColor(ren,255,0,0,255);
//Clear the screen to the set colour
SDL_RenderClear(ren);
//Show all the has been done behind the scenes
SDL_RenderPresent(ren);
}
All together:
#include <iostream>
#include <SDL2/SDL.h>
int main( int argc, char** argv )
{
if( SDL_Init( SDL_INIT_VIDEO ) != 0 )
{
std::cerr << "SDL_Init() Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_Window* win = SDL_CreateWindow
(
"Hello world",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480,
0
);
if( win == nullptr )
{
std::cerr << "SDL_CreateWindow() Error: " << SDL_GetError() << std::endl;
return 1;
}
//Create and init the renderer
SDL_Renderer* ren = SDL_CreateRenderer( win, -1, 0 );
if( ren == nullptr )
{
std::cerr << "SDL_CreateRenderer() Error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow( win );
return 1;
}
const Uint32 startMs = SDL_GetTicks();
while( SDL_GetTicks() - startMs < 5000 )
{
SDL_PumpEvents();
//Render something
SDL_RenderSetLogicalSize( ren, 640, 480 );
//Set colour of renderer
SDL_SetRenderDrawColor( ren, 255, 0, 0, 255 );
//Clear the screen to the set colour
SDL_RenderClear( ren );
//Show all the has been done behind the scenes
SDL_RenderPresent( ren );
}
//Clean Up
SDL_DestroyRenderer( ren );
SDL_DestroyWindow( win );
SDL_Quit();
return 0;
}

window doesnt show image SDL

The program doesnt show the image in the window i have created , also i dont get any of the fail messages that i have set , which means the values are not null.
What is the problem?
Here is the code:
#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
int main(int argc,char* argv[])
{
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
bool quit = false;
SDL_Surface *tmpsur = NULL;
SDL_Texture *tex = NULL;
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("First window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, 0);
tmpsur = IMG_Load("assets/player.png");
if (tmpsur == NULL)
{
std::cout << "fail" << std::endl;
}
tex = SDL_CreateTextureFromSurface(renderer,tmpsur);
if (tex == NULL)
{
std::cout << "fail 2" << std::endl;
}
SDL_FreeSurface(tmpsur);
SDL_RenderPresent(renderer);
while (!quit)
{
while (SDL_PollEvent(&event) != 0)
{
if(event.type == SDL_QUIT)
{
quit = true;
}
}
}
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
return 0;
}
You need to copy your texture onto the render target. Before presenting your renderer you need to call SDL_RenderCopy like this:
SDL_RenderCopy(renderer, text, nullptr, nullptr);
SDL_RenderPresent(renderer);
The nullptrs in the argument will make it copy the texture over all your target (the window).

SDL window not showing?

I have this simple code for SDL.
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
using namespace std;
int main(int argc, char * argv[]){
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
return 1;
}
SDL_Window * win = SDL_CreateWindow("Window", 0, 0, 1920, 1080, SDL_WINDOW_FULLSCREEN_DESKTOP);
if(win == nullptr){
return 1;
}
SDL_Quit();
return 0;
}
None of this shows a window, I have error checked everything. It was working previously, but now it just opens and closes. I'm running on Xcode, if that helps.
Like the others state, your program terminates immediately so the window should "flash" momentarily. You can have the window appear for a few seconds by using SDL_Delay:
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;
SDL_Quit();
return 1;
}
SDL_Delay(2000);
SDL_DestroyWindow(win);
SDL_Quit();
And remember to call SDL_DestroyWindow.
A while(true) {} loop will just cause your program to freeze. You probably want something like the following so that it listens for events, and you can close the window at your leisure.
SDL_Event e;
bool quit = false;
while (!quit){
while (SDL_PollEvent(&e)){
if (e.type == SDL_QUIT){
quit = true;
}
if (e.type == SDL_KEYDOWN){
quit = true;
}
if (e.type == SDL_MOUSEBUTTONDOWN){
quit = true;
}
}
}

SDL_CreateWindow fails, SDL_GetError shows nothing. Why does it fail?

I have a project that uses SDL 1.2 and want to migrate it to SDL 2.0. To keep things simple I tried writing a simple program just to get familiar with the changes.
However, SDL_CreateWindow is failing, and SDL_GetError is not showing anything. So I don't know why creating the window isn't working.
The window is actually created, but then disappears.
#include <SDL.h>
#include <stdio.h> // printf etc
#include <stdlib.h> // abs, malloc, realloc
#include <stdint.h> // uint8_t, uint16_t, int32_t
#define WIDTH 853
#define HEIGHT 480
int main(int argc, char** argv) {
SDL_Renderer* renderer;
SDL_Window* window;
SDL_Texture* screenTexture;
SDL_Event event;
Uint8* screenBuffer;
FILE* fp;
int quit = 0;
fp = fopen("SDL2test.log", "w");
if (!fp) {
printf("\nCould not create log file");
return -1;
}
if (SDL_Init(SDL_INIT_VIDEO) < 0 ) {
fprintf(fp, "\nCould not initialise SDL: %s\n", SDL_GetError() );
return -2;
}
window = NULL;
if ( NULL == ( window = SDL_CreateWindow("SDL2 test",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0)));{
fprintf(fp, "Could not create SDL window: %s\n", SDL_GetError() );
SDL_Delay(3000);
SDL_Quit();
return -3;
}
if ( !( renderer = SDL_CreateRenderer(window, -1, 0) ) ); {
SDL_Quit();
return -4;
}
if ( !( screenTexture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGB24, SDL_TEXTUREACCESS_STATIC, WIDTH, HEIGHT)));
screenBuffer = (Uint8*)malloc( sizeof(Uint8) * 3 * WIDTH * HEIGHT );
if (NULL == screenBuffer){
SDL_Quit();
return -5;
}
memset(screenBuffer, 0, 3 * WIDTH * HEIGHT); //set to black
SDL_UpdateTexture( screenTexture,
NULL,
screenBuffer,
WIDTH * sizeof(Uint8) );
while( !quit && ( SDL_WaitEvent(&event) ) ) {
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, screenTexture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_Delay(3000);
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}
This is your create window if statement:
if ( NULL == ( window = SDL_CreateWindow( ...code... ) ) ); //what is ; doing here
{
fprintf(fp, "Could not create SDL window: %s\n", SDL_GetError() );
SDL_Delay(3000);
SDL_Quit();
return -3;
}
Did you notice the ; at the end of first line?
This means the part of the code in the brackets gets executed every time. Basically the code looks like this:
if ( NULL == ( window = SDL_CreateWindow( ...code... ) ) ); //end of if
{ //gets executed every time
fprintf(fp, "Could not create SDL window: %s\n", SDL_GetError() );
SDL_Delay(3000);
SDL_Quit();
return -3;
}
There is at least one such error in the code.

Why the game window closes after specific time?

Why the window that created by SDL Game Library are automatically closed after specific time.
I know the reason is SDL_Delay() function, but if not used that function, the game will appear runtime error.
How can I create a window that continuously work without appear in specific period time ?
My code(Simplest code):
SDL_Window *window;
SDL_Renderer *render;
int main(int argc, char* args[]){
if(SDL_Init(SDL_INIT_EVERYTHING) >= 0){
window = SDL_CreateWindow("Simple game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
if(window != 0){
render = SDL_CreateRenderer(window, -1, 0);
}
}else{
return 1;
}
SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
SDL_RenderClear(render);
SDL_RenderPresent(render);
SDL_Delay(3000);
SDL_Quit();
return 0
}
You need to loop forever and call SDL update screen functions. Read LazyFoo tutorials found here: http://lazyfoo.net/SDL_tutorials
Or here a short code to get you started:
#include <iostream>
#include "SDL/SDL.h" // basic SDL
#include <string>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BBP = 32; // bits per-pixel
SDL_Surface* screen = NULL; // display screen
SDL_Event event; // grab events
using namespace std;
bool init() {
// initialize SDL
if(SDL_Init( SDL_INIT_EVERYTHING ) == -1)
return false;
//the screen image
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT,
SCREEN_BBP, SDL_SWSURFACE );
if(!screen) {
cout << "error creating screen" << endl;
return false;
}
//Set the window caption
SDL_WM_SetCaption("Event Test", NULL );
return true;
}
int main(int argc, char* argv[])
{
try
{
// make sure the program waits for a quit
bool quit = false;
cout << "Starting SDL..." << endl;
// Start SDL
if(!init()) {
cout << "initialize error" << endl;
return false;
}
// main loop
while( quit == false )
{
if (SDL_PollEvent(&event))
{
// The x button click
if(event.type == SDL_QUIT)
{
//quit the program
quit = true;
}
}
// Fill the screen white
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB(
screen->format, 0xFF, 0xFF, 0xFF ) );
//Update screen
if(SDL_Flip(screen) == -1)
return -1;
}
}
catch (exception& e)
{
cerr << "exception caught: " << e.what() << endl;
return -1;
}
return 0;
}