Ejemplo n.º 1
0
void *SDLStub::addTimer(uint32 delay, TimerCallback callback, void *param) {
	return SDL_AddTimer(delay, (SDL_NewTimerCallback)callback, param);
}
Ejemplo n.º 2
0
Archivo: game.c Proyecto: shiver/vectir
// the main game loop which will run until the game is done
void game_loop() {
	SDL_Event event, e;
	SDL_TimerID timer;
	int last_game_update = 0;
	int last_particle_update = 0;
	int last_render = 0;
	int previous_level = 0;

	debug_print("Loading media...");
	load_media();

	// check if we want to show score increments
	game.show_score_increments = atoi(config_getValue("show_score_increments"));

	// setup input
	input_init();

	// create & show menu
	ui_menuInit();
	ui_toggleMenuVisible();
	SDL_SetEventFilter(ui_handleEvents);

	// loop forever
	debug_print("Entering main game loop...");
	while (1) {
		// see if its time to trigger an update (make sure we're not paused either)
		if (!game.paused && 
					SDL_GetTicks() - last_game_update > game_getGameUpdateFreq()) {
			last_game_update = SDL_GetTicks();		// remember time of last update
			game_update();
		}

		if (game.show_score_increments) { // at the moment we just have the one particle set
			// see if its time to trigger a particle update
			if (SDL_GetTicks() - last_particle_update > PARTICLE_UPDATE_INTERVAL) {
				last_particle_update = SDL_GetTicks();
				particle_update();
			}
		}

		// check for any events waiting
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
				// key presses are handled in input.c
				case SDL_KEYDOWN:
					input_onKeyDown(event.key.keysym.sym);
					break;
				case LEFT_KEY:
					tetromino_moveLeft(current_tetromino);
					if (grid_checkCollision(grid, current_tetromino)) {
						tetromino_moveRight(current_tetromino);
					}
					break;
        case RIGHT_KEY:
          tetromino_moveRight(current_tetromino);
          if (grid_checkCollision(grid, current_tetromino)) {
            tetromino_moveLeft(current_tetromino);
          }
          break;
        case DOWN_KEY:
					// uses the key repeat interval to accelerate the tetromino down
          tetromino_moveDown(current_tetromino);
          if (grid_checkCollision(grid, current_tetromino)) {
            tetromino_moveUp(current_tetromino);
					}
					break;
        case UP_KEY:
          // rotate to a new position
          tetromino_setNextPosition(current_tetromino);
          tetromino_setShape(current_tetromino, current_tetromino->type,
            current_tetromino->position);

          // make sure the new position doesn't cause any collisions
          // if it does, reverse the rotation
          if (grid_checkCollision(grid, current_tetromino)) {
            tetromino_setPrevPosition(current_tetromino);
            tetromino_setShape(current_tetromino, current_tetromino->type,
            current_tetromino->position);
          }
          break;
				case SPACE_KEY:
					tetromino_moveDown(current_tetromino);

					// move the tetromino down until it causes a collision
					while (!grid_checkCollision(grid, current_tetromino)) {
						tetromino_moveDown(current_tetromino);
					}
					// once we have a collision, move it back into place
					tetromino_moveUp(current_tetromino);
					break;
				case PAUSE_KEY:
					debug_print("Pausing game");
					game.paused = !game.paused;

					// stop the game timer
					if (game.paused) {
						SDL_RemoveTimer(timer);
						timer = NULL;
					}
					else { // start it again
						timer = SDL_AddTimer(1000, game_updateTime, NULL);
					}
					break;
				case ESCAPE_KEY:
					// pause game updates
					debug_print("Escape key pressed.");
					
					// toggle paused game state if we're in game
					if (grid && current_tetromino) {
						game.paused = !game.paused;
						if (game.paused) { // stop couting time played
							SDL_RemoveTimer(timer);
							timer = NULL;
						}
						// starting timer again, only if we're still in a game
						else if (grid && current_tetromino) { 
							timer = SDL_AddTimer(1000, game_updateTime, NULL);
						}
					}

					// show or hide the menu
					if (grid && current_tetromino) {
						ui_toggleMenuVisible();
					}
					
					// enable ui message pump if its visible
					if (ui_isMenuVisible()) {
						// if we're in game, show in-game menu
						if (grid && current_tetromino) { 
							ui_menuPageSetCurrentById(MENU_IN_GAME);
						}	
						// otherwise show main menu
						else {
							ui_menuPageSetCurrentById(MENU_MAIN);
						}
						SDL_SetEventFilter(ui_handleEvents);
					}
					break;
				case GAME_START_NEW:
					// set some game variables
					game.level = 0;
					game.score = 0;
					game.lines = 0;
					game.paused = 0;

				  // time variables
					game.hours = 0;
					game.minutes = 0;
					game.seconds = 0;

					// create the grid
					grid = grid_createNew(GRID_WIDTH, GRID_HEIGHT);

				  // create the first tetromino
				  current_tetromino = tetromino_createNew();
				  current_tetromino->x = 0;
  				current_tetromino->y = 0;
  				
					// update time
				  SDL_Init(SDL_INIT_TIMER);
				  
					if (timer) {
						SDL_RemoveTimer(timer);
						timer = NULL;
					}

					ui_toggleMenuVisible();
					timer = SDL_AddTimer(1000, game_updateTime, NULL);
					game.paused = 0;
					break;
				case GAME_END: // called by either the menu or game over scenario
					// destroy timer, grid and tetromino
					SDL_RemoveTimer(timer);
					timer = NULL;

					grid_destroy(grid);
					grid = NULL;
					tetromino_destroy(current_tetromino);
					current_tetromino = NULL;

					// show menu if it isn't already visible
					ui_menuPageSetCurrentById(MENU_MAIN);
					if (!ui_isMenuVisible()) {
						SDL_SetEventFilter(ui_handleEvents);
						ui_toggleMenuVisible();
					}
					break;
				case TETROMINO_CREATE:
					// assumes that the old one has already been discarded
					current_tetromino = tetromino_createNew();
			    current_tetromino->x = 0;
			    current_tetromino->y = 0;

					// check if we have an immediate collision (game over)
					if (grid_checkCollision(grid, current_tetromino)) {
						SDL_RemoveTimer(timer);
						timer = NULL;
						
						e.type = GAME_END;
						SDL_PushEvent(&e);
					}
					break;
        case GRID_REMOVE_LINE:
					if (game.show_score_increments) {
          	// animated score increment
						game_showScoreIncrement(event.user.code, (game.level + 1) * 10);
					}

          grid_removeLine(grid, event.user.code);

          // increment number of complete lines
          game.lines += 1;
          // +10 per block and x10 per level
          game.score += (game.level + 1) * 10 * GRID_WIDTH;

          // increment the game level every 10 lines
          previous_level = game.level;
					game.level = game.lines / 10;
					if (previous_level != game.level) {
						game_showLevelIncrement();
					}

          break;
        case GAME_QUIT:
          SDL_RemoveTimer(timer); // stop gameplay timer
          timer = NULL;
					game_shutdown();
            break;
        // unhandled events are ignored
  			default:
  				break;
  		}
    }

		// update the display
		// without this delay gfx card tries to commit suicide by melting
		if (SDL_GetTicks() - last_render > 3) {
			display_update();
			last_render= SDL_GetTicks();
		}
	}
}
Ejemplo n.º 3
0
int
main(int argc, char *argv[])
{
    int i, desired;
    SDL_TimerID t1, t2, t3;
    Uint64 start, now;

    if (SDL_Init(SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    /* Start the timer */
    desired = 0;
    if (argv[1]) {
        desired = atoi(argv[1]);
    }
    if (desired == 0) {
        desired = DEFAULT_RESOLUTION;
    }
    SDL_SetTimer(desired, ticktock);

    /* Wait 10 seconds */
    printf("Waiting 10 seconds\n");
    SDL_Delay(10 * 1000);

    /* Stop the timer */
    SDL_SetTimer(0, NULL);

    /* Print the results */
    if (ticks) {
        fprintf(stderr,
                "Timer resolution: desired = %d ms, actual = %f ms\n",
                desired, (double) (10 * 1000) / ticks);
    }

    /* Test multiple timers */
    printf("Testing multiple timers...\n");
    t1 = SDL_AddTimer(100, callback, (void *) 1);
    if (!t1)
        fprintf(stderr, "Could not create timer 1: %s\n", SDL_GetError());
    t2 = SDL_AddTimer(50, callback, (void *) 2);
    if (!t2)
        fprintf(stderr, "Could not create timer 2: %s\n", SDL_GetError());
    t3 = SDL_AddTimer(233, callback, (void *) 3);
    if (!t3)
        fprintf(stderr, "Could not create timer 3: %s\n", SDL_GetError());

    /* Wait 10 seconds */
    printf("Waiting 10 seconds\n");
    SDL_Delay(10 * 1000);

    printf("Removing timer 1 and waiting 5 more seconds\n");
    SDL_RemoveTimer(t1);

    SDL_Delay(5 * 1000);

    SDL_RemoveTimer(t2);
    SDL_RemoveTimer(t3);

    start = SDL_GetPerformanceCounter();
    for (i = 0; i < 1000000; ++i) {
        ticktock(0);
    }
    now = SDL_GetPerformanceCounter();
    printf("1 million iterations of ticktock took %f ms\n", (double)((now - start)*1000) / SDL_GetPerformanceFrequency());

    SDL_Quit();
    return (0);
}
/* schedule a video refresh in 'delay' ms */
static void schedule_refresh(VideoState *is, int delay) {
  SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
}
Ejemplo n.º 5
0
int main(int argc, const char * argv[]) {
    
    SDL_Surface *ecran = NULL, *zozor = NULL;
    SDL_Rect positionZozor;
    SDL_Event event;
    SDL_TimerID timer;
    char continuer = 1;
    
    char versLaDroite = 1, versLeBas = 1;
    
    char pause = 0;
    
    int tempsPrecedent = 0, tempsActuel = 0;
    
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
    
    timer = SDL_AddTimer(30, bougerZozor, &positionZozor);
    
    ecran = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    SDL_WM_SetCaption("Gestion du temps en SDL", NULL);
    
    zozor = SDL_LoadBMP("zozor.bmp");
    SDL_SetColorKey(zozor, SDL_SRCCOLORKEY, SDL_MapRGB(zozor->format, 0, 0, 255));
    
    positionZozor.x = ecran->w / 2 - zozor->w / 2;
    positionZozor.y = ecran->h / 2 - zozor->h / 2;
    
    SDL_EnableKeyRepeat(10, 10);
    
    while (continuer) {
        
        SDL_PollEvent(&event);
        
        switch (event.type) {
            case SDL_QUIT:
                continuer = 0;
                break;
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym) {
                    case SDLK_p:
                        pause = !pause;
                        break;
                    case SDLK_ESCAPE:
                        continuer = 0;
                        break;
                    default:
                        break;
                }
                break;
        }
        
        tempsActuel = SDL_GetTicks();
        
        if (tempsActuel - tempsPrecedent > TIMER)
        {
            if (!pause) {
                if (positionZozor.x + zozor->w == ecran->w) {
                    versLaDroite = 0;
                }else if (positionZozor.x == 0) {
                    versLaDroite = 1;
                }
                
                if (positionZozor.y + zozor->h == ecran->h) {
                    versLeBas = 0;
                } else if (positionZozor.y == 0) {
                    versLeBas = 1;
                }
                
                if (versLaDroite) {
                    positionZozor.x++;
                } else {
                    positionZozor.x--;
                }
                
                if (versLeBas) {
                    positionZozor.y++;
                } else {
                    positionZozor.y--;
                }
            }
            
            tempsPrecedent = tempsActuel;
        }
        else
        {
            SDL_Delay(TIMER - (tempsActuel - tempsPrecedent));
        }
        
        SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
        SDL_BlitSurface(zozor, NULL, ecran, &positionZozor);
        SDL_Flip(ecran);
        
    }
    
    SDL_RemoveTimer(timer);
    SDL_FreeSurface(zozor);
    SDL_Quit();
    
    return EXIT_SUCCESS;
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
	// Variables
	SDL_Surface *ecran = NULL,*texte=NULL, *imgFond = NULL, *imgCar = NULL, *tileset = NULL, *imgTrain = NULL, *menutrain=NULL,*bouton1=NULL,*bouton0=NULL,*bouton2=NULL;
	SDL_Rect position_texte_menu;
	SDL_Event event;//variable event
	T_VOIT car[NBCARMAX], cartmp;
	T_BOUTON bout[8];
	int continuer;
	int menucontinuer;
	int nbVoitures;
	int flag;
	int flag1;
	flag=0;
	flag1=0;
	int flag2;
	flag2=0;
	int transparence;
	int i;
	int j;
	int u;

    int tabbouton[8];
    int positionsourisx;
    int positionsourisy;
	// Variables du Timer
	SDL_TimerID idTimerTrain, idTimerCar;
	int periode;
	int tmp;
    tmp=0;
	// initialisation
	continuer = 1;
	periode = 10;

	setParamVoiture(&car[0],1,358,0);		// car[0] -> le train
	affichageParamVoiture(car[0]);						// le train
	nbVoitures = 1;

	tileset = SDL_LoadBMP("route.bmp");

	//initialisation fmod
	FMOD_SYSTEM *system;
    FMOD_System_Create(&system);
    FMOD_System_Init(system, 2, FMOD_INIT_NORMAL, NULL);
    FMOD_SOUND *circulation = NULL,*train = NULL,*menu=NULL,*defilement=NULL;
    FMOD_System_CreateSound(system, "circulation.wav", FMOD_CREATESAMPLE, 0, &circulation);
    FMOD_System_CreateSound(system, "train.wav", FMOD_CREATESAMPLE, 0, &train);
    FMOD_System_CreateSound(system, "menu.mid", FMOD_CREATESAMPLE, 0, &menu);
    FMOD_System_CreateSound(system, "defilement.wav", FMOD_CREATESAMPLE, 0, &defilement);

	// SDL init
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
	idTimerTrain = SDL_AddTimer(periode,actualisePosTrain,&car[0]);
	idTimerCar = SDL_AddTimer(periode,actualisePosVoitures,car);
	ecran = SDL_SetVideoMode(LARGEUR_FENETRE, HAUTEUR_FENETRE, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
	SDL_WM_SetCaption("Premiere collision de vehicules ...", NULL);
	imgCar = SDL_LoadBMP("voiture.bmp");
	imgTrain = SDL_LoadBMP("train.bmp");
	menutrain = SDL_LoadBMP("mapmenu.bmp");
	bouton1 = SDL_LoadBMP("boutonappuyer.bmp");
	bouton2 = SDL_LoadBMP("boutonselectionner.bmp");
    bouton0 = SDL_LoadBMP("bouton.bmp");
    SDL_SetColorKey(bouton0, SDL_SRCCOLORKEY, SDL_MapRGB(bouton0->format, 255, 255, 255));
//



    TTF_Init();
    TTF_Font *police = NULL;
    SDL_Color couleurNoire = {0, 0, 0};
    police = TTF_OpenFont("airwaves.ttf", 50);
    position_texte_menu.x = 500;
    position_texte_menu.y = 500;


     for(i=0;i<8;i++)
       {
        setParambouton(&bout[i],0, 50,37+64*i);
       }

for (transparence = 0 ; transparence <= 255 ;transparence++)
{
    SDL_SetAlpha(menutrain, SDL_SRCALPHA,transparence);
    SDL_BlitSurface(menutrain, NULL, ecran, NULL);
    SDL_Flip(ecran);
}


 //FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, menu, 0, NULL);
       for(i=0;i<8;i++)
       {
           if(i==0)
           {
             for(j=0;j<485;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           SDL_BlitSurface(bouton0, NULL, ecran, &bout[i].pos);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
           if(i==1)
           {
             for(j=0;j<421;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
                if(i==2)
           {
             for(j=0;j<357;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
           if(i==3)
           {
             for(j=0;j<295;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
           if(i==4)
           {
             for(j=0;j<233;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
           if(i==5)
           {
             for(j=0;j<171;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
            if(i==6)
           {
             for(j=0;j<109;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }
           if(i==7)
           {
             for(j=0;j<47;j=j+5)
           {
           setParambouton(&bout[i],0, 50,j);
           SDL_BlitSurface(menutrain, NULL, ecran, NULL);
           for(u=0;u<=i;u++)
           {
            SDL_BlitSurface(bouton0, NULL, ecran, &bout[u].pos);
           }
           SDL_Flip(ecran);
           }
           }

       }


	while (menucontinuer)
{
    SDL_BlitSurface(menutrain, NULL, ecran, NULL);
    SDL_EnableKeyRepeat(10, 10);//repetition
    SDL_PollEvent(&event);
    switch(event.type)
    {
        case SDL_QUIT:
            menucontinuer = 0;
            break;

        case SDL_KEYDOWN:
        switch (event.key.keysym.sym)
        {
            case SDLK_ESCAPE:
                menucontinuer = 0;
                break;
        }
          break;
        case SDL_MOUSEMOTION:
          {
              for(i=0;i<8;i++)
                    {
                if ((event.motion.x>POSITION_TOUCHE_MENU_X)&&(event.motion.x<(POSITION_TOUCHE_MENU_X+LARGEUR_TOUCHE_MENU))&&(event.motion.y>(POSITION_TOUCHE_MENU_Y+i*62))&&(event.motion.y<((POSITION_TOUCHE_MENU_Y+i*62)+HAUTEUR_TOUCHE_MENU)))
                    bout[i].etat=1;
                else
                    bout[i].etat=0;
                    }
           }
        break;
    }

    for(i=0;i<8;i++)
 {
     if(bout[i].etat==0)
     {
         if(bout[tmp].etat==0)
         {
           flag2=0;
         }
      SDL_BlitSurface(bouton0, NULL, ecran, &bout[7-i].pos);
     }
     else
     {
         if(flag2==0)
         {
             tmp=i;
             flag2=1;
             FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, defilement, 0, NULL);
         }
         if(bout[0].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "1 :QUITTER", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[1].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "2 :LANCER", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[2].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "3 :TEMPS", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[3].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "4 : MUSIQUE", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[4].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "5 : FONCTIONS", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[5].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "6 :INITIALISER", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[6].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "7 :REGLAGES", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }
         if(bout[7].etat==1)
         {
         texte = TTF_RenderText_Blended(police, "8 :PARAMETRES", couleurNoire);
         SDL_BlitSurface(texte, NULL, ecran, &position_texte_menu); /* Blit du texte */
         }


         SDL_BlitSurface(bouton2, NULL, ecran, &bout[7-i].pos);
     }

 }


	       SDL_Flip(ecran);
}
	afficherMapEtTrain(ecran,tileset,table,LARGEUR_FENETRE/LARGEUR_TILE,HAUTEUR_FENETRE/HAUTEUR_TILE);
	SDL_BlitSurface(imgTrain, NULL, ecran, &car[0].pos);		// le train (actualise son affichage)
	SDL_Flip(ecran);

	while (continuer) {
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
				case SDL_QUIT:
					continuer = 0;
					break;
			}
		}

		if(nbVoitures<NBCARMAX) {
			cartmp = genereVoiture();
			if(PresenceVoituresEnPosNulle(car,nbVoitures,cartmp.pos.y) == 0) {
				car[nbVoitures] = cartmp;
				nbVoitures++;
			}
		}

       if(testDuPassageDuTrain(&car[0])==1)
        {
            if(flag==0)
            {
             flag=1;
             FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, train, 0, NULL);
            }
            flag1=0;
        	car[0].etat = 1;	// declenche un feu rouge pour les voitures
        }
        else
        {
            flag=0;
            car[0].etat = 0;
            if (flag1==0)
            {
              flag1=1;
              FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, circulation, 0, NULL);
            }

        }

		afficherMapEtTrain(ecran,tileset,table,LARGEUR_FENETRE/LARGEUR_TILE,HAUTEUR_FENETRE/HAUTEUR_TILE);
		afficherFeuRouge(ecran,tileset,table,LARGEUR_FENETRE/LARGEUR_TILE,HAUTEUR_FENETRE/HAUTEUR_TILE,car[0].etat);
		afficherVoitures(car,nbVoitures,imgCar,ecran);

		SDL_BlitSurface(imgTrain, NULL, ecran, &car[0].pos);		// le train (actualise son affichage)
		SDL_Flip(ecran);
	}
    FMOD_Sound_Release(circulation);
	FMOD_Sound_Release(train);
    FMOD_System_Close(system);//fermeture
    FMOD_System_Release(system);//li
	SDL_FreeSurface(imgFond); /* On libère la surface */
    TTF_CloseFont(police);
    TTF_Quit();
 	SDL_Quit();
	return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
int main(int argc,char* argv[])
{
  SDL_Surface *screen;
  SDL_Surface *ball_bmp;

  struct ball red_ball, blue_ball;

  SDL_TimerID timer, timer2;

  int done;

  /*The following code does the initialization for Audio and Video*/
  int i_error=SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER );

  /*If initialization is unsuccessful, then quit */
  if(i_error==-1)
    exit(1);

  atexit(SDL_Quit);

  /*   Initialize the display in a 640x480 8-bit palettized mode,
   *   requesting a software surface
   *                                    */

  screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);

  if ( screen == NULL )
  {
    fprintf(stderr, "Couldn't set 640x480x8 video mode: %sn",SDL_GetError());
    exit(1);
  }

  /* Load the BMP file into a surface */
  red_ball.ball_bmp = SDL_LoadBMP("ball.bmp");
  if (red_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball.bmp", SDL_GetError());
    exit(1);
  }

  /* Load the BMP file into a surface */
  blue_ball.ball_bmp = SDL_LoadBMP("ball2.bmp");
  if (blue_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball2.bmp", SDL_GetError());
    exit(1);
  }


  /*
   * Palettized screen modes will have a default palette (a standard
   * 8*8*4 colour cube), but if the image is palettized as well we can
   * use that palette for a nicer colour matching.
   * */
			         
  if (red_ball.ball_bmp->format->palette && screen->format->palette) {
    SDL_SetColors(screen, ball_bmp->format->palette->colors, 0, ball_bmp->format->palette->ncolors);
  }

  /* Blit onto the screen surface */
  if(SDL_BlitSurface(red_ball.ball_bmp, NULL, screen, NULL) < 0)
    fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  if(SDL_BlitSurface(blue_ball.ball_bmp, NULL, screen, NULL) < 0)
      fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  SDL_UpdateRect(screen, 0, 0, red_ball.ball_bmp->w, red_ball.ball_bmp->h);

  //This could be put in an init function:
  red_ball.startx=0; red_ball.starty=0; red_ball.destx=0; red_ball.desty=0;
  red_ball.x = (float)red_ball.startx; red_ball.y = (float)red_ball.starty;
  red_ball.dx = 0.0; red_ball.dy = 0.0;
  red_ball.screen = screen;

  blue_ball.startx=0; blue_ball.starty=0; blue_ball.destx=0; blue_ball.desty=0;
  blue_ball.x = (float)blue_ball.startx; blue_ball.y = (float)blue_ball.starty;
  blue_ball.dx = 0.0; blue_ball.dy = 0.0;
  blue_ball.screen = screen;

  timer = SDL_AddTimer(20, move_ball, &red_ball);
  SDL_Delay(10);
  timer2 = SDL_AddTimer(20, move_ball, &blue_ball);

  //printf("So far.\n");

  /*Handle the keyboards events here. Catch the SDL_Quit event to exit*/
  done = 0;
  while (!done)
  {
    SDL_Event event;

    /* Check for events */
    while (SDL_PollEvent (&event))
    {
      switch (event.type)
      {
        case SDL_KEYDOWN:
	  break;

        case SDL_MOUSEBUTTONDOWN: 
	{
          switch(event.button.button) 
	  {
	    case SDL_BUTTON_LEFT: 
	    {
	      
              red_ball.destx = event.button.x;
	      red_ball.desty = event.button.y;

	      red_ball.dx = (red_ball.destx - red_ball.x)/50.0;
	      red_ball.dy = (red_ball.desty - red_ball.y)/50.0;

	      break;
	    }

	    case SDL_BUTTON_RIGHT:
	    {
              blue_ball.destx = event.button.x;
	      blue_ball.desty = event.button.y;

	      blue_ball.dx = (blue_ball.destx - blue_ball.x)/50.0;
	      blue_ball.dy = (blue_ball.desty - blue_ball.y)/50.0;

	      break;
	    }

	  }
	}
	break;

	case SDL_QUIT:
	  done = 1;
	  break;

	default:
	  break;

      }
    } 
  }

  /* Free the allocated surface*/
  SDL_FreeSurface(red_ball.ball_bmp);
  SDL_FreeSurface(blue_ball.ball_bmp);

}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
	SDL_Surface *screen;
	SDL_Event event;
	PopplerDocument *document;
	GError *error;
	const char *pdf_file;
	gchar *absolute, *uri;
	int page_num = 1, num_pages;
	cairo_t *cr;
	double width, height;
	float ofs;
	PopplerPage *page;
	SDL_TimerID t = 0;
	SDL_Surface *pg_sf;
	SDL_Surface *n1, *n2, *n1l, *n2l;
	SDL_Surface **preld_sf = NULL;
	SDL_Surface *src_sf = NULL;
	int prerender = 1;

	if (argc < 2) {
		printf("Usage: %s input_file.pdf (pagenum)\n",argv[0]);
		return 0;
	}

	pdf_file = argv[1];
	if (argc > 2)
		page_num = atoi(argv[2]);
	g_type_init();
	error = NULL;

	n1 = IMG_Load("1_32.png");
	n2 = IMG_Load("2_32.png");

	if (g_path_is_absolute(pdf_file)) {
		absolute = g_strdup(pdf_file);
	} else {
		gchar *dir = g_get_current_dir();
		absolute = g_build_filename(dir, pdf_file, (gchar *) 0);
		free(dir);
	}

	uri = g_filename_to_uri(absolute, NULL, &error);
	free(absolute);
	if (uri == NULL) {
		printf("%s\n", error->message);
		return 1;
	}

	document = poppler_document_new_from_file(uri, NULL, &error);
	if (document == NULL) {
		printf("%s\n", error->message);
		return 1;
	}

	num_pages = poppler_document_get_n_pages(document);
	if (page_num < 1 || page_num > num_pages) {
		printf("page must be between 1 and %d\n", num_pages);
		return 1;
	}

	page = poppler_document_get_page(document, 0);
	if (page == NULL) {
		printf("poppler fail: page not found\n");
		return 1;
	}

	/* Initialize SDL, open a screen */
	screen = init_screen(1024, 768, 32);

	n1l = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_SRCALPHA,
				   screen->w,
				   32,
				   32,
				   0xff000000,
				   0x00ff0000, 0x0000ff00, 0x000000ff);

	n2l = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_SRCALPHA,
				   screen->w,
				   32,
				   32,
				   0xff000000,
				   0x00ff0000, 0x0000ff00, 0x000000ff);

	make_nyans(n1l, n1);
	make_nyans(n2l, n2);

	pg_sf = SDL_CreateRGBSurface(SDL_HWSURFACE | 0,
				     screen->w,
				     screen->h,
				     32,
				     CAIROSDL_RMASK,
				     CAIROSDL_GMASK, CAIROSDL_BMASK, 0);

	cr = cairosdl_create(pg_sf);

	poppler_page_get_size(page, &width, &height);
	g_object_unref(page);

	cairo_scale(cr, screen->w / width, screen->h / height);
	draw_page(pg_sf, cr, document, page_num);
	SDL_BlitSurface(pg_sf, NULL, screen, NULL);
	SDL_Flip(screen);

	if (prerender) {
		int i;
		preld_sf = malloc(sizeof(SDL_Surface *) * num_pages);
		for (i = 0; i < num_pages; i++) {
			preld_sf[i] = SDL_CreateRGBSurface(SDL_HWSURFACE | 0,
							   screen->w,
							   screen->h,
							   32,
							   CAIROSDL_RMASK,
							   CAIROSDL_GMASK,
							   CAIROSDL_BMASK, 0);
			draw_page(pg_sf, cr, document, i + 1);
			SDL_BlitSurface(pg_sf, NULL, preld_sf[i], NULL);
		}
	}

	while (SDL_WaitEvent(&event)) {
		int new_page = 0;
		switch (event.type) {
		case SDL_KEYDOWN:
			if (event.key.keysym.sym == SDLK_ESCAPE) {
				goto done;
			} else if (event.key.keysym.sym == SDLK_SPACE) {
				new_page = 1;
				++page_num;
			} else if (event.key.keysym.sym == SDLK_RIGHT) {
				new_page = 1;
				++page_num;
			} else if (event.key.keysym.sym == SDLK_LEFT) {
				new_page = 1;
				--page_num;
			} else if (event.key.keysym.sym == SDLK_PAGEUP) {
				new_page = 1;
				--page_num;
			} else if (event.key.keysym.sym == SDLK_PAGEDOWN) {
				new_page = 1;
				++page_num;
			}

			if (new_page) {
				SDL_Rect sr, sd;
				float x;

				SDL_RemoveTimer(t);

				if (page_num > num_pages)
					page_num = num_pages;
				if (page_num < 1)
					page_num = 1;

				src_sf = pg_sf;
				if (!prerender)
					draw_page(pg_sf, cr, document,
						  page_num);
				else {
					src_sf = preld_sf[page_num - 1];
				}

				SDL_BlitSurface(src_sf, NULL, screen, NULL);
				
				ofs = num_pages - page_num;
				ofs /= num_pages;
				x = n1l->w;
				x *= ofs;
				sr.x = x;
				sr.w = n1l->w - x;
				sr.h = n1l->h;
				sr.y = 0;
#ifndef NYAN_TOP
				sd.y = screen->h - n1l->h;
#else
				sd.y = 0;
#endif
				sd.w = sr.w;
				sd.x = 0;
				sd.h = sr.h;
				SDL_BlitSurface(page_num & 1 ? n1l : n2l, &sr,
						screen, &sd);
				SDL_Flip(screen);
				t = SDL_AddTimer(1000, timer_cb, NULL);
			}
			break;

		case SDL_QUIT:
			goto done;

		case SDL_USEREVENT:
			SDL_BlitSurface(src_sf, NULL, screen, NULL);
			SDL_Flip(screen);
			break;

		default:
			break;
		}
	}

 done:
	SDL_FreeSurface(screen);
	SDL_Quit();
	return 0;
}
Ejemplo n.º 9
0
	bool SDLApplication::Update () {
		
		SDL_Event event;
		event.type = -1;
		
		#if (!defined (IPHONE) && !defined (EMSCRIPTEN))
		
		if (active && (firstTime || WaitEvent (&event))) {
			
			firstTime = false;
			
			HandleEvent (&event);
			event.type = -1;
			if (!active)
				return active;
			
		#endif
			
			while (SDL_PollEvent (&event)) {
				
				HandleEvent (&event);
				event.type = -1;
				if (!active)
					return active;
				
			}
			
			currentUpdate = SDL_GetTicks ();
			
		#if defined (IPHONE)
			
			if (currentUpdate >= nextUpdate) {
				
				event.type = SDL_USEREVENT;
				HandleEvent (&event);
				event.type = -1;
				
			}
		
		#elif defined (EMSCRIPTEN)
			
			event.type = SDL_USEREVENT;
			HandleEvent (&event);
			event.type = -1;
		
		#else
			
			if (currentUpdate >= nextUpdate) {
				
				SDL_RemoveTimer (timerID);
				OnTimer (0, 0);
				
			} else if (!timerActive) {
				
				timerActive = true;
				timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0);
				
			}
			
		}
		
		#endif
		
		return active;
		
	}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	srandom(time(0) * getpid());
	int done;
		
	SDL_Event event;
	if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",
			SDL_GetError());
		exit(1);
	}	
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); 
	screen=SDL_SetVideoMode(screen_width,screen_height, 16, SDL_OPENGL | SDL_RESIZABLE);
		if (screen == NULL) {
		fprintf(stderr, "Couldn't set 800x600x%i video mode: %s\n",
						16, SDL_GetError());
		SDL_Quit();
		exit(2);
	}

	glEnable( GL_TEXTURE_2D );
	glViewport( 0, 0, screen_width, screen_height );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho(0.0f, screen_width, 0.0f, screen_height, -1.0f, 1.0f);
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
	
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);							// Enable Blending
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);		
	
	SDL_GL_SwapBuffers();
			
	addtimers(500,84000);

	unsigned int mousex;
	unsigned int mousey;

	
	TTF_Init(); 
	
	TTF_Font* font = TTF_OpenFont("tower.app/Contents/Resources/" "Vera.ttf", 12);  // FIXME: make this global
	if (font == NULL){
		printf("Unable to load font, exiting!\n");
		exit(1);
	}
	
	
	Globals *g = new Globals();
	g->screen_width = screen_width;
	g->screen_height = screen_height;
	
	g->font = font;
	
	textureManager *tm = new textureManager();
	g->tm = tm;
	GameTime *gt = new GameTime();
	g->gt = gt;
	
	tm->loadAll();
	
	g->bgim = tm->textures["buildingsbg"];
	
	bgdraw *bg = new bgdraw(g);
	floormanager *fm = new floormanager();
	fgdraw *fg = new fgdraw(g,fm);
	menudraw *mg = new menudraw(g);
	
	//////////////////////////////////////////////////////
	
	fm->build_floor(0,10,40);
	fm->build_floor(1,12,38);
	fm->build_floor(2,14,36);
	fm->changeFloorLeft(1, 11);
		
	office *of = new office(11,1,tm,gt);
	fm->addBuilding(1, of);
	of->occupied = true;
	office *of2 = new office(20,1,tm,gt);
	fm->addBuilding(1, of2);
	
	//////////////////////////////////////////////////////
	
	done = 0;
	while ( !done ) {

		/* Check for events */
		while ( SDL_PollEvent(&event) ) {
			switch (event.type) {
				case SDL_MOUSEMOTION:
					mousex = event.motion.x;
					mousey = event.motion.y;
					break;
				case SDL_USEREVENT:
					if(event.type==SDL_USEREVENT) {
						glClear( GL_COLOR_BUFFER_BIT );
						
						bg->drawBG();
						fg->drawFG();
						mg->drawMenu();
						
						SDL_GL_SwapBuffers();
						Uint32 time = 50;
						timer1 = SDL_AddTimer(time, game_event_push, NULL);
					}
					break;
				case (SDL_USEREVENT+1):
					if(event.type==(SDL_USEREVENT+1)) {
//						timer2 = SDL_AddTimer(84000, rent_event_push, 0);
					}
					break;
				case SDL_MOUSEBUTTONDOWN:
			//			toolLayerClicked(event.button.x,event.button.y);
					break;
				case SDL_MOUSEBUTTONUP:
						//toolLayerUnClicked(event.button.x,event.button.y);
					break;
				case SDL_VIDEORESIZE:
					screen_width = event.resize.w;
					screen_height = event.resize.h;
					
					/*screen=SDL_SetVideoMode(screen_width,screen_height, 16, SDL_OPENGL | SDL_RESIZABLE);
					if (screen == NULL) {
						fprintf(stderr,"Unable to grab surface after resize event: %s\n",SDL_GetError());
						exit(1);
					}*/
						

					glOrtho(0.0f, 1000, 1000, 0.0f, -1.0f, 1.0f);
					glViewport( 0, 0, screen_width, screen_height );
					glLoadIdentity();
					break;
				case SDL_KEYDOWN:
					switch(event.key.keysym.sym){
						case SDLK_q:
							removetimers();
							SDL_Quit();
							break;
						case SDLK_UP:
							g->y -= 10;
							glViewport( 0+g->x, 0+g->y, screen_width, screen_height );
							glLoadIdentity();
							break;
						case SDLK_DOWN:
							g->y += 10;
							glViewport( 0+g->x, 0+g->y, screen_width, screen_height );
							glLoadIdentity();
							break;
						case SDLK_LEFT:
							g->x += 10;
							glViewport( 0+g->x, 0+g->y, screen_width, screen_height );
							glLoadIdentity();

							break;
						case SDLK_RIGHT:
							g->x -= 10;
							glViewport( 0+g->x, 0+g->y, screen_width, screen_height );
							glLoadIdentity();

							break;
						default:
							break;
					}
					break;
				case SDL_QUIT:
					puts("Quitting");
					removetimers();
					done = 1;
					break;
				default:
					break;
			}
		}
	}
	
	/* Clean up the SDL library */
	puts("reached SDL_QUIT");
	SDL_Quit();
	return(0);
}
Ejemplo n.º 11
0
int main (int argc, char *argv[])
{
	SDL_Surface *screen;
	int before = 0;
	int delta = 0;

	if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
		fprintf (stderr, "Failed to init SDL: %s\n", SDL_GetError ());
		return -1;
	}
	atexit (SDL_Quit);

	PDL_Init (0);
	atexit (PDL_Quit);

	screen = SDL_SetVideoMode (0, 0, 0, SDL_SWSURFACE);
	if (!screen) {
		fprintf (stderr, "Failed to set video mode: %s\n", SDL_GetError ());
		return -1;
	}

	SDL_Event event;
	while (true) {
		if (paused) {
			//switch to WaitEvent on pause because it blocks
			SDL_WaitEvent (&event);
			if (event.type == SDL_ACTIVEEVENT && event.active.gain == 1 && event.active.state & SDL_APPACTIVE) {
				paused = false;
				continue;
			}

			//while not active the OS may ask us to draw anyway, don't ignore it
			if (event.type == SDL_VIDEOEXPOSE) {
				draw_frame (screen);
			}
		}
		else {
			before = SDL_GetTicks ();

			while (SDL_PollEvent (&event)) {
				process_event (event);
			}

			draw_frame (screen);

			//we don't want to draw too fast, limit framerate
			delta = SDL_GetTicks () - before;
			while (delta < TICKS_PER_FRAME) {
				//we setup a timer that sends a user (custom) event
				SDL_TimerID timer = SDL_AddTimer (TICKS_PER_FRAME - delta, limiter, NULL);

				//clear the event type and wait for another event
				event.type = -1;
				SDL_WaitEvent (&event);

				//if it wasn't the user event process it and loop
				SDL_RemoveTimer (timer);

				if (event.type != SDL_USEREVENT) {
					process_event (event);

					//some time has passed, reset delta
					delta = SDL_GetTicks () - before;
				}
				else {
					break;
				}
			}
			printf ("FPS: %d\n", 1000 / (SDL_GetTicks () - before));
		}
	}
	return 0;
}
Ejemplo n.º 12
0
void addtimers(unsigned int timer1_time, unsigned int timer2_time) {
	//timer2 = SDL_AddTimer(timer2_time, rent_event_push, 0); // 84000
	timer1 = SDL_AddTimer(timebase, game_event_push, 0);
}
Ejemplo n.º 13
0
/**
 * Setup SDL audio, video and window subsystems.
 */
