SDL event loop quitting? - c++

I am making an RTS in C++ using SDL for graphics.
Every time I run the game, it crashes without errors or anything in the compiler debug window. It doesn't crash immediately or consistently, sometimes taking 10 seconds to crash and other times taking 2 minutes to crash.
When I played around with return values (at the end of the main function) it turned out it wasn't crashing, but rather quitting as the return values were consistent with what I changed it to.
The only theory that I have is that my poll event loop is glitching and telling the program to quit when it isn't supposed to.
Here is my event loop, contained within my game loop:
if( SDL_PollEvent( &event ) )
{
if( event.type == SDL_MOUSEMOTION )
{
mx = event.motion.x;
my = event.motion.y;
}
if( event.type == SDL_MOUSEBUTTONDOWN )
{
if( hut.getselected() && hut.getplacable() )
{
hut.place( map );
}
}
if( event.type == SDL_QUIT )
{
quit = true;
}
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE: quit = true; break;
}
}
Is it possible that when the mouse moves or clicks, that it is confusing it for exiting? I don't think the ram is overloading either because it only displays what it needs to tile-wise.
Is it also possible that my compiler, VisualC++, is screwing up?

How about changing the switch at end of your snippet to:
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) {
quit = true;
}
Because in your code you check keysym for all events, so usually event is of wrong type when you test if it is escape, and you get "garbage" value for keysym, and sometimes it matches with ESC.
Actually might be good idea to test the event.type with switch:
switch(event.type) {
case SDL_MOUSEMOTION:
//....
break;
case SDK_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
quit = true;
break;
// cases for other keypresses
}
break;
// cases for other events
}

Related

SDL cannot read input from keyboard