void
av_setup(void)
{
#ifdef PACKAGE_BUILD
    std::string title(PACKAGE_NAME " " PACKAGE_VERSION " build " PACKAGE_BUILD);
#else
    std::string title(PACKAGE_STRING);
#endif


    display::graphics.create(title, (options.want_fullscreen == 1));


#ifdef SET_SDL_ICON
    char *icon_path;

    if ((icon_path = locate_file("moon_32x32.bmp", FT_IMAGE))) {
        SDL_Surface *icon = SDL_LoadBMP(icon_path);

        if (icon != NULL) {
            SDL_WM_SetIcon(icon, NULL);
        } else {
            INFO2("setting icon failed: %s\n", SDL_GetError());
        }

        free(icon_path);
    }

#endif


    fade_info.step = 1;
    fade_info.steps = 1;
    do_fading = 1;

    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,
                        SDL_DEFAULT_REPEAT_INTERVAL);

    if (have_audio) {
        int i = 0;

        audio_desired.freq = 11025;
        audio_desired.format = AUDIO_S16SYS;
        audio_desired.channels = 1;
        /* audio was unresponsive on win32 so let's use shorter buffer */
        audio_desired.samples = 2048;   /* was 8192 */
        audio_desired.callback = audio_callback;

        /* initialize audio channels */
        for (i = 0; i < AV_NUM_CHANNELS; ++i) {
            Channels[i].volume = AV_MAX_VOLUME;
            Channels[i].mute = 0;
            Channels[i].chunk = NULL;
            Channels[i].chunk_tailp = &Channels[i].chunk;
            Channels[i].offset = 0;
        }

        /* we don't care what we got, library will convert for us */
        if (SDL_OpenAudio(&audio_desired, NULL) < 0) {
            ERROR2("SDL_OpenAudio error: %s", SDL_GetError());
            NOTICE1("disabling audio");
            have_audio = 0;
        } else {
            SDL_PauseAudio(0);
        }
    }

    SDL_AddTimer(30, sdl_timer_callback, NULL);
}
Ejemplo n.º 14
0
Client::Client(const Options &options):
    mOptions(options),
    mGame(0),
    mCurrentDialog(0),
    mQuitDialog(0),
    mDesktop(0),
    mSetupButton(0),
    mState(STATE_CHOOSE_SERVER),
    mOldState(STATE_START),
    mStateAfterOkDialog(mState),
    mIcon(0),
    mLogicCounterId(0),
    mSecondsCounterId(0),
    mLimitFps(false)
{
    assert(!mInstance);
    mInstance = this;

    logger = new Logger;

    // Set default values for configuration files
    branding.setDefaultValues(getBrandingDefaults());
    paths.setDefaultValues(getPathsDefaults());
    config.setDefaultValues(getConfigDefaults());

    // Load branding information
    if (!options.brandingPath.empty())
    {
        branding.init(options.brandingPath);
    }

    initRootDir();
    initHomeDir();
    initConfiguration();

    chatLogger = new ChatLogger;
    if (options.chatLogDir.empty())
        chatLogger->setLogDir(mLocalDataDir + std::string("/logs/"));
    else
        chatLogger->setLogDir(options.chatLogDir);

    // Configure logger
    logger->setLogFile(mLocalDataDir + std::string("/mana.log"));
    logger->setLogToStandardOut(config.getBoolValue("logToStandardOut"));

    // Log the mana version
    logger->log("Mana %s", FULL_VERSION);

    initScreenshotDir();

    // Initialize SDL
    logger->log("Initializing SDL...");
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
    {
        logger->error(strprintf("Could not initialize SDL: %s",
                      SDL_GetError()));
    }
    atexit(SDL_Quit);

    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    SDL_WM_SetCaption(branding.getValue("appName", "Mana").c_str(), NULL);

    ResourceManager *resman = ResourceManager::getInstance();

    if (!resman->setWriteDir(mLocalDataDir))
    {
        logger->error(strprintf("%s couldn't be set as home directory! "
                                "Exiting.", mLocalDataDir.c_str()));
    }

    Image::SDLsetEnableAlphaCache(config.getValue("alphaCache", true));

#if defined __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path,
                                          PATH_MAX))
    {
        fprintf(stderr, "Can't find Resources directory\n");
    }
    CFRelease(resourcesURL);
    strncat(path, "/data", PATH_MAX - 1);
    resman->addToSearchPath(path, false);
    mPackageDir = path;
#else
    resman->addToSearchPath(PKG_DATADIR "data", false);
    mPackageDir = PKG_DATADIR "data";
#endif

    resman->addToSearchPath("data", false);

    // Add branding/data to PhysFS search path
    if (!options.brandingPath.empty())
    {
        std::string path = options.brandingPath;

        // Strip blah.mana from the path
#ifdef _WIN32
        int loc1 = path.find_last_of('/');
        int loc2 = path.find_last_of('\\');
        int loc = std::max(loc1, loc2);
#else
        int loc = path.find_last_of('/');
#endif
        if (loc > 0)
            resman->addToSearchPath(path.substr(0, loc + 1) + "data", false);
    }

    // Add the main data directories to our PhysicsFS search path
    if (!options.dataPath.empty())
        resman->addToSearchPath(options.dataPath, false);

    // Add the local data directory to PhysicsFS search path
    resman->addToSearchPath(mLocalDataDir, false);

    std::string iconFile = branding.getValue("appIcon", "icons/mana");
#ifdef _WIN32
    iconFile += ".ico";
#else
    iconFile += ".png";
#endif
    iconFile = resman->getPath(iconFile);
    logger->log("Loading icon from file: %s", iconFile.c_str());
#ifdef _WIN32
    static SDL_SysWMinfo pInfo;
    SDL_GetWMInfo(&pInfo);
    // Attempt to load icon from .ico file
    HICON icon = (HICON) LoadImage(NULL,
                                   iconFile.c_str(),
                                   IMAGE_ICON, 64, 64, LR_LOADFROMFILE);
    // If it's failing, we load the default resource file.
    if (!icon)
        icon = LoadIcon(GetModuleHandle(NULL), "A");

    if (icon)
        SetClassLong(pInfo.window, GCL_HICON, (LONG) icon);