I am having trouble dealing with input from the keyboard. Somehow all the letter ones are extremely slow(always a big delay), most of the time it just doesn't load at all. But the up down left right and number keys all work really well. Does anyone know why?
This is my program:
while (!quit)
{
while (SDL_PollEvent(&e) != 0 )
{
SDL_StartTextInput();
//User requests quit
switch (e.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_TEXTINPUT:
if (e.key.keysym.sym == SDLK_w)
std::cout << "w ";
break;
case SDL_KEYDOWN:
if (e.key.keysym.sym == SDLK_1)
std::cout << "1 ";
break;
}
As already mentioned in your comments, you never check the event type.
event.type can be SDL_TEXTINPUT or SDL_KEYDOWN for example.
Here I have a typical event loop copied from one of my projects:
while (SDL_PollEvent(&event)) {
SDL_StartTextInput();
switch (event.type) {
case SDL_QUIT:
appRunning = false;
break;
case SDL_TEXTINPUT:
// here you can use event.text.text; to
break;
case SDL_KEYDOWN:
char keyDown = event.key.keysym.scancode;
break;
}
}
Here is the official list of SDL_Events: https://wiki.libsdl.org/SDL2/SDL_Event
SDL provides event handlers for keyboard input.
SDL_Event e;
.
.
/* Poll for events. SDL_PollEvent() returns 0 when there are no */
/* more events on the event queue, our while loop will exit when */
/* that occurs. */
while(SDL_PollEvent(&e)){
/* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
switch(event.type){
case SDL_KEYDOWN:
//Keypress
break;
case SDL_KEYUP:
//Key Release
break;
default:
break;
}
Then, you can get the value of key->keysym.sym for the keyboard input.

SDL 2.0.3 event loop doesn't work

I can't make SDL wait for a an event. When I try to the window just briefly flashes on my screen and then disappears, I don't get any errors or anything in my IDE, nothing in the build log either. I looked at lazyfoo and the SDL wiki, but no help. I'm using Code blocks and SDL 2.0.3 Here's what I have so far:
while(&event != NULL && !quit)
{
while(SDL_PollEvent(&event) > 0)
{
if(event.type == SDL_QUIT)
{
quit = true;
}
else
{
if(event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_LEFT:
currentSurface = keyPressSurfaces[KEY_PRESS_LEFT];
break;
case SDLK_UP:
currentSurface = keyPressSurfaces[KEY_PRESS_UP];
break;
case SDLK_RIGHT:
currentSurface = keyPressSurfaces[KEY_PRESS_RIGHT];
break;
case SDLK_DOWN:
currentSurface = keyPressSurfaces[KEY_PRESS_DOWN];
break;
default:
currentSurface = keyPressSurfaces[KEY_PRESS_DEFAULT];
break;
}
}
}
}
}
Any suggestions?
you are polling for an event SDL_PollEvent, if you want to wait for an event, you should use SDL_WaitEvent
First, is quit false before you enter this loop?
If there are no events to poll, I believe event is NULL, causing your program to exit the next time it sees while(&event != NULL && !quit). If there are no immediate events on startup, you might not ever make it into that loop. Edit: Whoops - thought event was a pointer:
The while (SDL_PollEvent(&event)) line will loop through until all pending events have been handled. The outter while (!quit) would then keep your program open even if there are no events to process at the moment.

The correct way to test 'SDL_PollEvent' in a 'while'

As the manual says, the function SDL_PollEvent "Returns 1 if there is a pending event or 0 if there are none available." , that's why we use the test SDL_PollEvent(&e)!=0 (where e is a SDL_Event).
But, what about use this test: !SDL_PollEvent(&e)? It should work,but apparently it cause some problem.
Here an example of code:
#include <SDL2/SDL.h>
#include <stdio.h>
int main(int argc, char* args[]){
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("Hello",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100, SDL_WINDOW_SHOWN);
SDL_Event e;
int quit=0;
while(!quit){
//Here the test
while (!SDL_PollEvent(&e)){
if (e.type==SDL_QUIT)
quit=1;
else if ( e.type == SDL_KEYDOWN )
printf( "Hello\n" );
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
What this code should do is open a new window and print "Hello" in the console every time a key is pressed. This code works fine whit the test SDL_PollEvent(&e)!=0 but it doesn't read the SDL_KEYDOWN event when I use the test !SDL_PollEvent(&e) (but it DOES enter in the while and process the SDL_QUIT event without any problem).
Why this behaviour?
while (!SDL_PollEvent(&e))
needs to be:
while (SDL_PollEvent(&e))
if it should be the same as SDL_PollEvent(&e) != 0
because !SDL_PollEvent(&e) is the same as calling while(0)
(1 != 0) is true, but (!1) is false.
You probably should use SDL_WaitEvent instead anyway.
Addendum
One may think it's more clear to do something like this, since it ensures that user input is reacted upon. However, this is currently an OS dependent and possibly crazy CPU hog and will max out your CPU for this thread (on Windows). So you may think that you can just put a 1 second wait there, but then your window will become completely unresponsive or very laggy at best...
If you can live with a little CPU overhead for doing nothing, then you can compromise with using an 20-100 [ms] delay.
...
// Set the event handler...
...
bool isRunning = true;
while (isRunning) {
// Do the main thing here...
...
while(SDL_PollEvent(&windowEvent)) {
switch (windowEvent.type) {
case SDL_QUIT: isRunning = false;
case SDL_KEYDOWN: isRunning = false;
case SDL_MOUSEBUTTONDOWN: isRunning = false;
break;
}
SDL_Delay(100); // Wrong!
}
}
// End the program
So clearly this is not the correct way either. We need to use some other mechanism. Looking at the SDL repo, we find a long but very relevant discussion for the open issue:
SDL_WaitEvent causes high cpu usage
To Fix the issue
Make sure you put the delay in the outer loop, before the SDL_PollEvent().
// main loop
...
while(SDL_PollEvent(&windowEvent)) {
switch (windowEvent.type) {
case SDL_QUIT: isRunning = false;
case SDL_KEYDOWN: isRunning = false;
case SDL_MOUSEBUTTONDOWN: isRunning = false;
break;
}
}
SDL_Delay(100); // Right!
}

SDL x and y movement

Why wont this code let me move up or left?
while( quit == false )
{
apply_surface( 0,0, back,screen );
apply_surface( playerx,playery,player, screen );
SDL_Flip( screen );
//While there's an event to handle
while( SDL_PollEvent( &event ) )
{
if(event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_UP:playery=playery-10;
case SDLK_DOWN:playery=playery+10;
case SDLK_LEFT:playerx=playerx-10;
case SDLK_RIGHT:playerx=playerx+10;
}
}
You need to use a break after each case in the switch Otherwise the execution "falls through" to the next line, potentially cancelling your action (and indeed SDLK_UP and SDLK_LEFT are the ones where the cancellation happens)

SDL: Two Event Loops?

Take a look at this piece of code here:
void game::startLoop()
{
while(QUIT == false)
{
getRoomUpdate();
applySurface(-15, 280, zombie_lefthand, buffer);
applySurface(455, 280, zombie_righthand, buffer);
SDL_Flip(buffer);
while(SDL_PollEvent(&gameEvent))
{
if(gameEvent.type == SDL_QUIT)
{
QUIT = true;
}
}
while(SDL_WaitEvent(&keyEvent))
{
switch(keyEvent.type)
{
case SDL_KEYDOWN:
switch(keyEvent.key.keysym.sym)
{
//blahkeypress
}
}
}
}
}
I'm trying to figure out how to allow SDL_QUIT to work while we're waiting for a keypress. Is there a way to do this or do you guys have a better idea?
I'm a bit of a newbie so please be specific. :D
The name keyEvent is misleading. SDL_WaitEvent will wait for any sort of event, including QUIT.
SDL_Event event;
SDL_WaitEvent(&event);
switch (event.type) {
case SDL_QUIT:
quit = true;
break;
/* cases for keyboard events, etc. */
}
Minimal changes:
You could add if (QUIT) break; after the inner while loop that sets QUIT.
Or, you could move the outer while loop to a separate function and add a return; after QUIT = true;.
Better changes:
Refactor your code similar to many examples available on the web (at sourceforge, or at molly rocket, or just google it).