#else
    mIcon = IMG_Load(iconFile.c_str());
    if (mIcon)
    {
        SDL_SetAlpha(mIcon, SDL_SRCALPHA, SDL_ALPHA_OPAQUE);
        SDL_WM_SetIcon(mIcon, NULL);
    }
#endif

    bool useOpenGL = !mOptions.noOpenGL && (config.getValue("opengl", 1) == 1);

    // Set up the transparency option for low CPU when not using OpenGL.
    if (!useOpenGL && (config.getValue("disableTransparency", 0) == 1))
        Image::SDLdisableTransparency();

#ifdef USE_OPENGL

    // Setup image loading for the right image format
    Image::setLoadAsOpenGL(useOpenGL);

    // Create the graphics context
    graphics = useOpenGL ? new OpenGLGraphics : new Graphics;
#else
    // Create the graphics context
    graphics = new Graphics;
#endif

    const int width = config.getIntValue("screenwidth");
    const int height = config.getIntValue("screenheight");
    const int bpp = 0;
    const bool fullscreen = config.getBoolValue("screen");
    const bool hwaccel = config.getBoolValue("hwaccel");

    // Try to set the desired video mode
    if (!graphics->setVideoMode(width, height, bpp, fullscreen, hwaccel))
    {
        logger->error(strprintf("Couldn't set %dx%dx%d video mode: %s",
            width, height, bpp, SDL_GetError()));
    }

    // Initialize for drawing
    graphics->_beginDraw();

    Theme::prepareThemePath();

    // Initialize the item and emote shortcuts.
    itemShortcut = new ItemShortcut;
    emoteShortcut = new EmoteShortcut;

    gui = new Gui(graphics);

    // Initialize sound engine
    try
    {
        if (config.getBoolValue("sound"))
            sound.init();

        sound.setSfxVolume(config.getIntValue("sfxVolume"));
        sound.setNotificationsVolume(config.getIntValue("notificationsVolume"));
        sound.setMusicVolume(config.getIntValue("musicVolume"));
    }
    catch (const char *err)
    {
        mState = STATE_ERROR;
        errorMessage = err;
        logger->log("Warning: %s", err);
    }

    // Initialize keyboard
    keyboard.init();

    // Initialise player relations
    player_relations.init();

    userPalette = new UserPalette;
    setupWindow = new Setup;

    sound.playMusic(branding.getStringValue("loginMusic"));

    // Initialize default server
    mCurrentServer.hostname = options.serverName;
    mCurrentServer.port = options.serverPort;
    loginData.username = options.username;
    loginData.password = options.password;
    loginData.remember = config.getBoolValue("remember");
    loginData.registerLogin = false;

    if (mCurrentServer.hostname.empty())
        mCurrentServer.hostname = branding.getValue("defaultServer","").c_str();

    if (mCurrentServer.port == 0)
    {
        mCurrentServer.port = (short) branding.getValue("defaultPort",
                                                                  DEFAULT_PORT);
        mCurrentServer.type = ServerInfo::parseType(
                           branding.getValue("defaultServerType", "tmwathena"));
    }

    if (chatLogger)
        chatLogger->setServerName(mCurrentServer.hostname);

    if (loginData.username.empty() && loginData.remember)
        loginData.username = config.getStringValue("username");

    if (mState != STATE_ERROR)
        mState = STATE_CHOOSE_SERVER;

    // Initialize logic and seconds counters
    tick_time = 0;
    mLogicCounterId = SDL_AddTimer(MILLISECONDS_IN_A_TICK, nextTick, NULL);
    mSecondsCounterId = SDL_AddTimer(1000, nextSecond, NULL);

    // Initialize frame limiting
    SDL_initFramerate(&mFpsManager);

    listen(Event::ConfigChannel);

    //TODO: fix having to fake a option changed event
    Event fakeevent(Event::ConfigOptionChanged);
    fakeevent.setString("option", "fpslimit");
    event(Event::ConfigChannel, fakeevent);

    // Initialize PlayerInfo
    PlayerInfo::init();
}
Ejemplo n.º 15
0
static int l_mainloop(lua_State *L)
{
    luaL_checktype(L, 1, LUA_TTHREAD);
    lua_State *dispatcher = lua_tothread(L, 1);

    fps_ctrl *fps_control = (fps_ctrl*)lua_touserdata(L, luaT_upvalueindex(1));
    SDL_TimerID timer = SDL_AddTimer(30, timer_frame_callback, nullptr);
    SDL_Event e;

    while(SDL_WaitEvent(&e) != 0)
    {
        bool do_frame = false;
        bool do_timer = false;
        do
        {
            int nargs;
            switch(e.type)
            {
            case SDL_QUIT:
                goto leave_loop;
            case SDL_KEYDOWN:
                lua_pushliteral(dispatcher, "keydown");
                lua_pushstring(dispatcher, SDL_GetKeyName(e.key.keysym.sym));
                l_push_modifiers_table(dispatcher, e.key.keysym.mod);
                lua_pushboolean(dispatcher, e.key.repeat != 0);
                nargs = 4;
                break;
            case SDL_KEYUP:
                lua_pushliteral(dispatcher, "keyup");
                lua_pushstring(dispatcher, SDL_GetKeyName(e.key.keysym.sym));
                nargs = 2;
                break;
            case SDL_TEXTINPUT:
                lua_pushliteral(dispatcher, "textinput");
                lua_pushstring(dispatcher, e.text.text);
                nargs = 2;
                break;
            case SDL_TEXTEDITING:
                lua_pushliteral(dispatcher, "textediting");
                lua_pushstring(dispatcher, e.edit.text);
                lua_pushinteger(dispatcher, e.edit.start);
                lua_pushinteger(dispatcher, e.edit.length);
                nargs = 4;
                break;
            case SDL_MOUSEBUTTONDOWN:
                lua_pushliteral(dispatcher, "buttondown");
                lua_pushinteger(dispatcher, e.button.button);
                lua_pushinteger(dispatcher, e.button.x);
                lua_pushinteger(dispatcher, e.button.y);
                nargs = 4;
                break;
            case SDL_MOUSEBUTTONUP:
                lua_pushliteral(dispatcher, "buttonup");
                lua_pushinteger(dispatcher, e.button.button);
                lua_pushinteger(dispatcher, e.button.x);
                lua_pushinteger(dispatcher, e.button.y);
                nargs = 4;
                break;
            case SDL_MOUSEWHEEL:
                lua_pushliteral(dispatcher, "mousewheel");
                lua_pushinteger(dispatcher, e.wheel.x);
                lua_pushinteger(dispatcher, e.wheel.y);
                nargs = 3;
                break;
            case SDL_MOUSEMOTION:
                lua_pushliteral(dispatcher, "motion");
                lua_pushinteger(dispatcher, e.motion.x);
                lua_pushinteger(dispatcher, e.motion.y);
                lua_pushinteger(dispatcher, e.motion.xrel);
                lua_pushinteger(dispatcher, e.motion.yrel);
                nargs = 5;
                break;
            case SDL_WINDOWEVENT:
                switch (e.window.event) {
                    case SDL_WINDOWEVENT_FOCUS_GAINED:
                        lua_pushliteral(dispatcher, "active");
                        lua_pushinteger(dispatcher, 1);
                        nargs = 2;
                        break;
                    case SDL_WINDOWEVENT_FOCUS_LOST:
                        lua_pushliteral(dispatcher, "active");
                        lua_pushinteger(dispatcher, 0);
                        nargs = 2;
                        break;
                    default:
                        nargs = 0;
                        break;
                }
                break;
            case SDL_USEREVENT_MUSIC_OVER:
                lua_pushliteral(dispatcher, "music_over");
                nargs = 1;
                break;
            case SDL_USEREVENT_CPCALL:
                if(luaT_cpcall(L, (lua_CFunction)e.user.data1, e.user.data2))
                {
                    SDL_RemoveTimer(timer);
                    lua_pushliteral(L, "callback");
                    return 2;
                }
                nargs = 0;
                break;
            case SDL_USEREVENT_TICK:
                do_timer = true;
                nargs = 0;
                break;
            case SDL_USEREVENT_MOVIE_OVER:
                lua_pushliteral(dispatcher, "movie_over");
                nargs = 1;
                break;
            case SDL_USEREVENT_SOUND_OVER:
                lua_pushliteral(dispatcher, "sound_over");
                lua_pushinteger(dispatcher, *(static_cast<int*>(e.user.data1)));
                nargs = 2;
                break;
            default:
                nargs = 0;
                break;
            }
            if(nargs != 0)
            {
                if(luaT_resume(dispatcher, dispatcher, nargs) != LUA_YIELD)
                {
                    goto leave_loop;
                }
                do_frame = do_frame || (lua_toboolean(dispatcher, 1) != 0);
                lua_settop(dispatcher, 0);
            }
        } while(SDL_PollEvent(&e) != 0);
        if(do_timer)
        {
            lua_pushliteral(dispatcher, "timer");
            if(luaT_resume(dispatcher, dispatcher, 1) != LUA_YIELD)
            {
                break;
            }
            do_frame = do_frame || (lua_toboolean(dispatcher, 1) != 0);
            lua_settop(dispatcher, 0);
        }
        if(do_frame || !fps_control->limit_fps)
        {
            do
            {
                if(fps_control->track_fps)
                {
                    fps_control->count_frame();
                }
                lua_pushliteral(dispatcher, "frame");
                if(luaT_resume(dispatcher, dispatcher, 1) != LUA_YIELD)
                {
                    goto leave_loop;
                }
                lua_settop(dispatcher, 0);
            } while(fps_control->limit_fps == false && SDL_PollEvent(nullptr) == 0);
        }

        // No events pending - a good time to do a bit of garbage collection
        lua_gc(L, LUA_GCSTEP, 2);
    }

leave_loop:
    SDL_RemoveTimer(timer);
    int n = lua_gettop(dispatcher);
    if(lua_status(dispatcher) >= LUA_ERRRUN)
    {
        n = 1;
    }
    lua_checkstack(L, n);
    lua_xmove(dispatcher, L, n);
    return n;
}
Ejemplo n.º 16
0
// Initializes timers
void Application::initTimers() {
    // Creates a timer to send a move event every 60 ms    
    animateTimer = SDL_AddTimer(20, genericTimer, &timerId);
}
/**
 * Allows an event to be delayed a certain amount of time.
 *
 * @note the delay is the minimum time, after the time has passed the event
 * will be pushed in the SDL event queue, so it might delay more.
 *
 * @param event                   The event to delay.
 * @param delay                   The number of ms to delay the event.
 */
static void delay_event(const SDL_Event& event, const Uint32 delay)
{
	SDL_AddTimer(delay, delay_event_callback, new SDL_Event(event));
}
Ejemplo n.º 18
0
/**
 * Setup SDL audio, video and window subsystems.
 */
void
av_setup(void)
{
	unsigned video_flags = SDL_SWSURFACE;

#ifndef CONFIG_MACOSX
	char *icon_path = NULL;
#endif

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
	{
		CRITICAL2("SDL_Init error: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	atexit(SDL_Quit);

	if (options.want_audio)
	{
#ifdef CONFIG_WIN32
		/*
		 * default direct-audio-something has got unreasonably long audio buffers,
		 * but if user knows what he's doing then no problemo...
		 */
		if (!SDL_getenv("SDL_AUDIODRIVER"))
		{
			INFO1("fixing WIN32 audio driver setup");
			SDL_putenv("SDL_AUDIODRIVER=waveout");
		}
		/*
		 * also some sources mention that on win audio needs to be initialised
		 * together with video. Maybe, it works for me as it is now.
		 */
#endif
		if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
		{
			ERROR2("audio initialization failed: %s", SDL_GetError());
		}
		else
		{
			INFO1("audio subsystem initialized");
			have_audio = 1;
		}
	}
	else
		NOTICE1("no audio");

	if (options.want_fullscreen)
	{
		video_flags |= SDL_FULLSCREEN;
		NOTICE1("fullscreen mode enabled");
	}

#ifndef CONFIG_MACOSX
	if ((icon_path = locate_file("moon_32x32.bmp", FT_IMAGE)))
	{
		SDL_Surface *icon = SDL_LoadBMP(icon_path);

		if (icon != NULL)
			SDL_WM_SetIcon(icon, NULL);
		else
			INFO2("setting icon failed: %s\n", SDL_GetError());
		free(icon_path);
	}
#endif

#ifdef PACKAGE_BUILD
	SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION
			" build " PACKAGE_BUILD, NULL);
#else
	SDL_WM_SetCaption(PACKAGE_STRING, NULL);
#endif

	if ((display = SDL_SetVideoMode(MAX_X * 2, MAX_Y * 2, 24, video_flags))
			== NULL)
	{
		CRITICAL2("SDL_SetVideoMode failed: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	screen = xcalloc(MAX_X * MAX_Y, 1);
	screen_surf = SDL_CreateRGBSurfaceFrom(screen, MAX_X, MAX_Y, 8, MAX_X,
			0, 0, 0, 0);
	if (!screen_surf)
	{
		CRITICAL2("can't create screen surface: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	screen_surf2x = SDL_CreateRGBSurface(SDL_SWSURFACE, MAX_X * 2, MAX_Y * 2,
			8, ~0, ~0, ~0, 0);
	if (!screen_surf2x)
	{
		CRITICAL2("can't create screen_2x surface: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* XXX: Hardcoded video width & height */
	video_overlay = SDL_CreateYUVOverlay(160, 100, SDL_YV12_OVERLAY, display);
	if (!video_overlay)
	{
		CRITICAL2("can't create video_overlay: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	news_overlay = SDL_CreateYUVOverlay(312, 106, SDL_YV12_OVERLAY, display);
	/* XXX: Hardcoded video width & height */
	if (!news_overlay)
	{
		CRITICAL2("can't create news_overlay: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	fade_info.step = 1;
	fade_info.steps = 1;
	do_fading = 1;

	alloc_dirty_tree();

	SDL_EnableUNICODE(1);
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,
		SDL_DEFAULT_REPEAT_INTERVAL);

	if (have_audio)
	{
		int i = 0;

		audio_desired.freq = 11025;
		audio_desired.format = AUDIO_S16SYS;
		audio_desired.channels = 1;
		/* audio was unresponsive on win32 so let's use shorter buffer */
		audio_desired.samples = 2048;	/* was 8192 */
		audio_desired.callback = audio_callback;

		/* initialize audio channels */
		for (i = 0; i < AV_NUM_CHANNELS; ++i)
		{
			Channels[i].volume = AV_MAX_VOLUME;
			Channels[i].mute = 0;
			Channels[i].chunk = NULL;
			Channels[i].chunk_tailp = &Channels[i].chunk;
			Channels[i].offset = 0;
		}

		/* we don't care what we got, library will convert for us */
		if (SDL_OpenAudio(&audio_desired, NULL) < 0)
		{
			ERROR2("SDL_OpenAudio error: %s", SDL_GetError());
			NOTICE1("disabling audio");
			have_audio = 0;
		}
		else
			SDL_PauseAudio(0);
	}

	SDL_AddTimer(30, sdl_timer_callback, NULL);
}
Ejemplo n.º 19
0
void SDLTimerService::TriggerCallback(int msec,timerCallback cb) {
	SDL_AddTimer(msec,SDLTriggerCallback,(void *)cb);
}
Ejemplo n.º 20
0
int main( int argc, char* args[] )
{
    SDL_Color BACKGROUND_COLOR  = SDL_Color();  BACKGROUND_COLOR.r  = 0;    BACKGROUND_COLOR.g  = 0;    BACKGROUND_COLOR.b  = 0;     BACKGROUND_COLOR.a = 255;
    SDL_Color HUNTER_COLOR      = SDL_Color();  HUNTER_COLOR.r      = 255;  HUNTER_COLOR.g      = 0;    HUNTER_COLOR.b      = 0;     HUNTER_COLOR.a     = 255;
    SDL_Color BOUND_COLOR       = SDL_Color();  BOUND_COLOR.r       = 0;    BOUND_COLOR.g       = 255;  BOUND_COLOR.b       = 0;    BOUND_COLOR.a       = 255;
    SDL_Color PREY_COLOR        = SDL_Color();  PREY_COLOR.r        = 0;    PREY_COLOR.g        = 0;    PREY_COLOR.b        = 255;  PREY_COLOR.a        = 255;
    
    
    // Init GUI
    SDL_Window *screen = NULL;
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) {
        std::cout << "Error on SDL_Init:" << std::endl << SDL_GetError() << std::endl;
        return 1;
    }
    
    screen = SDL_CreateWindow(WINDOW_NAME, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
    if( screen == NULL ) {
        std::cout << "Error on SDL_CreateWindow:" << std::endl << SDL_GetError() << std::endl;
        return 1;
    }
    
    SDL_Renderer* bgRenderer = NULL;
    bgRenderer =  SDL_CreateRenderer( screen, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if( bgRenderer == NULL ) {
        std::cout << "Error on SDL_CreateRenderer:" << std::endl << SDL_GetError() << std::endl;
        return 1;
    }

    
    // Define QLAgent
    QLAgent<QLAction,QLState>::qlt table;
    if(std::ifstream(FILENAME)) { loadQLTable(table,FILENAME); }
    const std::vector<QLAction> actionVec { Entity::UP, Entity::DOWN, Entity::LEFT, Entity::RIGHT, Entity::IDLE };
    QLAgent<QLAction,QLState> preyAgent = QLAgent<QLAction,QLState>([&actionVec](QLState u){return actionVec;} , table);
    preyAgent.setQLParameters(CAP, LR, DF, GVR);

    // Inizialization
    SDL_Rect bounds = SDL_Rect();
    bounds.x = BOUND_MIN_X;
    bounds.y = BOUND_MIN_Y;
    bounds.w = BOUND_MAX_X - BOUND_MIN_X;
    bounds.h = BOUND_MAX_Y - BOUND_MIN_Y;
    
    Entity hunter   = Entity( HUNTER_WIDTH, HUNTER_HEIGHT,  HUNTER_SPEED,   HUNTER_START_X, HUNTER_START_Y, bounds, HUNTER_COLOR );
    Entity prey     = Entity( PREY_WIDTH,   PREY_HEIGHT,    PREY_SPEED,     PREY_START_X,   PREY_START_Y,   bounds, PREY_COLOR );
    
    preyAgent.setCurrentState(dataToQLState(hunter,prey));
    
    // Render
    clr(bgRenderer,BACKGROUND_COLOR);
    renderRect(bounds, BOUND_COLOR, bgRenderer, false);
    renderEntity(hunter, bgRenderer);
    renderEntity(prey, bgRenderer);
    SDL_RenderPresent(bgRenderer);



    // TIMERS
    SDL_TimerID renderTimerId = SDL_AddTimer(TIME_GAP_RENDER, render_callback, NULL);
    if( renderTimerId == 0 ) {
        std::cout << "Error on SDL_AddTimer:" << std::endl << SDL_GetError() << std::endl;
        return 1;
    }
    
    SDL_TimerID movementTimerId = SDL_AddTimer(TIME_GAP_MOVEMENT, movement_callback, NULL);
    if( movementTimerId == 0 ) {
        std::cout << "Error on SDL_AddTimer:" << std::endl << SDL_GetError() << std::endl;
        return 1;
    }


    // main cycle
    //// structure to read user events
    SDL_Event event;
    //// to check when the key is pressed or released
    bool isKeyPressed[4] = { false, false, false, false };
    
    bool quit = false;
    int matchCounter = 0;
    while( quit == false ) {
        
        bool matchIsOver = false;
        matchCounter++;
        // int moveCounter = 0;
        // int succesCounter = 0;
        while(!matchIsOver) {
        
            // event handling
            while( SDL_PollEvent( &event ) ) {
                switch( event.type ) {
                    case SDL_QUIT:
                        quit = true;
                    break;
                    case SDL_KEYDOWN:
                        // Keyboard input handling - keydown
                        checkKeyPressed( event.key.keysym.sym, isKeyPressed, true );
                    break;
                    case SDL_KEYUP:
                        // Keyboard input handling - keyup
                        checkKeyPressed( event.key.keysym.sym, isKeyPressed, false );
                    break;
                    case SDL_USEREVENT:

                        switch(event.user.code) {
                            case RENDER_CB:
                                // Render
                                clr(bgRenderer,BACKGROUND_COLOR);
                                renderRect(bounds, BOUND_COLOR, bgRenderer, false);
                                renderEntity(hunter, bgRenderer);
                                renderEntity(prey, bgRenderer);
                                SDL_RenderPresent(bgRenderer);
                            break;
                            case MOVEMENT_CB:
                                // Entities movement
                                hunter.move( actHunter(hunter,prey) );
                                //userMovement(prey, isKeyPressed);

                                prey.move( preyAgent.chooseAction() );

                                // check contact
                                if( checkContact( hunter, prey ) ) {
                                    hunter.reset();
                                    prey.reset();
                                    preyAgent.update(dataToQLState(hunter,prey), CATCH_REWARD);
                                    matchIsOver = true;
                                }
                                else {
                                    preyAgent.update(dataToQLState(hunter,prey), SURVIVE_REWARD);
                                }

                            break;
                        }


                    break;
                    default:
                    break;
                }
            }

            
            // 
// moveCounter++;
//
//             hunter.move( actHunter(hunter,prey) );
//             //userMovement(prey, isKeyPressed);
//
//             prey.move( preyAgent.chooseAction() );
//
//             // check contact
//             if( checkContact( hunter, prey ) ) {
//                 hunter.reset();
//                 prey.reset();
//                 preyAgent.update(dataToQLState(hunter,prey), CATCH_REWARD);
//                 matchIsOver = true;
//             }
//                else {
//                    preyAgent.update(dataToQLState(hunter,prey), SURVIVE_REWARD);
//                }
//
//             if(matchCounter%10000 == 0) { std::cout << matchCounter << std::endl; }
//             if(matchCounter%100000 == 0) { quit = true; }
//             if(moveCounter == 1000) { succesCounter++; matchIsOver = true; }
//             if(succesCounter == 100) { std::cout << "SUCCESS!!!" << std::endl; }
                
        }
        
    }
    
    std::cout << "states in table: " << table.size() << std::endl;
    saveQLTable(table,FILENAME);
    SDL_Quit();
    return 0;
}
Ejemplo n.º 21
0
int main(int argc, char* argv[])
{
  std::srand(std::time(0));

  RaiiSdlMain sdlMain;
  Graphics graphics(width, height);

  Physics physics(physWidth, physHeight);

  std::vector<Circle> circles;
  std::vector<b2Body*> boxes;
  std::vector<Flyer> flyers;
  for (int i(0); i<NUM_OF_CIRCLES; ++i)
  {
    int r = std::rand() % 50 + 30;
    int x = width / 2;
    int y = height / 4;

    //circles.push_back(Circle{x, y, r, std::rand() % 30 - 15, std::rand() % 30 - 15, (std::rand() % 0xffffff) << 8});

    boxes.push_back(physics.addBox(Vector(physWidth / 2 + std::rand() % physWidth / 2 - physWidth / 4, physHeight / 2 + std::rand() % physHeight / 2 - physHeight / 4), 1, 1));
    boxes.back()->ApplyForceToCenter(Vector(std::rand() % 1000 - 500, std::rand() % 1000 - 500));
  }

  for (int i(1); i < argc; ++i)
  {
    boxes.push_back(physics.addComplexPolygon(Vector(physWidth / 2 + std::rand() % physWidth / 2 - physWidth / 4, physHeight / 2 + std::rand() % physHeight / 2 - physHeight / 4), readPolygon(argv[i])));
    flyers.push_back(Flyer());
    boxes.back()->SetUserData(&flyers.back());
  }

  SDL_AddTimer(TIMER_INTERVAL, timerTick, 0);

  bool exit(false);
  bool forwardEngine(false);
  bool turnEngine(false);

  SDL_Event event;
  while (!exit && 1 == SDL_WaitEvent(&event))
  {
    ScopedPrinter printer("while (!exit && 1 == SDL_WaitEvent(&event))");
    switch (event.type)
    {
      case SDL_QUIT:
      {
        exit = true;
        break;
      }
      case SDL_USEREVENT:
      {
        if (forwardEngine)
        {
          //boxes.back()->ApplyForceToCenter(rotate(EngineForce, boxes.back()->GetAngle()));
          boxes.back()->ApplyForce(EngineForce, boxes.back()->GetPosition() + rotate(Vector(1.5f, 0.5f), boxes.back()->GetAngle()));
        }
        if (turnEngine)
        {
          boxes.back()->ApplyTorque(1.0f);
        }
        ScopedPrinter printer("case SDL_USEREVENT:");
        draw(graphics, circles, boxes);
        graphics.show();
        move(boxes);
        physics.step();

        timerEventInQueue = false;

        break;
      }
      case SDL_KEYDOWN:
      {
        switch (event.key.keysym.sym)
        {
          case SDLK_UP:
          {
            forwardEngine = true;

            break;
          }
          case SDLK_LEFT:
          {
            turnEngine = true;

            break;
          }
          default: break;
        }

        break;
      }
      case SDL_KEYUP:
      {
        switch (event.key.keysym.sym)
        {
          case SDLK_UP:
          {
            forwardEngine = false;

            break;
          }
          case SDLK_LEFT:
          {
            turnEngine = false;

            break;
          }
          default: break;
        }

        break;
      }
    }
  }
}
Ejemplo n.º 22
0
static bool __init_video(Camera *camera)
{
    assert(camera && "Bad camera pointer.");

    camera->w = 800;
    camera->h = 600;
    camera->bpp = 32;
    camera->move_speed = 4.0;
    camera->mouse_sensitivity = 0.1;
    camera->z = 512;
    camera->vertical_angle = 90.0;
    camera->horizontal_angle = 0.0;
    camera->fov_y = 60.0;

    check(0 == SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER), "Failed to init SDL.", "");
    SDL_WM_SetCaption("morrigan viewer", NULL);
    check(0 == SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16), "Failed to set SDL_GL_DEPTH_SIZE.", "");
    check(0 == SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1), "Failed to set SDL_GL_DOUBLEBUFFER.", "");
    /*
    const SDL_VideoInfo *vi = SDL_GetVideoInfo();
    check(NULL != vi, "SDL_GetVideoInfo() failed.", "");
    w = vi->current_w;
    h = vi->current_h;
    */
    check(NULL != SDL_SetVideoMode(camera->w, camera->h, camera->bpp, SDL_HWSURFACE | SDL_SWSURFACE | SDL_OPENGL), "Failed to set video mode.", "");
    SDL_ShowCursor(SDL_DISABLE);
    check(NULL != (timer_id = SDL_AddTimer(SDL_DEFAULT_REPEAT_INTERVAL, __timer_handler, (void *) TIMER_EVENT_ID)), "Failed to setup timer.", "");
    check(NULL != (tanks_timer_id = SDL_AddTimer(TANKS_POLL_INTERVAL, __timer_handler, (void *) TANKS_TIMER_EVENT_ID)), "Failed to setup tanks timer.", "");

    glLineWidth(1.0);

    glShadeModel(GL_SMOOTH);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glCullFace(GL_FRONT);
    glEnable(GL_DITHER);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_ALPHA_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_LINE_SMOOTH);
    glEnable(GL_POLYGON_SMOOTH);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    glEnable(GL_COLOR_MATERIAL);

    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

    glViewport(0, 0, camera->w, camera->h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    float ratio = (float) camera->w / (float) camera->h;
    gluPerspective(camera->fov_y, ratio, 1, 16384.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glScaled(1.0, 1.0, -1.0);

    SDL_WarpMouse(camera->mouse_prev_x = camera->w / 2,
                  camera->mouse_prev_y = camera->h / 2);
    return true;
    error:
    return false;
}
Ejemplo n.º 23
0
 RedrawTimer(unsigned interval)
     : id(SDL_AddTimer(interval, callback, NULL))
 {
     if(id == NULL) throw SDL_Exception();
 }
Ejemplo n.º 24
0
void AVPlayer::refresh_timer_callback(void* obj, int delay)
{
	/* 타이머 초기화 */
	SDL_AddTimer(delay, refresh_time_static, this);
}
void WindowManager::eventLoop()
{
	// be sure there's at least one observer!
	assert(eventObservers.size() > 0);

	// set two main timers (interval in ms)
	SDL_AddTimer(m_RenderEventInterval, &timerCallbackRenderEvent, NULL);
	SDL_AddTimer(1000, &timerCallbackBOINCUpdateEvent, NULL);

	// events we don't ignore, hence use
	//SDL_EventState(SDL_QUIT, SDL_IGNORE);
	//SDL_EventState(SDL_KEYDOWN, SDL_IGNORE);
	//SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
	//SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE);
	//SDL_EventState(SDL_VIDEORESIZE, SDL_IGNORE);
	//SDL_EventState(SDL_USEREVENT, SDL_IGNORE);

	// events we ignore
	SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
	SDL_EventState(SDL_KEYUP, SDL_IGNORE);
	SDL_EventState(SDL_JOYAXISMOTION, SDL_IGNORE);
	SDL_EventState(SDL_JOYBALLMOTION, SDL_IGNORE);
	SDL_EventState(SDL_JOYHATMOTION, SDL_IGNORE);
	SDL_EventState(SDL_JOYBUTTONDOWN, SDL_IGNORE);
	SDL_EventState(SDL_JOYBUTTONUP, SDL_IGNORE);
	SDL_EventState(SDL_VIDEOEXPOSE, SDL_IGNORE);
	SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);

	SDL_Event event;

	while (SDL_WaitEvent(&event) ) {
		if (event.type == SDL_USEREVENT &&
			event.user.code == RenderEvent) {

#ifdef DEBUG_VALGRIND
			// stop after i iterations when running valgrinded
			static int i = 0;
			if(i < 500) {
				i++;
#endif
				// notify our observers (currently exactly one, hence front())
				eventObservers.front()->render(dtime());
#ifdef DEBUG_VALGRIND
			}
			else {
				if (m_DisplaySurface) SDL_FreeSurface(m_DisplaySurface);
				break;
			}
#endif
		}
		else if (event.type == SDL_USEREVENT &&
				 event.user.code == BOINCUpdateEvent) {

			// notify observers (currently exactly one, hence front()) to fetch a BOINC update
			eventObservers.front()->refreshBOINCInformation();
		}
		else if (m_ScreensaverMode &&
				(event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEBUTTONDOWN ||
				 event.type == SDL_KEYDOWN)) {

			// we're in screensaver mode so exit on user input
			SDL_Quit();
		}
		else if (event.motion.state & (SDL_BUTTON(1) | SDL_BUTTON(3)) &&
				 event.type == SDL_MOUSEMOTION) {

			if (event.motion.state & SDL_BUTTON(1)) {
				// notify our observers (currently exactly one, hence front())
				eventObservers.front()->mouseMoveEvent(
										event.motion.xrel,
										event.motion.yrel,
										AbstractGraphicsEngine::MouseButtonLeft);
			}
			else if (event.motion.state & SDL_BUTTON(3)) {
				// notify our observers (currently exactly one, hence front())
				eventObservers.front()->mouseMoveEvent(
										event.motion.xrel,
										event.motion.yrel,
										AbstractGraphicsEngine::MouseButtonRight);
			}
		}
		else if (event.type == SDL_VIDEORESIZE) {
			m_CurrentWidth = m_WindowedWidth = event.resize.w;
			m_CurrentHeight = m_WindowedHeight = event.resize.h;

			// update video mode
			m_DisplaySurface = SDL_SetVideoMode(
									m_CurrentWidth,
									m_CurrentHeight,
									m_DesktopBitsPerPixel,
									m_VideoModeFlags);

			// notify our observers (currently exactly one, hence front())
			// (windoze needs to be reinitialized instead of just resized, oh well)
			/// \todo Can we determine the host OS? On X11 a resize() is sufficient!
			eventObservers.front()->initialize(m_CurrentWidth, m_CurrentHeight, 0, true);
		}
		else if (event.type == SDL_QUIT ||
				(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {

			// just exit (SDL_FreeSurface is called automatically)
			SDL_Quit();

			break;
		}
		else if (event.type == SDL_KEYDOWN) {
			switch (event.key.keysym.sym) {
				// notify our observers (currently exactly one, hence front())
				case SDLK_s:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyS);
					break;
				case SDLK_c:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyC);
					break;
				case SDLK_o:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyO);
					break;
				case SDLK_x:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyX);
					break;
				case SDLK_p:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyP);
					break;
				case SDLK_r:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyR);
					break;
				case SDLK_g:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyG);
					break;
				case SDLK_a:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyA);
					break;
				case SDLK_i:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyI);
					break;
				case SDLK_l:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyL);
					break;
				case SDLK_m:
					eventObservers.front()->keyboardPressEvent(AbstractGraphicsEngine::KeyM);
					break;
				case SDLK_RETURN:
					toggleFullscreen();
				default:
					break;
			}
		}
	}
}
Ejemplo n.º 26
0
Archivo: main.c Proyecto: tthimm/c_sim
int main(int argc, char *argv[]) {
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) {
		printf("Can't initialize SDL: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	atexit(SDL_Quit);

	SDL_Surface *screen, *text, *save_message;
	SDL_Event event;
	TTF_Font *font;
	int i, done = 0, mouse_x = 0, mouse_y = 0;
	unsigned int frames = SDL_GetTicks() + FLIMIT;
	unsigned int *frame_limit;
	frame_limit = &frames;
	int *mouse_x_ptr, *mouse_y_ptr;
	mouse_x_ptr = &mouse_x;
	mouse_y_ptr = &mouse_y;
	int show_save_msg = 0;

	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_DOUBLEBUF | SDL_HWSURFACE);
	//screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16, SDL_DOUBLEBUF | SDL_FULLSCREEN);
	if(NULL == screen) {
		printf("Can't set video mode: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* set window title */
	SDL_WM_SetCaption("2D SIMULATION", NULL);

	/* disable cursor */
	SDL_ShowCursor(SDL_DISABLE);

	/* load new cursor */
	load_cursor();

	/* load the map and fill tiles array */
	load_map();

	/* load tileset */
	load_tileset();

	/* load player */
	load_player_image();

	/* setup font */
	TTF_Init();
	SDL_Color text_color = {255, 255, 255};
	font = TTF_OpenFont("media/fonts/slkscrb.ttf", 8);

	/* game loop */
	while(!done) {
		while(SDL_PollEvent(&event)) {
			switch(event.type) {
				case SDL_QUIT:
					done = 1;
					break;
				case SAVE_EVENT:
					show_save_msg = 0;
					//printf("SDL_USEREVENT: %i\n", SAVE_EVENT);
					break;
				case SDL_MOUSEMOTION:
					*mouse_x_ptr = event.motion.x;
					*mouse_y_ptr = event.motion.y;
					break;
				case SDL_MOUSEBUTTONDOWN:
					switch(event.button.button) {
						case 1:
							//destroy_block(screen, event.button.x, event.button.y);
							input.mleft = 1;
							break;
						case 3:
							//place_block(event.button.x, event.button.y, &player);
							input.mright = 1;
							break;
						default:
							break;
					}
					break;
				case SDL_MOUSEBUTTONUP:
					switch(event.button.button) {
						/* removed because if player falls down, it deletes always the block below the player */
						case 1:
							input.mleft = 0;
							break;
						case 3:
							input.mright = 0;
							break;
						default:
							break;
					}
					break;

				case SDL_KEYDOWN:
					switch(event.key.keysym.sym) {
						case SDLK_ESCAPE:
							done = 1;
							break;
						case SDLK_a:
							input.left = 1;
							break;
						case SDLK_d:
							input.right = 1;
							break;
						case SDLK_SPACE:
							input.jump = 1;
							break;
						case SDLK_1:
							player.selected = DIRT;
							break;
						case SDLK_2:
							player.selected = GRASS;
							break;
						case SDLK_3:
							player.selected = SAND;
							break;
						case SDLK_4:
							player.selected = ROCK;
							break;
						case SDLK_5:
							player.selected = WATER5;
							break;
						case SDLK_6:
							player.selected = OIL;
							break;
						case SDLK_F12:
							save_map();
							SDL_AddTimer (2000, msg_event, NULL);
							show_save_msg = 1;
							break;
						default:
							break;
					}
					break;
				case SDL_KEYUP:
					switch(event.key.keysym.sym) {
						case SDLK_a:
							input.left = 0;
							break;
						case SDLK_d:
							input.right = 0;
							break;
						default:
							break;
					}
					break;
			}
		}
		move_player(&player); // and camera
		move_sand();
		simulate_water();
		simulate_oil();
		place_and_destroy_blocks(screen, event.button.x, event.button.y, &player);
		//input.mleft = 0; // uncomment for click once to delete one block
		//input.mright = 0; // uncomment for click once to place one block
		draw(screen, mouse_x_ptr, mouse_y_ptr, &player, text, font, text_color, show_save_msg, save_message);

		delay(frame_limit);
		*frame_limit = SDL_GetTicks() + FLIMIT;
	}

	/* free tiles/mass/new_mass array in reverse order */
	for(i = 0; i < map.h; i++) {
		free(map.tiles[i]);
		free(map.water_mass[i]);
		free(map.new_water_mass[i]);
		free(map.oil_mass[i]);
		free(map.new_oil_mass[i]);
	}
	free(map.tiles);
	free(map.water_mass);
	free(map.new_water_mass);
	free(map.oil_mass);
	free(map.new_oil_mass);

	SDL_FreeSurface(tileset);
	SDL_FreeSurface(player_image);
	SDL_FreeSurface(cursor);
	SDL_FreeSurface(text);
	SDL_FreeSurface(save_message);
	return 0;
}
Ejemplo n.º 27
0
int
main(int argc, char *argv[])
{
    int i, desired;
    SDL_TimerID t1, t2, t3;
    Uint32 start32, now32;
    Uint64 start, now;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if (SDL_Init(SDL_INIT_TIMER) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        return (1);
    }

    /* Start the timer */
    desired = 0;
    if (argv[1]) {
        desired = atoi(argv[1]);
    }
    if (desired == 0) {
        desired = DEFAULT_RESOLUTION;
    }
    t1 = SDL_AddTimer(desired, ticktock, NULL);

    /* Wait 10 seconds */
    SDL_Log("Waiting 10 seconds\n");
    SDL_Delay(10 * 1000);

    /* Stop the timer */
    SDL_RemoveTimer(t1);

    /* Print the results */
    if (ticks) {
        SDL_Log("Timer resolution: desired = %d ms, actual = %f ms\n",
                desired, (double) (10 * 1000) / ticks);
    }

    /* Test multiple timers */
    SDL_Log("Testing multiple timers...\n");
    t1 = SDL_AddTimer(100, callback, (void *) 1);
    if (!t1)
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 1: %s\n", SDL_GetError());
    t2 = SDL_AddTimer(50, callback, (void *) 2);
    if (!t2)
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 2: %s\n", SDL_GetError());
    t3 = SDL_AddTimer(233, callback, (void *) 3);
    if (!t3)
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 3: %s\n", SDL_GetError());

    /* Wait 10 seconds */
    SDL_Log("Waiting 10 seconds\n");
    SDL_Delay(10 * 1000);

    SDL_Log("Removing timer 1 and waiting 5 more seconds\n");
    SDL_RemoveTimer(t1);

    SDL_Delay(5 * 1000);

    SDL_RemoveTimer(t2);
    SDL_RemoveTimer(t3);

    start = SDL_GetPerformanceCounter();
    for (i = 0; i < 1000000; ++i) {
        ticktock(0, NULL);
    }
    now = SDL_GetPerformanceCounter();
    SDL_Log("1 million iterations of ticktock took %f ms\n", (double)((now - start)*1000) / SDL_GetPerformanceFrequency());

    SDL_Log("Performance counter frequency: %"SDL_PRIu64"\n", (unsigned long long) SDL_GetPerformanceFrequency());
    start32 = SDL_GetTicks();
    start = SDL_GetPerformanceCounter();
    SDL_Delay(1000);
    now = SDL_GetPerformanceCounter();
    now32 = SDL_GetTicks();
    SDL_Log("Delay 1 second = %d ms in ticks, %f ms according to performance counter\n", (now32-start32), (double)((now - start)*1000) / SDL_GetPerformanceFrequency());

    SDL_Quit();
    return (0);
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
	int desired;
	SDL_TimerID t1, t2, t3;

	if ( SDL_Init(SDL_INIT_TIMER) < 0 ) {
		fprintf(stderr, "Couldn't load SDL: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);

	/* Start the timer */
	desired = 0;
	if ( argv[1] ) {
		desired = atoi(argv[1]);
	}
	if ( desired == 0 ) {
		desired = DEFAULT_RESOLUTION;
	}
	SDL_SetTimer(desired, ticktock);

	/* Wait 10 seconds */
	printf("Waiting 10 seconds\n");
	SDL_Delay(10*1000);

	/* Stop the timer */
	SDL_SetTimer(0, NULL);

	/* Print the results */
	if ( ticks ) {
		fprintf(stderr,
		"Timer resolution: desired = %d ms, actual = %f ms\n",
					desired, (double)(10*1000)/ticks);
	}
	
	/* Test multiple timers */
	printf("Testing multiple timers...\n");
	t1 = SDL_AddTimer(100, callback, (void*)1);
	if(!t1)
	  fprintf(stderr,"Could not create timer 1: %s\n", SDL_GetError());
	t2 = SDL_AddTimer(50, callback, (void*)2);
	if(!t2)
	  fprintf(stderr,"Could not create timer 2: %s\n", SDL_GetError());
	t3 = SDL_AddTimer(233, callback, (void*)3);
	if(!t3)
	  fprintf(stderr,"Could not create timer 3: %s\n", SDL_GetError());
	
	/* Wait 10 seconds */
	printf("Waiting 10 seconds\n");
	SDL_Delay(10*1000);

	printf("Removing timer 1 and waiting 5 more seconds\n");
	SDL_RemoveTimer(t1);

	SDL_Delay(5*1000);

	SDL_RemoveTimer(t2);
	SDL_RemoveTimer(t3);

	return(0);
}
Ejemplo n.º 29
0
int PLATFORM_Keyboard(void)
{
	int shiftctrl = 0;
	SDL_Event event;

#ifdef USE_UI_BASIC_ONSCREEN_KEYBOARD
	if (!atari_screen_backup)
		atari_screen_backup = malloc(Screen_HEIGHT * Screen_WIDTH);
#endif

#if HAVE_WINDOWS_H
	/* Used to delay resize events on Windows 7, see above. */
	enum { RESIZE_INTERVAL = 500 };
	static int resize_delayed = FALSE;
	static int resize_needed = FALSE;
	static int resize_w, resize_h;
#endif /* HAVE_WINDOWS_H */

	/* Very ugly fix for SDL CAPSLOCK brokenness.  This will let the user
	 * press CAPSLOCK and get a brief keypress on the Atari but it is not
	 * possible to emulate holding down CAPSLOCK for longer periods with
	 * the broken SDL*/
	if (lastkey == SDLK_CAPSLOCK) {
		lastkey = SDLK_UNKNOWN;
	   	key_pressed = 0;
 		lastuni = 0;
	}

	if (SDL_PollEvent(&event)) {
		switch (event.type) {
		case SDL_KEYDOWN:
			lastkey = event.key.keysym.sym;
 			lastuni = event.key.keysym.unicode;
			key_pressed = 1;
			break;
		case SDL_KEYUP:
			lastkey = event.key.keysym.sym;
 			lastuni = 0; /* event.key.keysym.unicode is not defined for KEYUP */
			key_pressed = 0;
			/* ugly hack to fix broken SDL CAPSLOCK*/
			/* Because SDL is only sending Keydown and keyup for every change
			 * of state of the CAPSLOCK status, rather than the actual key.*/
			if(lastkey == SDLK_CAPSLOCK) {
				key_pressed = 1;
			}
			break;
		case SDL_VIDEORESIZE:
#if HAVE_WINDOWS_H
			/* Delay resize events on Windows 7, see above. */
			if (resize_delayed) {
				resize_w = event.resize.w;
				resize_h = event.resize.h;
				resize_needed = TRUE;
			} else {
				VIDEOMODE_SetWindowSize(event.resize.w, event.resize.h);
				resize_delayed = TRUE;
				if (SDL_AddTimer(RESIZE_INTERVAL, &ResizeDelayCallback, NULL) == NULL) {
					Log_print("Error: SDL_AddTimer failed: %s", SDL_GetError());
					Log_flushlog();
					exit(-1);
				}
			}
#else
			VIDEOMODE_SetWindowSize(event.resize.w, event.resize.h);
#endif /* HAVE_WINDOWS_H */
			break;
		case SDL_VIDEOEXPOSE:
			/* When window is "uncovered", and we are in the emulator's menu,
			   we need to refresh display manually. */
			PLATFORM_DisplayScreen();
			break;
		case SDL_QUIT:
			return AKEY_EXIT;
			break;
#if HAVE_WINDOWS_H
		case SDL_USEREVENT:
			/* Process delayed video resize on Windows 7, see above. */
			if (event.user.code == USER_EVENT_RESIZE_DELAY) {
				if (resize_needed) {
					SDL_Event events[1];
					resize_needed = FALSE;
					/* If there's a resize event in the queue,
					   wait for it and don't resize now. */
					if (SDL_PeepEvents(events, 1, SDL_PEEKEVENT, SDL_EVENTMASK(SDL_VIDEORESIZE)) != 0)
						resize_delayed = FALSE;
					else {
						VIDEOMODE_SetWindowSize(resize_w, resize_h);
						if (SDL_AddTimer(RESIZE_INTERVAL, &ResizeDelayCallback, NULL) == NULL) {
							Log_print("Error: SDL_AddTimer failed: %s", SDL_GetError());
							Log_flushlog();
							exit(-1);
						}
					}
				} else
					resize_delayed = FALSE;
			}
			break;
#endif /* HAVE_WINDOWS_H */
		}
	}
	else if (!key_pressed)
#ifdef USE_UI_BASIC_ONSCREEN_KEYBOARD
		return SDL_controller_kb();
#else
		return AKEY_NONE;
#endif

	UI_alt_function = -1;
	if (kbhits[SDLK_LALT]) {
		if (key_pressed) {
			switch (lastkey) {
			case SDLK_f:
				key_pressed = 0;
				VIDEOMODE_ToggleWindowed();
				break;
			case SDLK_x:
				if (INPUT_key_shift) {
					key_pressed = 0;
					VIDEOMODE_Toggle80Column();
				}
				break;
			case SDLK_g:
				key_pressed = 0;
				VIDEOMODE_ToggleHorizontalArea();
				break;
			case SDLK_j:
				key_pressed = 0;
				SwapJoysticks();
				break;
			case SDLK_r:
				UI_alt_function = UI_MENU_RUN;
				break;
			case SDLK_y:
				UI_alt_function = UI_MENU_SYSTEM;
				break;
			case SDLK_o:
				UI_alt_function = UI_MENU_SOUND;
				break;
			case SDLK_w:
				UI_alt_function = UI_MENU_SOUND_RECORDING;
				break;
			case SDLK_a:
				UI_alt_function = UI_MENU_ABOUT;
				break;
			case SDLK_s:
				UI_alt_function = UI_MENU_SAVESTATE;
				break;
			case SDLK_d:
				UI_alt_function = UI_MENU_DISK;
				break;
			case SDLK_l:
				UI_alt_function = UI_MENU_LOADSTATE;
				break;
			case SDLK_c:
				UI_alt_function = UI_MENU_CARTRIDGE;
				break;
			case SDLK_t:
				UI_alt_function = UI_MENU_CASSETTE;
				break;
			case SDLK_BACKSLASH:
				return AKEY_PBI_BB_MENU;
			case SDLK_m:
				grab_mouse = !grab_mouse;
				SDL_WM_GrabInput(grab_mouse ? SDL_GRAB_ON : SDL_GRAB_OFF);
				key_pressed = 0;
				break;
			case SDLK_1:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->hue > COLOURS_HUE_MIN)
						Colours_setup->hue -= 0.02;
				} else {
					if (Colours_setup->hue < COLOURS_HUE_MAX)
						Colours_setup->hue += 0.02;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_2:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->saturation > COLOURS_SATURATION_MIN)
						Colours_setup->saturation -= 0.02;
				} else {
					if (Colours_setup->saturation < COLOURS_SATURATION_MAX)
						Colours_setup->saturation += 0.02;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_3:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->contrast > COLOURS_CONTRAST_MIN)
						Colours_setup->contrast -= 0.04;
				} else {
					if (Colours_setup->contrast < COLOURS_CONTRAST_MAX)
					Colours_setup->contrast += 0.04;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_4:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->brightness > COLOURS_BRIGHTNESS_MIN)
						Colours_setup->brightness -= 0.04;
				} else {
					if (Colours_setup->brightness < COLOURS_BRIGHTNESS_MAX)
						Colours_setup->brightness += 0.04;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_5:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->gamma > COLOURS_GAMMA_MIN)
						Colours_setup->gamma -= 0.02;
				} else {
					if (Colours_setup->gamma < COLOURS_GAMMA_MAX)
						Colours_setup->gamma += 0.02;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_6:
				if (kbhits[SDLK_LSHIFT]) {
					if (Colours_setup->color_delay > COLOURS_DELAY_MIN)
						Colours_setup->color_delay -= 0.4;
				} else {
					if (Colours_setup->color_delay < COLOURS_DELAY_MAX)
						Colours_setup->color_delay += 0.4;
				}
				Colours_Update();
				return AKEY_NONE;
			case SDLK_LEFTBRACKET:
				if (kbhits[SDLK_LSHIFT])
					SDL_VIDEO_SetScanlinesPercentage(SDL_VIDEO_scanlines_percentage - 1);
				else
					SDL_VIDEO_SetScanlinesPercentage(SDL_VIDEO_scanlines_percentage + 1);
				return AKEY_NONE;
			default:
				if(FILTER_NTSC_emu != NULL){
					switch(lastkey){
					case SDLK_7:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.sharpness > FILTER_NTSC_SHARPNESS_MIN)
								FILTER_NTSC_setup.sharpness -= 0.02;
						} else {
							if (FILTER_NTSC_setup.sharpness < FILTER_NTSC_SHARPNESS_MAX)
								FILTER_NTSC_setup.sharpness += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_8:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.resolution > FILTER_NTSC_RESOLUTION_MIN)
								FILTER_NTSC_setup.resolution -= 0.02;
						} else {
							if (FILTER_NTSC_setup.resolution < FILTER_NTSC_RESOLUTION_MAX)
								FILTER_NTSC_setup.resolution += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_9:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.artifacts > FILTER_NTSC_ARTIFACTS_MIN)
								FILTER_NTSC_setup.artifacts -= 0.02;
						} else {
							if (FILTER_NTSC_setup.artifacts < FILTER_NTSC_ARTIFACTS_MAX)
								FILTER_NTSC_setup.artifacts += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_0:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.fringing > FILTER_NTSC_FRINGING_MIN)
								FILTER_NTSC_setup.fringing -= 0.02;
						} else {
							if (FILTER_NTSC_setup.fringing < FILTER_NTSC_FRINGING_MAX)
								FILTER_NTSC_setup.fringing += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_MINUS:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.bleed > FILTER_NTSC_BLEED_MIN)
								FILTER_NTSC_setup.bleed -= 0.02;
						} else {
							if (FILTER_NTSC_setup.bleed < FILTER_NTSC_BLEED_MAX)
								FILTER_NTSC_setup.bleed += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_EQUALS:
						if (kbhits[SDLK_LSHIFT]) {
							if (FILTER_NTSC_setup.burst_phase > FILTER_NTSC_BURST_PHASE_MIN)
								FILTER_NTSC_setup.burst_phase -= 0.02;
						} else {
							if (FILTER_NTSC_setup.burst_phase < FILTER_NTSC_BURST_PHASE_MAX)
								FILTER_NTSC_setup.burst_phase += 0.02;
						}
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						return AKEY_NONE;
					case SDLK_RIGHTBRACKET:
						key_pressed = 0;
						FILTER_NTSC_NextPreset();
						FILTER_NTSC_Update(FILTER_NTSC_emu);
						break;
					}
				}
			break;
			}
		}
	}

	/* SHIFT STATE */
	if ((kbhits[SDLK_LSHIFT]) || (kbhits[SDLK_RSHIFT]))
		INPUT_key_shift = 1;
	else
		INPUT_key_shift = 0;

	/* CONTROL STATE */
	if ((kbhits[SDLK_LCTRL]) || (kbhits[SDLK_RCTRL]))
		key_control = 1;
	else
		key_control = 0;

	/*
	if (event.type == 2 || event.type == 3) {
		Log_print("E:%x S:%x C:%x K:%x U:%x M:%x",event.type,INPUT_key_shift,key_control,lastkey,event.key.keysym.unicode,event.key.keysym.mod);
	}
	*/

	/* OPTION / SELECT / START keys */
	INPUT_key_consol = INPUT_CONSOL_NONE;
	if (kbhits[SDLK_F2])
		INPUT_key_consol &= (~INPUT_CONSOL_OPTION);
	if (kbhits[SDLK_F3])
		INPUT_key_consol &= (~INPUT_CONSOL_SELECT);
	if (kbhits[SDLK_F4])
		INPUT_key_consol &= (~INPUT_CONSOL_START);

	if (key_pressed == 0)
		return AKEY_NONE;

	/* Handle movement and special keys. */
	switch (lastkey) {
	case SDLK_F1:
		key_pressed = 0;
		return AKEY_UI;
	case SDLK_F5:
		key_pressed = 0;
		return INPUT_key_shift ? AKEY_COLDSTART : AKEY_WARMSTART;
	case SDLK_F8:
		UI_alt_function = UI_MENU_MONITOR;
		break;
	case SDLK_F9:
		return AKEY_EXIT;
	case SDLK_F10:
		key_pressed = 0;
		return INPUT_key_shift ? AKEY_SCREENSHOT_INTERLACE : AKEY_SCREENSHOT;
	case SDLK_F12:
		key_pressed = 0;
		return AKEY_TURBO;
	}

	if (UI_alt_function != -1) {
		key_pressed = 0;
		return AKEY_UI;
	}

	/* keyboard joysticks: don't pass the keypresses to emulation
	 * as some games pause on a keypress (River Raid, Bruce Lee)
	 */
	if (!UI_is_active && PLATFORM_kbd_joy_0_enabled) {
		if (lastkey == KBD_STICK_0_LEFT || lastkey == KBD_STICK_0_RIGHT ||
			lastkey == KBD_STICK_0_UP || lastkey == KBD_STICK_0_DOWN || lastkey == KBD_TRIG_0) {
			key_pressed = 0;
			return AKEY_NONE;
		}
	}

	if (!UI_is_active && PLATFORM_kbd_joy_1_enabled) {
		if (lastkey == KBD_STICK_1_LEFT || lastkey == KBD_STICK_1_RIGHT ||
			lastkey == KBD_STICK_1_UP || lastkey == KBD_STICK_1_DOWN || lastkey == KBD_TRIG_1) {
			key_pressed = 0;
			return AKEY_NONE;
		}
	}

	if (INPUT_key_shift)
		shiftctrl ^= AKEY_SHFT;

	if (Atari800_machine_type == Atari800_MACHINE_5200 && !UI_is_active) {
		if (lastkey == SDLK_F4)
			return AKEY_5200_START ^ shiftctrl;
		switch (lastuni) {
		case 'p':
			return AKEY_5200_PAUSE ^ shiftctrl;
		case 'r':
			return AKEY_5200_RESET ^ shiftctrl;
		case '0':
			return AKEY_5200_0 ^ shiftctrl;
		case '1':
			return AKEY_5200_1 ^ shiftctrl;
		case '2':
			return AKEY_5200_2 ^ shiftctrl;
		case '3':
			return AKEY_5200_3 ^ shiftctrl;
		case '4':
			return AKEY_5200_4 ^ shiftctrl;
		case '5':
			return AKEY_5200_5 ^ shiftctrl;
		case '6':
			return AKEY_5200_6 ^ shiftctrl;
		case '7':
			return AKEY_5200_7 ^ shiftctrl;
		case '8':
			return AKEY_5200_8 ^ shiftctrl;
		case '9':
			return AKEY_5200_9 ^ shiftctrl;
		case '#':
		case '=':
			return AKEY_5200_HASH ^ shiftctrl;
		case '*':
			return AKEY_5200_ASTERISK ^ shiftctrl;
		}
		return AKEY_NONE;
	}

	if (key_control)
		shiftctrl ^= AKEY_CTRL;

	switch (lastkey) {
	case SDLK_BACKQUOTE: /* fallthrough */
		/* These are the "Windows" keys, but they don't work on Windows*/
	case SDLK_LSUPER:
		return AKEY_ATARI ^ shiftctrl;
	case SDLK_RSUPER:
		if (INPUT_key_shift)
			return AKEY_CAPSLOCK;
		else
			return AKEY_CAPSTOGGLE;
	case SDLK_END:
	case SDLK_F6:
		return AKEY_HELP ^ shiftctrl;
	case SDLK_PAGEDOWN:
		return AKEY_F2 | AKEY_SHFT;
	case SDLK_PAGEUP:
		return AKEY_F1 | AKEY_SHFT;
	case SDLK_HOME:
		return key_control ? AKEY_LESS|shiftctrl : AKEY_CLEAR;
	case SDLK_PAUSE:
	case SDLK_F7:
		return AKEY_BREAK;
	case SDLK_CAPSLOCK:
		if (INPUT_key_shift)
			return AKEY_CAPSLOCK|shiftctrl;
		else
			return AKEY_CAPSTOGGLE|shiftctrl;
	case SDLK_SPACE:
		return AKEY_SPACE ^ shiftctrl;
	case SDLK_BACKSPACE:
		return AKEY_BACKSPACE|shiftctrl;
	case SDLK_RETURN:
		return AKEY_RETURN ^ shiftctrl;
	case SDLK_LEFT:
		return (!UI_is_active && Atari800_f_keys ? AKEY_F3 : (INPUT_key_shift ? AKEY_PLUS : AKEY_LEFT)) ^ shiftctrl;
	case SDLK_RIGHT:
		return (!UI_is_active && Atari800_f_keys ? AKEY_F4 : (INPUT_key_shift ? AKEY_ASTERISK : AKEY_RIGHT)) ^ shiftctrl;
	case SDLK_UP:
		return (!UI_is_active && Atari800_f_keys ? AKEY_F1 : (INPUT_key_shift ? AKEY_MINUS : AKEY_UP)) ^ shiftctrl;
	case SDLK_DOWN:
		return (!UI_is_active && Atari800_f_keys ? AKEY_F2 : (INPUT_key_shift ? AKEY_EQUAL : AKEY_DOWN)) ^ shiftctrl;
	case SDLK_ESCAPE:
		/* Windows takes ctrl+esc and ctrl+shift+esc */
		return AKEY_ESCAPE ^ shiftctrl;
	case SDLK_TAB:
#if HAVE_WINDOWS_H
		/* On Windows, when an SDL window has focus and LAlt+Tab is pressed,
		   a window-switching menu appears, but the LAlt+Tab key sequence is
		   still forwarded to the SDL window. In the effect the user cannot
		   switch with LAlt+Tab without the emulator registering unwanted key
		   presses. On other operating systems (e.g. GNU/Linux/KDE) everything
		   is OK, the key sequence is not registered by the emulator. This
		   hack fixes the behaviour on Windows. */
		if (kbhits[SDLK_LALT]) {
			key_pressed = 0;
			/* 1. In fullscreen software (non-OpenGL) mode, user presses LAlt, then presses Tab.
			      Atari800 window gets minimised and the window-switching menu appears.
			   2. User switches back to Atari800 without releasing LAlt.
			   3. User releases LAlt. Atari800 gets switched back to fullscreen.
			   In the above situation, the emulator would register pressing of LAlt but
			   would not register releasing of the key. It would think that LAlt is still
			   pressed. The hack below fixes the issue by causing SDL to assume LAlt is
			   not pressed. */
#if HAVE_OPENGL
			if (!VIDEOMODE_windowed && !SDL_VIDEO_opengl)
#else
			if (!VIDEOMODE_windowed)
#endif /* HAVE_OPENGL */
				kbhits[SDLK_LALT] = 0;
			return AKEY_NONE;
		}
#endif /* HAVE_WINDOWS_H */
		return AKEY_TAB ^ shiftctrl;
	case SDLK_DELETE:
		if (INPUT_key_shift)
			return AKEY_DELETE_LINE|shiftctrl;
		else
			return AKEY_DELETE_CHAR;
	case SDLK_INSERT:
		if (INPUT_key_shift)
			return AKEY_INSERT_LINE|shiftctrl;
		else
			return AKEY_INSERT_CHAR;
	}
	if (INPUT_cx85) switch (lastkey) {
	case SDLK_KP1:
		return AKEY_CX85_1;
	case SDLK_KP2:
		return AKEY_CX85_2;
	case SDLK_KP3:
		return AKEY_CX85_3;
	case SDLK_KP4:
		return AKEY_CX85_4;
	case SDLK_KP5:
		return AKEY_CX85_5;
	case SDLK_KP6:
		return AKEY_CX85_6;
	case SDLK_KP7:
		return AKEY_CX85_7;
	case SDLK_KP8:
		return AKEY_CX85_8;
	case SDLK_KP9:
		return AKEY_CX85_9;
	case SDLK_KP0:
		return AKEY_CX85_0;
	case SDLK_KP_PERIOD:
		return AKEY_CX85_PERIOD;
	case SDLK_KP_MINUS:
		return AKEY_CX85_MINUS;
	case SDLK_KP_ENTER:
		return AKEY_CX85_PLUS_ENTER;
	case SDLK_KP_DIVIDE:
		return (key_control ? AKEY_CX85_ESCAPE : AKEY_CX85_NO);
	case SDLK_KP_MULTIPLY:
		return AKEY_CX85_DELETE;
	case SDLK_KP_PLUS:
		return AKEY_CX85_YES;
	}

	/* Handle CTRL-0 to CTRL-9 and other control characters */
	if (key_control) {
		switch(lastuni) {
		case '.':
			return AKEY_FULLSTOP|shiftctrl;
		case ',':
			return AKEY_COMMA|shiftctrl;
		case ';':
			return AKEY_SEMICOLON|shiftctrl;
		}
		switch (lastkey) {
		case SDLK_PERIOD:
			return AKEY_FULLSTOP|shiftctrl;
		case SDLK_COMMA:
			return AKEY_COMMA|shiftctrl;
		case SDLK_SEMICOLON:
			return AKEY_SEMICOLON|shiftctrl;
		case SDLK_SLASH:
			return AKEY_SLASH|shiftctrl;
		case SDLK_BACKSLASH:
			/* work-around for Windows */
			return AKEY_ESCAPE|shiftctrl;
		case SDLK_0:
			return AKEY_CTRL_0|shiftctrl;
		case SDLK_1:
			return AKEY_CTRL_1|shiftctrl;
		case SDLK_2:
			return AKEY_CTRL_2|shiftctrl;
		case SDLK_3:
			return AKEY_CTRL_3|shiftctrl;
		case SDLK_4:
			return AKEY_CTRL_4|shiftctrl;
		case SDLK_5:
			return AKEY_CTRL_5|shiftctrl;
		case SDLK_6:
			return AKEY_CTRL_6|shiftctrl;
		case SDLK_7:
			return AKEY_CTRL_7|shiftctrl;
		case SDLK_8:
			return AKEY_CTRL_8|shiftctrl;
		case SDLK_9:
			return AKEY_CTRL_9|shiftctrl;
		}
	}

	/* Host Caps Lock will make lastuni switch case, so prevent this*/
    if(lastuni>='A' && lastuni <= 'Z' && !INPUT_key_shift) lastuni += 0x20;
    if(lastuni>='a' && lastuni <= 'z' && INPUT_key_shift) lastuni -= 0x20;
	/* Uses only UNICODE translation, no shift states (this was added to
	 * support non-US keyboard layouts)*/
	/* input.c takes care of removing invalid shift+control keys */
	switch (lastuni) {
	case 1:
		return AKEY_CTRL_a|shiftctrl;
	case 2:
		return AKEY_CTRL_b|shiftctrl;
	case 3:
		return AKEY_CTRL_c|shiftctrl;
	case 4:
		return AKEY_CTRL_d|shiftctrl;
	case 5:
		return AKEY_CTRL_e|shiftctrl;
	case 6:
		return AKEY_CTRL_f|shiftctrl;
	case 7:
		return AKEY_CTRL_g|shiftctrl;
	case 8:
		return AKEY_CTRL_h|shiftctrl;
	case 9:
		return AKEY_CTRL_i|shiftctrl;
	case 10:
		return AKEY_CTRL_j|shiftctrl;
	case 11:
		return AKEY_CTRL_k|shiftctrl;
	case 12:
		return AKEY_CTRL_l|shiftctrl;
	case 13:
		return AKEY_CTRL_m|shiftctrl;
	case 14:
		return AKEY_CTRL_n|shiftctrl;
	case 15:
		return AKEY_CTRL_o|shiftctrl;
	case 16:
		return AKEY_CTRL_p|shiftctrl;
	case 17:
		return AKEY_CTRL_q|shiftctrl;
	case 18:
		return AKEY_CTRL_r|shiftctrl;
	case 19:
		return AKEY_CTRL_s|shiftctrl;
	case 20:
		return AKEY_CTRL_t|shiftctrl;
	case 21:
		return AKEY_CTRL_u|shiftctrl;
	case 22:
		return AKEY_CTRL_v|shiftctrl;
	case 23:
		return AKEY_CTRL_w|shiftctrl;
	case 24:
		return AKEY_CTRL_x|shiftctrl;
	case 25:
		return AKEY_CTRL_y|shiftctrl;
	case 26:
		return AKEY_CTRL_z|shiftctrl;
	case 'A':
		return AKEY_A;
	case 'B':
		return AKEY_B;
	case 'C':
		return AKEY_C;
	case 'D':
		return AKEY_D;
	case 'E':
		return AKEY_E;
	case 'F':
		return AKEY_F;
	case 'G':
		return AKEY_G;
	case 'H':
		return AKEY_H;
	case 'I':
		return AKEY_I;
	case 'J':
		return AKEY_J;
	case 'K':
		return AKEY_K;
	case 'L':
		return AKEY_L;
	case 'M':
		return AKEY_M;
	case 'N':
		return AKEY_N;
	case 'O':
		return AKEY_O;
	case 'P':
		return AKEY_P;
	case 'Q':
		return AKEY_Q;
	case 'R':
		return AKEY_R;
	case 'S':
		return AKEY_S;
	case 'T':
		return AKEY_T;
	case 'U':
		return AKEY_U;
	case 'V':
		return AKEY_V;
	case 'W':
		return AKEY_W;
	case 'X':
		return AKEY_X;
	case 'Y':
		return AKEY_Y;
	case 'Z':
		return AKEY_Z;
	case ':':
		return AKEY_COLON;
	case '!':
		return AKEY_EXCLAMATION;
	case '@':
		return AKEY_AT;
	case '#':
		return AKEY_HASH;
	case '$':
		return AKEY_DOLLAR;
	case '%':
		return AKEY_PERCENT;
	case '^':
		return AKEY_CARET;
	case '&':
		return AKEY_AMPERSAND;
	case '*':
		return AKEY_ASTERISK;
	case '(':
		return AKEY_PARENLEFT;
	case ')':
		return AKEY_PARENRIGHT;
	case '+':
		return AKEY_PLUS;
	case '_':
		return AKEY_UNDERSCORE;
	case '"':
		return AKEY_DBLQUOTE;
	case '?':
		return AKEY_QUESTION;
	case '<':
		return AKEY_LESS;
	case '>':
		return AKEY_GREATER;
	case 'a':
		return AKEY_a;
	case 'b':
		return AKEY_b;
	case 'c':
		return AKEY_c;
	case 'd':
		return AKEY_d;
	case 'e':
		return AKEY_e;
	case 'f':
		return AKEY_f;
	case 'g':
		return AKEY_g;
	case 'h':
		return AKEY_h;
	case 'i':
		return AKEY_i;
	case 'j':
		return AKEY_j;
	case 'k':
		return AKEY_k;
	case 'l':
		return AKEY_l;
	case 'm':
		return AKEY_m;
	case 'n':
		return AKEY_n;
	case 'o':
		return AKEY_o;
	case 'p':
		return AKEY_p;
	case 'q':
		return AKEY_q;
	case 'r':
		return AKEY_r;
	case 's':
		return AKEY_s;
	case 't':
		return AKEY_t;
	case 'u':
		return AKEY_u;
	case 'v':
		return AKEY_v;
	case 'w':
		return AKEY_w;
	case 'x':
		return AKEY_x;
	case 'y':
		return AKEY_y;
	case 'z':
		return AKEY_z;
	case ';':
		return AKEY_SEMICOLON;
	case '0':
		return AKEY_0;
	case '1':
		return AKEY_1;
	case '2':
		return AKEY_2;
	case '3':
		return AKEY_3;
	case '4':
		return AKEY_4;
	case '5':
		return AKEY_5;
	case '6':
		return AKEY_6;
	case '7':
		return AKEY_7;
	case '8':
		return AKEY_8;
	case '9':
		return AKEY_9;
	case ',':
		return AKEY_COMMA;
	case '.':
		return AKEY_FULLSTOP;
	case '=':
		return AKEY_EQUAL;
	case '-':
		return AKEY_MINUS;
	case '\'':
		return AKEY_QUOTE;
	case '/':
		return AKEY_SLASH;
	case '\\':
		return AKEY_BACKSLASH;
	case '[':
		return AKEY_BRACKETLEFT;
	case ']':
		return AKEY_BRACKETRIGHT;
	case '|':
		return AKEY_BAR;
	}

	return AKEY_NONE;
}
Ejemplo n.º 30
0
signed ODE_Init()
{
	Quit = SDL_FALSE;
	dInitODE2(dInitFlagManualThreadCleanup);
	dSetMessageHandler(Error);
	dSetDebugHandler(Error);
	dSetErrorHandler(Error);

	World = dWorldCreate();
	Space = dHashSpaceCreate(0);
	Group = dJointGroupCreate(0);
	Step = 1.0/50.0;

	lua_getglobal(State, "World");
	int table = lua_gettop(State);

	if (!lua_isnil(State, table))
	{
	 lua_pushnil(State);
	 while (lua_next(State, table))
	 {
		const char *key = lua_tostring(State, -2);
		#define tointeger lua_tointeger(State, -1)
		#define toboolean lua_toboolean(State, -1)
		#define tonumber  lua_tonumber(State, -1)

		if (!SDL_strcasecmp(key, "FPS"))
		{
		 Step = 1.0/tonumber;
		}
		else
		if (!SDL_strcasecmp(key, "ERP"))
		{
		 dWorldSetERP(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CFM"))
		{
		 dWorldSetCFM(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "LINEAR_DAMPING"))
		{
		 dWorldSetLinearDamping(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "LINEAR_DAMPING_THRESHOLD"))
		{
		 dWorldSetLinearDampingThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "ANGULAR_DAMPING"))
		{
		 dWorldSetAngularDamping(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "ANGULAR_DAMPING_THRESHOLD"))
		{
		 dWorldSetAngularDampingThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "MAX_ANGULAR_SPEED"))
		{
		 dWorldSetMaxAngularSpeed(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CONTACT_MAX_CORRECTING_VELOCITY"))
		{
		 dWorldSetContactMaxCorrectingVel(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "CONTACT_SURFACE_LAYER"))
		{
		 dWorldSetContactSurfaceLayer(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE"))
		{
		 dWorldSetAutoDisableFlag(World, toboolean);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_LINEAR_THRESHOLD"))
		{
		 dWorldSetAutoDisableLinearThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_ANGULAR_THRESHOLD"))
		{
		 dWorldSetAutoDisableAngularThreshold(World, tonumber);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_STEPS"))
		{
		 dWorldSetAutoDisableSteps(World, tointeger);
		}
		else
		if (!SDL_strcasecmp(key, "AUTO_DISABLE_TIME"))
		{
		 dWorldSetAutoDisableTime(World, tonumber);
		}
		else
		{
		 SDL_Log("World: %s does not match", key);
		}
		lua_pop(State, 1);
	 }
	}
	lua_pop(State, 1);

	Cond = SDL_CreateCond();
	if (!Cond)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_perror("SDL_CreateCond");
	 return SDL_SetError("cannot create simulation signal");
	}
	Mutex = SDL_CreateMutex();
	if (!Mutex)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_perror("SDL_CreateMutex");
	 return SDL_SetError("cannot create simulation mutex");
	}
	Thread = SDL_CreateThread(SimulationThread, "ODE", NULL);
	if (!Thread)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_DestroyMutex(Mutex);
	 SDL_perror("SDL_CreateThread");
	 return SDL_SetError("cannot create simulation thread");
	}
	TimerID = SDL_AddTimer(Uint32(1000*Step), SimulationTimer, NULL);
	if (!TimerID)
	{
	 dWorldDestroy(World);
	 dSpaceDestroy(Space);
	 dJointGroupDestroy(Group);
	 SDL_DestroyCond(Cond);
	 SDL_DestroyMutex(Mutex);
	 SDL_perror("SDL_AddTimer");
	 return SDL_SetError("cannot create simulation timer");
	}
	return 0;
}