コード例 #1
0
ファイル: main.cpp プロジェクト: ivop/RastaConverter
int main(int argc, char *argv[])
{	
	//////////////////////////////////////////////////////////////////////////
	allegro_init(); // Initialize Allegro
	install_keyboard();
	set_close_button_callback(quit_function);
	FreeImage_Initialise(TRUE);

	create_cycles_table();

	Configuration cfg;
	cfg.Process(argc, argv);

	if (cfg.continue_processing)
	{
		quiet=true;
		rasta.Resume();
		rasta.cfg.continue_processing=true;
		quiet=false;
	}
	else
		rasta.SetConfig(cfg);

	screen_color_depth = desktop_color_depth();
	get_desktop_resolution(&desktop_width,&desktop_height);
	set_color_depth(screen_color_depth);

	if (!rasta.cfg.preprocess_only)
	{
		if (desktop_width>=320*3)
			set_gfx_mode(GFX_AUTODETECT_WINDOWED, 320*3,480,0,0); 
		else
			set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480,0,0); // Change our graphics mode to 640x480

		set_display_switch_mode(SWITCH_BACKGROUND);
		set_close_button_callback(close_button_procedure);

		set_window_title(rasta.cfg.command_line.c_str());
	}
	else
		quiet=true;

	rasta.LoadAtariPalette();

	rasta.LoadInputBitmap();
	if (rasta.ProcessInit())
	{
		rasta.FindBestSolution();
		rasta.SaveBestSolution();
	}
	return 0; // Exit with no errors
}
コード例 #2
0
ファイル: allegro_v.cpp プロジェクト: Ayutac/OpenTTD
const char *VideoDriver_Allegro::Start(const char * const *parm)
{
	if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
		DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
		return "Failed to set up Allegro";
	}
	_allegro_instance_count++;

	install_timer();
	install_mouse();
	install_keyboard();

#if defined _DEBUG
/* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
 * be triggered, so rereplace the signals and make the debugger useful. */
	signal(SIGABRT, NULL);
	signal(SIGSEGV, NULL);
#endif

#if defined(DOS)
	/* Force DOS builds to ALWAYS use full screen as
	 * it can't do windowed. */
	_fullscreen = true;
#endif

	GetVideoModes();
	if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
		return "Failed to set up Allegro video";
	}
	MarkWholeScreenDirty();
	set_close_button_callback(HandleExitGameRequest);

	return NULL;
}
コード例 #3
0
ファイル: main.cpp プロジェクト: VictorLeach96/ChuckieEgg
//Main function
int main(){
	//Allegro init
	allegro_init();
	set_color_depth(32); 
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1280, 960, 0, 0);
	set_window_title("Chuckie Egg");
	srand(time(NULL));

	//Installations
	install_sound(DIGI_AUTODETECT,MIDI_AUTODETECT,0);
	install_timer();
	install_keyboard();
	install_mouse();

	//Close button
    LOCK_FUNCTION(close_button_handler);
    set_close_button_callback(close_button_handler);

	//Show menu
	ce_menu *menu = new ce_menu();
	menu->setupMenu();
	menu->showMenu();
	delete menu;

	allegro_exit();

	return 1;
}
コード例 #4
0
ファイル: allegro.c プロジェクト: gsrr/Python
void textgfx_init()
{
#ifdef UNIX
	strcpy(_xwin.application_name, "vitetris");
	strcpy(_xwin.application_class, "Vitetris");
#endif
	if (install_allegro(SYSTEM_AUTODETECT, &errno, NULL) != 0)
		exit(1);
#ifdef UNIX
	sigaction(SIGINT, NULL, &allegro_sigint_handler);
	signal(SIGINT, sigint_handler);
#endif
	load_pc8x16_font();
	set_window_title(VITETRIS_VER);
	set_close_button_callback(close_btn);
#ifndef UNIX
	/* Seems to cause seg fault later quite randomly on Linux  */
	int depth = desktop_color_depth();
	if (depth != 0)
		set_color_depth(depth);
#endif
	virt_screen = set_screen(getopt_int("", "fullscreen"));
	lang |= LATIN1;
	if (!font8x16) {
		font8x16 = font;
		textgfx_flags |= ASCII;
	}
	setattr_normal();
#if WIN32 && !ALLEGRO_USE_CONSOLE
	if (exists("stdout.tmp")) {
		FILE *fp;
		freopen("stdout2.tmp", "w", stdout);
		fp = fopen("stdout.tmp", "r");
		if (fp) {
			char line[80];
			int i;
			for (i=0; i < 25 && fgets(line, 80, fp); i++) {
				setcurs(0, i);
				i += printline(line);	
			}
			fclose(fp);
			if (i) {
				refreshscreen();
				if (!strncmp(line, "Press ", 6)) {
					install_keyboard();
					clear_keybuf();
					readkey();
					remove_keyboard();
				}
			}
		}
		freopen("stdout.tmp", "w", stdout);
		delete_file("stdout2.tmp");
	}
#endif
}
コード例 #5
0
ファイル: main.cpp プロジェクト: dacap/defenderofnothing
int main()
{
  std::srand(std::time(NULL));

  allegro_init();
  install_timer();
  install_keyboard();
//   install_mouse();
  install_joystick(JOY_TYPE_AUTODETECT);

  override_config_file(redir("defnot.ini").c_str());

  gfx_widescreen = get_config_int("Game", "Widescreen", gfx_widescreen);
  gfx_fullscreen = get_config_int("Game", "Fullscreen", gfx_fullscreen);

  if (!setup_gfx() != 0) {
    allegro_message("Unable to setup the graphics mode\n");
    return 1;
  }

//   if (gfx_capabilities & GFX_HW_CURSOR) {
//     enable_hardware_cursor();
//     select_mouse_cursor(MOUSE_CURSOR_ARROW);
//     show_mouse(screen);
//   }

  if (!load_media()) {
    allegro_message("Unable to load data files to play the game\n");
    return 1;
  }

  // install the timer to control the game speed
  LOCK_VARIABLE(beats);
  LOCK_FUNCTION(timer_control);

  beats = 0;
  install_int_ex(timer_control, BPS_TO_TIMER(BPS));

  // insert the callback routine for the close-button
  LOCK_VARIABLE(continuing);
  LOCK_FUNCTION(close_button);

  set_close_button_callback(close_button);

  // play the game
  game_loop();

  set_config_int("Game", "Widescreen", gfx_widescreen);
  set_config_int("Game", "Fullscreen", gfx_fullscreen);

  remove_int(timer_control);
  allegro_exit();
  return 0;
}
コード例 #6
0
ファイル: skat.c プロジェクト: ThomasWitte/sskat
int main(int argc, char **argv) {
    allegro_init();
    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, SCRW, SCRH, 0, 0);
    install_keyboard();
    install_mouse();
    install_timer();

    LOCK_VARIABLE(timer);
    LOCK_FUNCTION(timerupdate);
    install_int_ex(timerupdate, BPS_TO_TIMER(TIMER_BPS));

    srand((unsigned)time(NULL));
    set_window_title("Skat");

    LOCK_FUNCTION(close_handler);
    set_close_button_callback(close_handler);

    cards = load_bitmap("images/cards.tga", NULL);
    game.p[0] = &human;
    game.p[1] = &cpu1;
    game.p[2] = &cpu2;
    human.choose_card = human_choose_card;
    cpu1.choose_card = cpu_choose_card;
    cpu2.choose_card = cpu_choose_card;
    human.choose_game = human_choose_game;
    cpu1.choose_game = cpu_choose_game;
    cpu2.choose_game = cpu_choose_game;
    human.reizen = human_reizen;
    cpu1.reizen = cpu_reizen;
    cpu2.reizen = cpu_reizen;
    human.schieben = human_schieben;
    cpu1.schieben = cpu_schieben;
    cpu2.schieben = cpu_schieben;
    human.kontra = human_kontra;
    cpu1.kontra = cpu_kontra;
    cpu2.kontra = cpu_kontra;
    human.name = "Stefan";
    cpu1.name = "Robert";
    cpu2.name = "Thomas";
    human.rtext = cpu1.rtext = cpu2.rtext = NULL;
    human.total_points = 0;
    cpu1.total_points = 0;
    cpu2.total_points = 0;

    enable_hardware_cursor();
    show_mouse(screen);

    buffered_do_dialog(main_dlg, -1);

    destroy_bitmap(cards);
}
コード例 #7
0
ファイル: main.cpp プロジェクト: ADSgames/Panic-Station
// Setup game
void setup(){
  // Setup for FPS system
  LOCK_VARIABLE(ticks);
  LOCK_FUNCTION(ticker);
  install_int_ex(ticker, BPS_TO_TIMER(updates_per_second));

  LOCK_VARIABLE(game_time);
  LOCK_FUNCTION(game_time_ticker);
  install_int_ex(game_time_ticker, BPS_TO_TIMER(10));

  // Close button
  LOCK_FUNCTION(close_button_handler);
  set_close_button_callback(close_button_handler);

  // Game state
  int stateID = STATE_NULL;
  int nextState = STATE_NULL;

  // Variables
  closeGame = false;
}
コード例 #8
0
ファイル: main.c プロジェクト: KUNICA/MoneyMan
int main(int argc, char *argv[]) {
	int i;
	char **menutext;

	/* Allocate space for menu texts and write them there */

	menutext = malloc(5*sizeof(*menutext));
	for(i=0;i<5;i++)
		menutext[i] = malloc(64*sizeof(**menutext));

	sprintf(menutext[0],"Play speed mode");
	sprintf(menutext[1],"Play time mode");
	sprintf(menutext[2],"Players: 1");
	sprintf(menutext[3],"Settings");
	sprintf(menutext[4],"Quit");

	/* Init allegro and stuff I need */
	allegro_init();
	install_keyboard();
	/* install_mouse(); */

	/* Init gfx mode */
	set_color_depth(24);
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800,600,0,0);
	set_window_title("Anton Pirogov's MoneyMan v1.0");

	/* Init logic tick timer */
	install_timer();
	LOCK_VARIABLE(speed_counter);
	LOCK_FUNCTION(increment_speed_counter);
	install_int_ex(increment_speed_counter, BPS_TO_TIMER(60));
	/* Lock coin movement timer */
	LOCK_VARIABLE(coinmove_counter);
	LOCK_FUNCTION(increment_coinmove_counter);

	set_close_button_callback( close_button_handler ); /* Close with X */

	/* Set colors */
	titlecol=makecol(255,192,0);
	infocol=makecol(255,128,192);
	menucol=makecol(0,0,255);
	menuselcol=makecol(171,171,255);
	backcolor=makecol(245, 245, 220); /* beige */
	scoretitcol=makecol(0,128,128);
	scorenamcol=makecol(128,64,255);
	scorescrcol=makecol(255,128,255);

	/* Load font */
	myfont = load_font("gfx/Komikaboogie18px.tga",NULL,NULL);

	/* Show main menu */
	read_scores();
	generic_menu(menutext,5,mainmenu_event,backcolor,menucol,menuselcol,fontpxsize,0,0,renderscores);

	/* Finish clean up */
	for (i=0;i<4;i++)
		free(menutext[i]);
	free(menutext);
	allegro_exit();
	return 0;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: Bencepapa/CymonsGames
//main function
void main()
{
    //setup allegro
    allegro_init();
    install_mouse();
    install_timer();
    set_color_depth(COLOR_DEPTH);
    set_gfx_mode(MODE, WIDTH, HEIGHT, 0, 0);

    //setup the timer
    install_int(update_timer, 1);

    //seed random number
    srand(time(NULL));

    //set up the close button
    set_close_button_callback(quit);

    //initialize the buffer
    buffer = create_bitmap(WIDTH, HEIGHT);

    //main loop
    while (!end_game)
    {
        //log the start time
        start_time = timer;

        F_PLUS = (loop_num/50);
        if (F_PLUS > 120) F_PLUS = 120;

        mx = (mouse_x+mx*7)/8;
        my = (mouse_y+my*7)/8;

        if (mouse_b & 2) {nshots = 0; score = 0; ray_t = 50; game_over = false;}

        //fire a new shot
        if (loop_num % 10-F_PLUS/30 == 0)
        {
                if (rand()%2)
                {
                        shot[nshots].x = rand()%2*WIDTH;
                        shot[nshots].y = rand()%HEIGHT;
                        shot[nshots].vy = 0;
                        shot[nshots].vx = (WIDTH/2-shot[nshots].x)/(WIDTH/2);
                        nshots++;
                }
                else
                {
                        shot[nshots].y = rand()%2*HEIGHT;
                        shot[nshots].x = rand()%WIDTH;
                        shot[nshots].vx = 0;
                        shot[nshots].vy = (HEIGHT/2-shot[nshots].y)/(HEIGHT/2);
                        nshots++;
                }
        }
        //rays
        if ((loop_num % 300-F_PLUS == 0)&&(loop_num > 300))
        {
                ray_x = mx+rand()%11-5;
                ray_y = my+rand()%11-5;
                ray_t = -40;
        }

        if (loop_num % 2) ray_t++;

        //bullet move
        for (int i = 0; i < nshots; i++)
        {
                shot[i].x += shot[i].vx;
                shot[i].y += shot[i].vy;
                if ((shot[i].x > WIDTH)||(shot[i].y > HEIGHT)||(shot[i].x < 0)||(shot[i].y < 0)){nshots--; shot[i] = shot[nshots];}
                if (hit(mx, my, shot[i].x, shot[i].y, 5)){game_over = true;}
        }

        //death
        if ((abs(ray_t) < 20)&&(((mx < ray_x+(20-abs(ray_t)))&&(mx > ray_x-(20-abs(ray_t))))
        ||((my < ray_y+(20-abs(ray_t)))&&(my > ray_y-(20-abs(ray_t)))))){game_over = true;}

        ////drawing////

        //player
        if (!game_over)
        circle(buffer, mx, my, 5, WHITE);
        else
        circle(buffer, mx, my, 5, makecol(255, 0, 0));

        //bullets
        for (int i = 0; i < nshots; i++)
        {
                circlefill(buffer, shot[i].x, shot[i].y, 2, WHITE);
        }

        //beams
        if (ray_t <= -20)
        {
                hline(buffer, 0, ray_y, WIDTH, WHITE);
                vline(buffer, ray_x, 0, HEIGHT, WHITE);
        }
        if (abs(ray_t) < 20)
        {
                rectfill(buffer, 0, ray_y-(20-abs(ray_t)), WIDTH, ray_y+(20-abs(ray_t)), WHITE);
                rectfill(buffer, ray_x-(20-abs(ray_t)), 0, ray_x+(20-abs(ray_t)), HEIGHT, WHITE);
                rectfill(buffer, 0, ray_y-(20-abs(ray_t))/2, WIDTH, ray_y+(20-abs(ray_t))/2, SILVER);
                rectfill(buffer, ray_x-(20-abs(ray_t))/2, 0, ray_x+(20-abs(ray_t))/2, HEIGHT, SILVER);
        }

        //text
        if (!game_over)
        textprintf_centre_ex(buffer, font, WIDTH/2, 10, WHITE, BLACK, "%i", score*LOOP_TIME/1000);
        else
        {
        textprintf_centre_ex(buffer, font, WIDTH/2, 10, makecol(255, 0, 0), BLACK, "%i", score*LOOP_TIME/1000);
        textprintf_centre_ex(buffer, font, WIDTH/2, HEIGHT/2-5, WHITE, BLACK, "Game Over");
        textprintf_centre_ex(buffer, font, WIDTH/2, HEIGHT/2+10, WHITE, BLACK, "Right-Click to restart");
        }

        //draw to the screen
        blit(buffer, screen, 0, 0, 0, 0, WIDTH, HEIGHT);

        //clear the buffer
        clear_to_color(buffer, BLACK);

        //wait
        while (timer < start_time + LOOP_TIME)
        {rest(1);}
        loop_num++;
        if (game_over == false) score++;
    }
    remove_int(update_timer);
    destroy_bitmap(buffer);
    return;
}
コード例 #10
0
ファイル: MACAUBAU.c プロジェクト: GiovanniSuy/MACAUBAU
int main()
{
 allegro_init();
 install_timer();
 install_keyboard();
 set_color_depth(32);
 set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800, 600, 0, 0);
 set_window_title("MACAUBAU");

 /// Funcoes
 LOCK_VARIABLE(saida_programa);
 LOCK_FUNCTION(fechar_X);
 set_close_button_callback(fechar_X);


 tempMsec=0;
 LOCK_FUNCTION(tempo_Turtle);
 LOCK_VARIABLE(tempMsec);
 install_int_ex(tempo_Msec, MSEC_TO_TIMER(1));

 int exit_program = FALSE;

 /// BITMAPS
 BITMAP* buffer=create_bitmap(SCREEN_W, SCREEN_H);
 BITMAP* personagem=load_bitmap("imagens/m1d.bmp", NULL);
 BITMAP* fundo=load_bitmap("imagens/fundo.bmp",NULL);
 BITMAP* turtle=load_bitmap("imagens/t1.bmp", NULL);
 BITMAP* gameover=load_bitmap("imagens/gameover.bmp",NULL);
 BITMAP* fail=load_bitmap("imagens/fail.bmp",NULL);

 BITMAP* per[4];
 per[0]=load_bitmap("imagens/m1d.bmp",NULL);
 per[1]=load_bitmap("imagens/m2d.bmp",NULL);
 per[2]=load_bitmap("imagens/m1e.bmp",NULL);
 per[3]=load_bitmap("imagens/m2e.bmp",NULL);

 /// Fonts
 FONT * fontscore = load_font("fontscore.pcx",NULL,NULL);

 /// Variaveis
 int score = 0,printnv=1;
 float nivel=1;
 int iPersonagem=0, seed, xPersonagem=0, colisao=0;
 int tempo_mov=tempMsec, tempo_animacao=tempMsec;
 int finalScore=0;

 struct turtle vetTurtle[4]={0,0,0,0};

 vetTurtle[0].tempo=tempMsec;
 vetTurtle[1].tempo=tempMsec;
 vetTurtle[2].tempo=tempMsec;

 while(!saida_programa)
 {
   /// ENTRADA
   if (key[KEY_ESC]) saida_programa=TRUE;

   /// ATUALIZACAO DE DADOS
   if(tempMsec-vetTurtle[0].tempo>=20)
   {
    vetTurtle[0].yTurtle+=10*nivel;
    vetTurtle[0].angulo+=7;
    vetTurtle[0].tempo=tempMsec;
   }

   if(vetTurtle[0].yTurtle>560 && colisao!=1)
   {
    seed=time(0);
    srand(seed);
    vetTurtle[0].xTurtle=(rand()%13)*70;

    score+=1;
    vetTurtle[0].yTurtle=0;
   }


   if(tempMsec-vetTurtle[1].tempo>=20)
   {
    vetTurtle[1].yTurtle+=9*nivel;
    vetTurtle[1].angulo+=7;
    vetTurtle[1].tempo=tempMsec;
   }

   if(vetTurtle[1].yTurtle>560 && colisao!=1)
   {
    seed=time(0);
    srand(seed);
    vetTurtle[1].xTurtle=(rand()%7+rand()%7)*70;

    score+=1;
    vetTurtle[1].yTurtle=0;
   }

   if(tempMsec-vetTurtle[2].tempo>=20)
   {
       vetTurtle[2].yTurtle+=9.5*nivel;
       vetTurtle[2].angulo+=7;
       vetTurtle[2].tempo=tempMsec;
   }
   if(vetTurtle[2].yTurtle>560 && colisao!=1)
   {
       seed=time(0);
       srand(seed);
       vetTurtle[2].xTurtle=(rand()%5+rand()%8+rand()%2)*70;


       score+=1;
       vetTurtle[2].yTurtle=0;
   }

   /// * ======== MOVIMENTO PERSONAGEM ======== * ///

    ///*xPersonagem -- *iPersonagem -- *colisao -- *tempMsec -- *tempo_mov -- *tempo_animacao
    mov_Personagem(&xPersonagem, &iPersonagem, &colisao, &tempMsec, &tempo_mov, &tempo_animacao);

   /// * ======== COLISOES ========== * ///

   func_Colisao(xPersonagem,vetTurtle[0].xTurtle,vetTurtle[0].yTurtle,&colisao);
   func_Colisao(xPersonagem,vetTurtle[1].xTurtle,vetTurtle[1].yTurtle,&colisao);
   func_Colisao(xPersonagem,vetTurtle[2].xTurtle,vetTurtle[2].yTurtle,&colisao);

   /// * ========== NIVEIS - DIFICULDADES =========== * ///
   func_Nivel(score,&nivel,&printnv);

   if(vetTurtle[0].angulo>255) vetTurtle[0].angulo=0;
   if(vetTurtle[1].angulo>255) vetTurtle[1].angulo=0;
   if(vetTurtle[2].angulo>255) vetTurtle[2].angulo=0;


   /// * ======== DESENHOS ========= * ///

   clear(buffer);
   draw_sprite(buffer,fundo,0,0);

    if(colisao==0)
   draw_sprite_ex(buffer,per[iPersonagem],xPersonagem,500,0,0);

   else
   {
     if(score!=0)finalScore=score;
     draw_sprite(buffer,gameover,0,0);
     textprintf_ex(buffer,fontscore,300,320,makecol(181,230,29), -1, "FINAL SCORE: %d", finalScore);
     nivel=1;
     score=0;
     printnv=1;
   }

   /// ========== Desenho das Turtles ======== ///
   rotate_sprite(buffer,turtle,vetTurtle[0].xTurtle,vetTurtle[0].yTurtle,ftofix(vetTurtle[0].angulo));
   rotate_sprite(buffer,turtle,vetTurtle[1].xTurtle,vetTurtle[1].yTurtle,ftofix(vetTurtle[1].angulo));
   rotate_sprite(buffer,turtle,vetTurtle[2].xTurtle,vetTurtle[2].yTurtle,ftofix(vetTurtle[2].angulo));

   if(vetTurtle[0].yTurtle>=500 && colisao!=1) draw_sprite(buffer,fail,vetTurtle[0].xTurtle,540);
   if(vetTurtle[1].yTurtle>=500 && colisao!=1) draw_sprite(buffer,fail,vetTurtle[1].xTurtle,540);
   if(vetTurtle[2].yTurtle>=500 && colisao!=1) draw_sprite(buffer,fail,vetTurtle[2].xTurtle,540);



   if(colisao!=1)
   {
     textprintf_ex(buffer,fontscore,10,10,makecol(181,230,29), -1, "SCORE: %d", score);
     textprintf_ex(buffer,fontscore,700,10,makecol(181,230,29), -1, "NIVEL: %d",printnv);
   }

   draw_sprite(screen, buffer,0,0);

 }

 /// DESTROY
 destroy_font(fontscore);
 destroy_bitmap(buffer);
 destroy_bitmap(turtle);
 destroy_bitmap(personagem);
 destroy_bitmap(fundo);

 allegro_exit();
 return 0;
}
コード例 #11
0
int install()
{
    int screen_mode;

    if(IsInstalled)
        return 0;
    if(allegro_init())
        return 1;
    if(install_allegro_gl())
        return 1;
    set_window_title("Sharp Fighters");

    Resolutions=get_gfx_mode_list(GFX_OPENGL_FULLSCREEN);

    LoadSettings();

   LoadCollisionData();

    if(install_keyboard())
        return 1;
    if(install_timer())
        return 1;
    if(install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL))
        return 1;

    JoyStickEnabled=(install_joystick(JOY_TYPE_AUTODETECT)==0);
    JoyStickEnabled=JoyStickEnabled && num_joysticks;
    LoadInput();

    if(install_fonts())
        printf("One or more font files were not loaded.\n");

    allegro_gl_set(AGL_COLOR_DEPTH, depth);
    allegro_gl_set(AGL_RENDERMETHOD, 1);
    allegro_gl_set(AGL_DOUBLEBUFFER, 1);
    allegro_gl_set(AGL_SUGGEST, AGL_COLOR_DEPTH | AGL_DOUBLEBUFFER | AGL_RENDERMETHOD);

    if(Fullscreen)
        screen_mode=GFX_OPENGL_FULLSCREEN;
    else
        screen_mode=GFX_OPENGL_WINDOWED;

    if (set_gfx_mode(screen_mode, Width,Height, 0, 0))
    {
        set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
        allegro_message("Unable to set graphic mode\n%s\n", allegro_error);
        return 1;
    }
    set_close_button_callback(close_button_handler);
    SetOpenGL2D();
    screenimage=(IMAGE*)malloc(sizeof(IMAGE));
    screenimage->ID=0;
    AspectRatio=(float)SCREEN_W/(float)SCREEN_H;

    if(install_int(Ticks,1))
        return 1;
    if(install_int(ProcessKeys,25))
        return 1;

    IsInstalled=1;
    return 0;
}
コード例 #12
0
ファイル: main.c プロジェクト: jcarlosadm/minigames
int main()
{
    init(); // inicializa

/*  #######################################################################################
                    declaração das variáveis (e algumas inicializações)
    #######################################################################################
*/
    int i,j; // controladores de loops e auxiliares
    int ticks; // controla velocidade do jogo
    int tempo_de_jogo=0; // controla o tempo de jogo
    int matriz_tela[ALTURA_MAPA/32][LARGURA_MAPA/32]; // matriz da tela
    int ajuste_mapa = 0; // variavel que cuida do movimento do mapa e dos objetos nele
    int tela = 0, selecionar = 0; //controla o carregamento de cada tela
    int tela_destino=1; // determina qual tela será carregada após a tela de carregamento
    int fase=1;
    int carrega_fase=1;
    char nome_fase[N_FASES][10]={"mapa1.txt","mapa2.txt","mapa3.txt"};
    int loading_time = 0;
    int estagio_loading=0;
    int bloqueios[3] = {TERRA, PEDRA, CHAO};
    int pause = 0;
    int tocando=0;
    int tocando_game_over=0;
    int tutorial=1;

    // abrindo os datafiles
    DATAFILE* graficos = NULL;
    DATAFILE* musicas = NULL;
    DATAFILE* efeitos = NULL;
    DATAFILE* fontes = NULL;

    packfile_password("kill");

    graficos = load_datafile("imagens.dat");
    musicas = load_datafile("musicas.dat");
    efeitos = load_datafile("efeitos.dat");
    fontes = load_datafile("fontes.dat");

    packfile_password(NULL);

    // variáveis de objetos
    Tjanelas janelas;
    Tcriatura guerreiro; // declara objeto guerreiro
    Toponentes inimigos;
    Titens itens;
    Teventos eventos;

    // declara BITMAPS
    BITMAP *buffer = create_bitmap(SCREEN_W,SCREEN_H); // Cria o buffer;
    BITMAP *mapa = create_bitmap(LARGURA_MAPA,ALTURA_MAPA); // Cria o mapa
    BITMAP *texturas[MAX_TERRENOS]; // declara a array de texturas
    BITMAP *background = create_bitmap(960,480);

    //BITMAPs do Menu
    BITMAP *menu_iniciar = (BITMAP*) graficos[MENU_1].dat;//menu iniciar
    BITMAP *menu_creditos = (BITMAP*) graficos[MENU_3].dat;
    BITMAP *menu_options = (BITMAP*) graficos[MENU_2].dat;//menu opções
    BITMAP *menu_exit = (BITMAP*) graficos[MENU_4].dat;//menu saída

    BITMAP *logo = (BITMAP*) graficos[LOGO_1].dat;

    // BITMAPS da tela de carregamento
    BITMAP *tela_loading[4];
    tela_loading[0] = (BITMAP*) graficos[CARREGAR_1].dat;
    tela_loading[1] = (BITMAP*) graficos[CARREGAR_2].dat;
    tela_loading[2] = (BITMAP*) graficos[CARREGAR_3].dat;
    tela_loading[3] = (BITMAP*) graficos[CARREGAR_4].dat;

    // Declara fontes
    FONT* corpo_texto = (FONT*) fontes[CORPO_TEXTO].dat;
    FONT* titulo_texto = (FONT*) fontes[TITULO_TEXTO].dat;

    // Declara sons
    MIDI* musica_floresta = (MIDI*) musicas[MUSICA_FLORESTA].dat;
    MIDI* musica_caverna = (MIDI*) musicas[MUSICA_CAVERNA].dat;
    MIDI* musica_chefe1 = (MIDI*) musicas[MUSICA_CHEFE_1].dat;
    MIDI* musica_chefe2 = (MIDI*) musicas[MUSICA_CHEFE_2].dat;
    MIDI* musica_chefe3 = (MIDI*) musicas[MUSICA_CHEFE_3].dat;
    MIDI* musica_menu = (MIDI*) musicas[MUSICA_MENU].dat;
    MIDI* musica_gameover = (MIDI*) musicas[MUSICA_GAMEOVER].dat;

    SAMPLE* selecao = (SAMPLE*) efeitos[SELECIONAR].dat;
    SAMPLE* confirmar = (SAMPLE*) efeitos[CONFIRMAR].dat;
    SAMPLE* espada = (SAMPLE*) efeitos[ESPADA].dat;
    SAMPLE* besta = (SAMPLE*) efeitos[BESTA].dat;
    SAMPLE* som_pause = (SAMPLE*) efeitos[PAUSE].dat;
    SAMPLE* som_dano_goblin = (SAMPLE*) efeitos[DANO_GOBLIN].dat;
    SAMPLE* som_dano_guerreiro = (SAMPLE*) efeitos[DANO_HEROI].dat;
    SAMPLE* som_cura = (SAMPLE*) efeitos[CURA].dat;
    SAMPLE* som_vinhas = (SAMPLE*) efeitos[PARALISIA].dat;
    SAMPLE* som_recuo = (SAMPLE*) efeitos[RECUO].dat;

    volume=250;
    set_volume(volume,volume);

/*  #######################################################################################
                                fim da declaração das variáveis
    #######################################################################################
*/

    // configura saída com o botão x no alto da tela
    exit_program = FALSE;
    LOCK_FUNCTION(fecha_programa);
    LOCK_VARIABLE(exit_program);
    set_close_button_callback(fecha_programa); // fecha a qualquer momento com o botão fechar

    // timer
    timer=0;
    LOCK_FUNCTION(incrementa_timer);
    LOCK_VARIABLE(timer);
    install_int_ex(incrementa_timer,BPS_TO_TIMER(60)); // para que o jogo execute 60 vezes por segundo

    ticks = timer; // velocidade do jogo

    // Processo de repetição principal
    while (!exit_program)
    {
        // loop válido, executado 60 vezes por segundo
        while(ticks<=timer && !exit_program)
        {
            // tela de menu
            if(tela==0)
            {
                clear_bitmap(buffer);
                keyboard_input();
                menu_inicial(buffer, &selecionar, menu_iniciar, menu_options, menu_exit,menu_creditos,&loading_time, &tela,
                             &estagio_loading,&tela_destino,&fase,&carrega_fase,&tempo_de_jogo,selecao,confirmar,&tocando,
                             musica_menu);
            }

            // tela de loading
            else if (tela == 9)
            {
                clear_bitmap(buffer);
                tela_carregamento(buffer, tela_loading, &loading_time,tela_destino, &tela,logo);
                carrega_elementos_fase(&carrega_fase,&estagio_loading,matriz_tela,nome_fase,fase,&itens,&guerreiro,&inimigos,
                                       &janelas,background,texturas,&eventos,mapa,graficos);
            }

            // tela de jogo
            else if(tela==1)
            {
                // toca a musica da fase se não estiver tocando
                tocar(&tocando,fase,musica_floresta,musica_caverna);

                // atualiza estado do teclado
                keyboard_input();

                pausar(&pause,&selecionar,som_pause); // verifica se pressionou pause

                // limpa bitmaps de armazenamento
                clear_bitmap(buffer); // Limpa o buffer;
                clear_bitmap(guerreiro.sprite); // Limpa bitmap guerreiro
                clear_bitmap(inimigos.goblins_guerreiros.goblins[0].sprite); // Limpa bitmap goblin tipo 1
                clear_bitmap(inimigos.goblins_guerreiros.goblins[1].sprite); // Limpa bitmap goblin tipo 1

                if (!pause) // pause pode travar toda a lógica e tempo de jogo, exceto os eventos
                {
                    // incrementa o tempo de jogo
                    tempo_de_jogo++;

                    // Lógica do jogo
                    tocou_oponente(&guerreiro,&inimigos,tempo_de_jogo,som_dano_guerreiro);
                    verificar_status(&guerreiro,&inimigos,tempo_de_jogo,&itens);
                    movimento_guerreiro(&guerreiro,matriz_tela, bloqueios,som_recuo);
                    ataque_guerreiro(&guerreiro,tempo_de_jogo,&inimigos,espada,som_dano_goblin);

                    calcular_ajuste_mapa(&guerreiro,&ajuste_mapa);
                    acoes_goblins(&inimigos,&guerreiro,tempo_de_jogo,matriz_tela,bloqueios,&itens,espada,besta,som_dano_guerreiro,
                                  som_vinhas);
                    verifique_efeito_item(&itens,&guerreiro,&inimigos,tempo_de_jogo,som_dano_guerreiro,som_cura);
                    movimento_itens(&itens,&guerreiro,tempo_de_jogo,matriz_tela,bloqueios);
                }

                verificar_evento(&pause,fase,&eventos,&guerreiro,&janelas,matriz_tela,bloqueios,&ajuste_mapa,musica_chefe1,
                                 musica_chefe2,musica_chefe3,confirmar);

                // Desenhar
                draw_sprite(buffer,background,ajuste_mapa/10,0);
                draw_sprite(buffer, mapa, ajuste_mapa, 0); // manda mapa para o buffer na posição mov_mapa
                desenhar_todos_goblins(&inimigos,buffer,ajuste_mapa,tempo_de_jogo);
                desenhar_guerreiro(buffer,&guerreiro,&inimigos,ajuste_mapa,tempo_de_jogo,graficos); // desenha guerreiro e manda para buffer
                desenhar_itens(buffer,&itens,ajuste_mapa);
                desenhos_evento(buffer,fase,&eventos,&janelas,&guerreiro,corpo_texto,titulo_texto,&inimigos);

                pause_menu(&pause,&eventos,buffer,&selecionar,&tela,tempo_de_jogo,&tela_destino,&loading_time,
                           selecao,confirmar,&tocando);
                game_over(&pause,&eventos,buffer,&selecionar,&tela,tempo_de_jogo,&tela_destino,&loading_time,selecao,confirmar,
                          &tocando,musica_gameover,&guerreiro,&estagio_loading,&tocando_game_over,&carrega_fase,graficos);

                // se inicio da fase, coloca um efeito de opacidade
                efeito_inicio_fase(&eventos,&pause,buffer,graficos,confirmar,fase,&tutorial);

                // nova fase?
                verifica_nova_fase(&guerreiro,&fase,&carrega_fase,&tela,&loading_time,&estagio_loading,&tela_destino,
                                   &inimigos.chefes,&eventos,&tocando,&pause,buffer);

                blit(buffer,screen,0,0,0,0,LARGURA_SCREEN,ALTURA_SCREEN); // Manda o buffer para a tela;


            }
            // tela de opçções
            else if(tela==2)
            {
                clear_bitmap(buffer);
                keyboard_input();

                menu_opcoes(buffer,graficos,selecao,confirmar,&tela);
            }
            // tela de créditos
            else if(tela==3)
            {
                clear_bitmap(buffer);
                keyboard_input();

                creditos(buffer,graficos,confirmar,&tela);
            }
            else if(tela==4)
            {
                clear_bitmap(buffer);
                keyboard_input();

                final_de_jogo(buffer,graficos,&tela,confirmar);
            }
            ticks++; // incrementa controle de velocidade do jogo
        }
    }

    deinit(); // finaliza

    // destruição de bitmaps

    destroy_bitmap(buffer);
    destroy_bitmap(mapa);
    destroy_bitmap(background);

    for(i=0;i<MAX_TERRENOS;i++)
        destroy_bitmap(texturas[i]);

    destroy_bitmap(guerreiro.sprite);
    for(i=0;i<8;i++)
        destroy_bitmap(guerreiro.vetor_sprite[i]);
    for(i=0;i<10;i++)
        destroy_bitmap(guerreiro.barraHp[i]);

    for(i=0;i<8;i++)
    {
        for(j=0;j<6;j++)
            destroy_bitmap(inimigos.goblins_guerreiros.goblins[j].vetor_sprite[i]);
        if(i!=7)
        {
            for(j=0;j<6;j++)
                destroy_bitmap(inimigos.goblins_arqueiros.goblins[j].vetor_sprite[i]);
        }
        destroy_bitmap(inimigos.chefes.chefe[0].vetor_sprite[i]);
    }

    for(i=0;i<6;i++)
    {
        destroy_bitmap(inimigos.goblins_guerreiros.goblins[i].sprite);
        destroy_bitmap(inimigos.goblins_arqueiros.goblins[i].sprite);
    }
    destroy_bitmap(inimigos.chefes.chefe[0].sprite);

    for(i=0;i<8;i++)
    {
        destroy_bitmap(itens.todosItens[i].imagem);
        destroy_bitmap(itens.todosItens[i].imagem_buffer);
    }

    return 0 ;
}
コード例 #13
0
ファイル: allegro.c プロジェクト: Yurand/tw-light
/* _install_allegro:
 *  Initialises the Allegro library, activating the system driver.
 */
static int _install_allegro(int system_id, int *errno_ptr, int (*atexit_ptr)(void (*func)(void)))
{
   RGB black_rgb = {0, 0, 0, 0};
   char tmp1[64], tmp2[64];
   int i;

   #ifndef ALLEGRO_USE_CONSTRUCTOR
      /* call constructor functions manually */
      extern void _initialize_datafile_types();
      extern void _midi_constructor();
      extern void _mouse_constructor();

      _initialize_datafile_types();
      _midi_constructor();
      _mouse_constructor();
      _register_bitmap_file_type_init();
      _register_sample_file_type_init();
      _register_font_file_type_init();
   #endif

   if (errno_ptr)
      allegro_errno = errno_ptr;
   else
      allegro_errno = &errno;

   /* set up default palette structures */
   for (i=0; i<256; i++)
      black_palette[i] = black_rgb;

   for (i=16; i<256; i++)
      desktop_palette[i] = desktop_palette[i & 15];

   /* lock some important variables */
   LOCK_VARIABLE(screen);
   LOCK_VARIABLE(gfx_driver);
   LOCK_VARIABLE(gfx_capabilities);
   LOCK_VARIABLE(_last_bank_1);
   LOCK_VARIABLE(_last_bank_2);
   LOCK_VARIABLE(_gfx_bank);
   LOCK_VARIABLE(_drawing_mode);
   LOCK_VARIABLE(_drawing_pattern);
   LOCK_VARIABLE(_drawing_x_anchor);
   LOCK_VARIABLE(_drawing_y_anchor);
   LOCK_VARIABLE(_drawing_x_mask);
   LOCK_VARIABLE(_drawing_y_mask);
   LOCK_VARIABLE(_current_palette);
   LOCK_VARIABLE(os_type);

   /* nasty stuff to set up the config system before the system driver */
   system_driver = _system_driver_list[0].driver;

   /* needed in case set_config_file was called before allegro_init */
   _reload_config();

   reload_config_texts(NULL);

   if (system_id == SYSTEM_AUTODETECT)
      system_id = get_config_id(uconvert_ascii("system", tmp1), uconvert_ascii("system", tmp2), SYSTEM_AUTODETECT);

   system_driver = NULL;

   /* initialise the system driver */
   usetc(allegro_error, 0);

   for (i=0; _system_driver_list[i].driver; i++) {
      if ((_system_driver_list[i].id == system_id) ||
	  ((_system_driver_list[i].autodetect) && (system_id == SYSTEM_AUTODETECT))) {
	 system_driver = _system_driver_list[i].driver;
	 system_driver->name = system_driver->desc = get_config_text(system_driver->ascii_name);
	 if (system_driver->init() != 0) {
	    system_driver = NULL;
	    if (system_id != SYSTEM_AUTODETECT)
	       break;
	 }
	 else
	    break;
      }
   }

   if (!system_driver)
      return -1;

   /* disable close button */
   set_close_button_callback(NULL);

   /* detect CPU type */
   check_cpu();

#if defined(ALLEGRO_UNIX) || defined(ALLEGRO_WINDOWS)
   /* detect filename encoding used by libc */
   /* XXX This should be done for all platforms but I'm not set up to check
    * that all platforms have been covered before making the 4.2.3 release.
    * --pw
    */
   _al_detect_filename_encoding();
#endif

   /* set up screensaver policy */
   _screensaver_policy = get_config_int(uconvert_ascii("system", tmp1),
                                        uconvert_ascii("disable_screensaver", tmp2),
                                        FULLSCREEN_DISABLED);

   /* install shutdown handler */
   if (_allegro_count == 0) {
      if (atexit_ptr)
	 atexit_ptr(allegro_exit_stub);
   }

   _allegro_count++;

   TRACE(PREFIX_I "Allegro initialised (instance %d)\n", _allegro_count);
   return 0;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: RichardMarks/islandadventure
int main(int argc, char* argv[])
{
	// init allegro and add keyboard and optional mouse support
	allegro_init();
	install_timer();
	install_keyboard();
	if (ENABLE_MOUSE_SUPPORT)
	{
		install_mouse();
	}

	// set the video mode
	set_color_depth(WINDOW_COLOR_DEPTH);
	set_gfx_mode(
		(WINDOW_USE_FULLSCREEN) ?
			GFX_AUTODETECT_FULLSCREEN :
			GFX_AUTODETECT_WINDOWED,
		WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0);
	// set the window caption text
	set_window_title(WINDOW_CAPTION);

	// create the back buffer bitmap
	backbuffer = create_bitmap(SCREEN_W, SCREEN_H);

	// seed the random number generator
	srand(time(0));

	// lock the static functions and variables we need for handling timing and closing the window via the [X] button
	LOCK_FUNCTION(my_allegro_close_button_handler);
	LOCK_FUNCTION(my_allegro_timer_speed_controller);
	LOCK_VARIABLE(allegrotimerspeedcounter);

	// set the callback function for the close-button to our global handler function
	set_close_button_callback(my_allegro_close_button_handler);

	// set our FPS lock timing global function
	install_int_ex(my_allegro_timer_speed_controller, BPS_TO_TIMER(FRAME_LOCK_RATE));

	// setup the game
	if (!setup_game())
	{
		fprintf(stderr, "The game initialization has failed. Cannot continue!\n");
		exit(1);
	}

	// main loop
	bool gameover = false;
	while(!gameover)
	{
		// if our global is ever false
		if (!mainthreadisrunning)
		{
			gameover = true;
		}

		// we only draw when the FPS should be locked
		if (allegrotimerspeedcounter > 0)
		{
			// we only update during our FPS lock time
			while (allegrotimerspeedcounter > 0)
			{
				// ensure the keyboard data is current
				if (keyboard_needs_poll())
				{
					poll_keyboard();
				}

				// ensure the mosue data is current
				if (ENABLE_MOUSE_SUPPORT)
				{
					if (mouse_needs_poll())
					{
						poll_mouse();
					}
				}

				// update
				update_game();

				// decrement the global timing var so that we can leave the update loop!
				allegrotimerspeedcounter--;
			}

			// start rendering the scene
			render_game();

			if (ENABLE_MOUSE_SUPPORT)
			{
				show_mouse(backbuffer);
			}

			// make it all visible
			blit(backbuffer, screen, 0, 0, 0, 0, backbuffer->w, backbuffer->h);
		}
		else
		{
			// a little rest to keep CPU usage down ^-^
			rest(1);
		}
	}

	// shutdown the game
	shutdown_game();

	// clean up the back buffer
	if (backbuffer)
	{
		if (ENABLE_MOUSE_SUPPORT)
		{
			show_mouse(0);
		}
		destroy_bitmap(backbuffer);
	}

	return 0;
}
コード例 #15
0
ファイル: dumbplay.c プロジェクト: JoeyZheng/deadbeef
int main(int argc, const char *const *argv) /* I'm const-crazy! */
{
	DUH *duh;          /* Encapsulates the music file. */
	AL_DUH_PLAYER *dp; /* Holds the current playback state. */

	/* Initialise Allegro */
	if (allegro_init())
		return EXIT_FAILURE;

	/* Check that we have one argument (plus the executable name). */
	if (argc != 2)
		usage(argv[0]);

	/* Tell Allegro where to find configuration data. This means you can
	 * put any settings for Allegro in dumb.ini. See Allegro's
	 * documentation for more information.
	 */
	set_config_file("dumb.ini");

	/* Initialise Allegro's keyboard input. */
	if (install_keyboard()) {
		allegro_message("Failed to initialise keyboard driver!\n");
		return EXIT_FAILURE;
	}

	/* This function call is appropriate for a program that will play one
	 * sample or one audio stream at a time. If you have sound effects
	 * too, you may want to increase the parameter. See Allegro's
	 * documentation for details on what the parameter means. Note that
	 * newer versions of Allegro act as if set_volume_per_voice() was
	 * called with parameter 1 initially, while older versions behave as
	 * if -1 was passed, so you should call the function if you want
	 * consistent behaviour.
	 */
	set_volume_per_voice(0);

	/* Initialise Allegro's sound output system. */
	if (install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL)) {
		allegro_message("Failed to initialise sound driver!\n%s\n", allegro_error);
		return EXIT_FAILURE;
	}

	/* dumb_exit() is a function defined by DUMB. This operation arranges
	 * for dumb_exit() to be called last thing before the program exits.
	 * dumb_exit() does a bit of cleaning up for you. atexit() is
	 * declared in stdlib.h.
	 */
	atexit(&dumb_exit);

	/* DUMB defines its own wrappers for file input. There is a struct
	 * called DUMBFILE that holds function pointers for the various file
	 * operations needed by DUMB. You can decide whether to use stdio
	 * FILE objects, Allegro's PACKFILEs or something else entirely. No
	 * wrapper is installed initially, so you must call this or
	 * dumb_register_stdfiles() or set up your own before trying to load
	 * modules by file name. (If you are using another method, such as
	 * loading an Allegro datafile with modules embedded in it, then DUMB
	 * never opens a file by file name so this doesn't apply.)
	 */
	dumb_register_packfiles();

	/* Load the module file into a DUH object. Quick and dirty: try the
	 * loader for each format until one succeeds. Note that 15-sample
	 * mods have no identifying features, so dumb_load_mod() may succeed
	 * on files that aren't mods at all. We therefore try that one last.
	 */
	duh = dumb_load_it(argv[1]);
	if (!duh) {
		duh = dumb_load_xm(argv[1]);
		if (!duh) {
			duh = dumb_load_s3m(argv[1]);
			if (!duh) {
				duh = dumb_load_mod(argv[1]);
				if (!duh) {
					allegro_message("Failed to load %s!\n", argv[1]);
					return EXIT_FAILURE;
				}
			}
		}
	}

	/* Read the quality values from the config file we told Allegro to
	 * use. You may want to hardcode these or provide a more elaborate
	 * interface via which the user can control them.
	 */
	dumb_resampling_quality = get_config_int("sound", "dumb_resampling_quality", 4);
	dumb_it_max_to_mix = get_config_int("sound", "dumb_it_max_to_mix", 128);

	/* If we're not in DOS, show a window and register our close hook
	 * function.
	 */
#	ifndef ALLEGRO_DOS
		{
			const char *fn = get_filename(argv[1]);
			gfx_half_width = strlen(fn);
			if (gfx_half_width < 22) gfx_half_width = 22;
			gfx_half_width = (gfx_half_width + 2) * 4;

			/* set_window_title() is not const-correct (yet). */
			set_window_title((char *)"DUMB Music Player");

			if (set_gfx_mode(GFX_DUMB_MODE, gfx_half_width*2, 80, 0, 0) == 0) {
				acquire_screen();
				textout_centre(screen, font, fn, gfx_half_width, 20, 14);
				textout_centre(screen, font, "Press any key to exit.", gfx_half_width, 52, 11);
				release_screen();
			} else
				gfx_half_width = 0;
		}

		/* Silly check to get around the fact that someone stupidly removed
		 * an old function from Allegro instead of deprecating it. The old
		 * function was put back a version later, but we may as well use the
		 * new one if it's there!
		 */
#		if ALLEGRO_VERSION*10000 + ALLEGRO_SUB_VERSION*100 + ALLEGRO_WIP_VERSION >= 40105
			set_close_button_callback(&closehook);
#		else
			set_window_close_hook(&closehook);
#		endif

#	endif

	/* We want to continue running if the user switches to another
	 * application.
	 */
	set_display_switch_mode(SWITCH_BACKGROUND);

	/* We have the music loaded, but it isn't playing yet. This starts it
	 * playing. We construct a second object, the AL_DUH_PLAYER, to
	 * represent the playing music. This means you can play the music
	 * twice at the same time should you want to!
	 *
	 * Specify the number of channels (2 for stereo), which 'signal' to
	 * play (always 0 for modules), the volume (1.0f for default), the
	 * buffer size (4096 generally works well) and the sampling frequency
	 * (ideally match the final output frequency Allegro is using). An
	 * Allegro audio stream will be started.
	 */
	dp = al_start_duh(duh, 2, 0, 1.0f,
		get_config_int("sound", "buffer_size", 4096),
		get_config_int("sound", "sound_freq", 44100));

	/* Register our callback functions so that they are called when the
	 * music loops or stops. See docs/howto.txt for more information.
	 * There is no threading issue: DUMB will only process playback
	 * in al_poll_duh(), which we call below.
	 */
	{
		DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(dp);
		DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(sr);
		dumb_it_set_loop_callback(itsr, &loop_callback, NULL);
		dumb_it_set_xm_speed_zero_callback(itsr, &xm_speed_zero_callback, NULL);
	}

	/* Main loop. */
	for (;;) {
		/* Check for keys in the buffer. If we get one, discard it
		 * and exit the main loop.
		 */
		if (keypressed()) {
			readkey();
			break;
		}

		/* Poll the music. We exit the loop if al_poll_duh() has
		 * returned nonzero (music finished) or the window has been
		 * closed. al_poll_duh() might return nonzero if you have set
		 * up a callback that tells the music to stop.
		 */
		if (al_poll_duh(dp) || closed)
			break;

		/* Give other threads a look-in, or allow the processor to
		 * sleep for a bit. YIELD() is defined further up in this
		 * file.
		 */
		YIELD();
	}

	/* Remove the audio stream and deallocate the memory being used for
	 * the playback state. We set dp to NULL to emphasise that the object
	 * has gone.
	 */
	al_stop_duh(dp);
	dp = NULL;

	/* Free the DUH object containing the actual music data. */
	unload_duh(duh);
	duh = NULL;

	/* All done! */
	return EXIT_SUCCESS;
}
コード例 #16
0
void inicia_allegro() {
	int profundidade, res;
	allegro_init();
	install_timer();
	install_keyboard();
	clear_keybuf();
	install_mouse();

	set_uformat(U_ASCII); // Habilita acentuação em ALGUMAS FONTES
	/*profundidade = desktop_color_depth();
	if (profundidade == 0) profundidade = 32;
	   set_color_depth(profundidade);*/

	//roda configuracao de um arquivo
	set_config_file("config.txt");

	profundidade = get_config_int("Inicializacao", "colordepth",32);
	int v = GetVersion() & 65535;
    float versao = (v%256) + (v/256)/10.;
    /*if (versao<=5.1) //5.1 = XP, 6.0 = Vista, 6.1 Win7
        profundidade=16;
    else
        profundidade=32;*/

	set_color_depth(profundidade); //padrao é 32 bits, no XP é 16

	volume=get_config_int("Inicializacao", "volume", 128); //usa as config de volume do arquivo
	exibirFPS=get_config_int("Inicializacao", "exibirFps", 0);

	#define GFX_BWINDOWSCREEN_ACCEL AL_ID('B','W','S','A')
	#define GFX_BWINDOWSCREEN        AL_ID('B','W','S',' ')
    AL_VAR(GFX_DRIVER, gfx_beos_bwindowscreen_accel);
    AL_VAR(GFX_DRIVER, gfx_beos_bwindowscreen);

	vSync = get_config_int("Inicializacao", "vsync",0);
	resolucaoX = get_config_int("Inicializacao", "resolucaox",800);
	resolucaoY = get_config_int("Inicializacao", "resolucaoy",600);
    //Fullscreen
    //res = set_gfx_mode(GFX_AUTODETECT_FULLSCREEN & GFX_BWINDOWSCREEN_ACCEL, resolucaoX, resolucaoY, 0, 0);
    //Janela
	res = set_gfx_mode(GFX_AUTODETECT_WINDOWED, resolucaoX, resolucaoY, 0, 0);
	if (res != 0) {
		allegro_message(allegro_error);
		exit(-1);
	}
	if(install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL))
    {
        allegro_message("Sound Error: %s", allegro_error);
    }

	//inicializa o metodo de atualizacao
	initialize_screen_updating(get_config_int("Inicializacao", "updatemethod", UPDATE_TRIPLE_BUFFER));

    set_window_title("Snake Criado por Arthur Assuncao"); //nome da Janela

    set_display_switch_mode(SWITCH_BACKGROUND); //roda o allegro em segundo plano

    //Botao fechar
    LOCK_FUNCTION(BotaoFechar);
    set_close_button_callback(BotaoFechar);

	//Contador de frames
	// Faz o lock das variaveis usadas pela funcao de timer e da propria funcao
    LOCK_VARIABLE(fps);
    LOCK_VARIABLE(contFrames);
    LOCK_FUNCTION(funcFPS);
	//chama a funcao funcFPS
	install_int_ex(funcFPS,BPS_TO_TIMER(MAXFPS)); //Frames por segundo, 60FPS
	//chama a funcao funcTempo
	LOCK_VARIABLE(contTempo);
    LOCK_FUNCTION(funcTempo);
	install_int(funcTempo, 1000); //Timer "ticks" a cada mil milisegundos, ou seja, 1 segundo

	/* adicione outras iniciacoes aqui */
}
コード例 #17
0
ファイル: c_simulation.cpp プロジェクト: rfree/antinet
void c_simulation::main_loop () {
	//	PALETTE palette;
	//BITMAP *img_bgr = load_bitmap("dat/bgr-bright.tga", NULL); // TODO:
    s_font_allegl.reset (allegro_gl_convert_allegro_font(font,AGL_FONT_TYPE_TEXTURED,500.0), [](FONT *f){allegro_gl_destroy_font(f);});

    for(auto &obj : m_world->m_objects) {
        obj->set_font(s_font_allegl);
    }
	int viewport_x = 0, viewport_y = 0;

	//show_mouse(m_screen);

	set_close_button_callback(c_close_button_handler);

	bool print_connect_line = false;
	bool start_simulation = false;
	bool simulation_pause = true;
	shared_ptr<c_cjddev> connect_node;
	std::chrono::steady_clock::time_point last_click_time =
		std::chrono::steady_clock::now() - std::chrono::milliseconds(1000);

	m_gui = make_shared<c_gui>();


	// prepare drawtarget surface to draw to
	switch (m_drawtarget_type) {
		case e_drawtarget_type_allegro:
			m_drawtarget = make_shared<c_drawtarget_allegro>(m_frame); 
		break;
		case e_drawtarget_type_opengl:
			m_drawtarget = make_shared<c_drawtarget_opengl>(); 
		break;
		default:
			_erro("Warning: unsupported drawtarget");
	}

	m_drawtarget->m_gui = m_gui;



	//	bool allegro_keys_any_was=false; // is any key pressed right now (for key press/release)
	long loop_miliseconds = 0;
	long unsigned int frame_checkpoint = 0; /// needed for speed control (without world_draw manipulate in spacetime!)
	_UNUSED(frame_checkpoint);

	bool use_input_allegro = true; // always for now.  input from Allegro
	bool use_draw_allegro = m_drawtarget_type == e_drawtarget_type_allegro; // draw in allegro
	bool use_draw_opengl = m_drawtarget_type == e_drawtarget_type_opengl; // draw in opengl


	_note("Entering main simulation loop");

	// The main drawing is done inside this loop.
	
	///@see rendering.txt/[[drawing_main]]
    float view_angle = 0.0;
    //float camera_offset = 1.0;

    float zoom = 1.0;
    float camera_step_z=-11.0;
    // === main loop ===
    while (!m_goodbye && !close_button_pressed) {

		auto start_time = std::chrono::high_resolution_clock::now();

		// --- process the keyboard/inputs ---
		if (use_input_allegro) {
				// TODO move this code here, but leave the variables in higher scope
		}

			poll_keyboard();
			auto allegro_keys = key;
			auto allegro_shifts = key_shifts;
			//		bool allegro_keys_any_is=false;
			//		for (size_t i=0; i<sizeof(allegro_keys)/sizeof(allegro_keys[0]); ++i) allegro_keys_any_is=true;
			// the direct raw position
			const int allegro_mouse_x = mouse_x;
			const int allegro_mouse_y = mouse_y;
			const int allegro_mouse_b = mouse_b; // buttons

			// the position in display port GUI
			const int gui_mouse_x = allegro_mouse_x; 
			const int gui_mouse_y = allegro_mouse_y;
			const int gui_mouse_b = allegro_mouse_b; // buttons
			
			// the position in the world coordinates
			const int gui_cursor_x = m_gui->view_x_rev(gui_mouse_x);
			const int gui_cursor_y = m_gui->view_y_rev(gui_mouse_y);
			const int gui_cursor_z = 0; // m_gui->view_z_rev(gui_mouse_z);
			
			_UNUSED(gui_mouse_b);
			_UNUSED(gui_cursor_x);
			_UNUSED(gui_cursor_y);
			_UNUSED(gui_cursor_z);

            //_dbg1("mouse_x mouse_y: " << gui_mouse_x << " " << gui_mouse_y);

			int allegro_char = 0;
			if (keypressed()) {
				allegro_char = readkey();
			}
		// end of input

		// draw background of frame
		if (use_draw_allegro) {
			clear_to_color(m_frame, makecol(0, 128, 0));
            blit(c_bitmaps::get_instance().m_background, m_frame, 0, 0, viewport_x, viewport_y, c_bitmaps::get_instance().m_background->w, c_bitmaps::get_instance().m_background->h);
		}
        if (use_draw_opengl) {
            glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
            //glDisable(GL_DEPTH_TEST);      // ??? Enables Depth Testing
            //glEnable(GL_DEPTH_TEST);
            //glDepthFunc(GL_LEQUAL);                         // The Type Of Depth Testing To Do
            //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
             //glLoadIdentity();
            // glTranslatef(m_gui->camera_x, m_gui->camera_y,camera_offset);

            // minimum and maximum value for zoom in/out and rotate the scene
//            if (camera_offset >= 10.0) camera_offset = 10.0;
//            if (camera_offset <= 0.5) camera_offset = 0.5;
            if (view_angle >= 70) view_angle = 70;
            if(view_angle <= 0) view_angle = 0;

            if( zoom <= 0.1 ) zoom = 0.1;  //because of glFrustum -> when left=right, or bottom=top there's error GL_INVALID_VALUE, so we can't multiply e.g left,right by 0

            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glFrustum(-1.0*zoom, 1.0*zoom, -1.0*zoom, 1.0*zoom, 1.0,60.0);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();

            //glTranslatef(0.0f,0.0f,-11.0);
            glTranslatef(0.0f,0.0f,camera_step_z);
            glRotatef(-view_angle, 1,0,0);
            glScalef(10,10,10);

            // drawing backgound
            glPushMatrix();
            //glScalef(1,1,1);
            glBindTexture(GL_TEXTURE_2D,c_bitmaps::get_instance().m_background_opengl);
            glEnable(GL_BLEND);
            //float q=1.0/zoom;
            float q=1.0;
            glBegin(GL_QUADS);
                glTexCoord2f(0,q); glVertex3f(-1.0f,1.0f, 0.0f);
                glTexCoord2f(q,q); glVertex3f(1.0f,1.0f, 0.0f);
                glTexCoord2f(q,0); glVertex3f(1.0f,-1.0f,0.0f);
                glTexCoord2f(0,0); glVertex3f(-1.0f,-1.0f,0.0f);
            glEnd();
            glDisable(GL_BLEND);
            glBindTexture(GL_TEXTURE_2D, 0);   // texture
            glPopMatrix();
		}
		
		// clear additional things
		if (use_draw_allegro) {
			clear_to_color(smallWindow, makecol(128, 128, 128));
		}

		// main controll keys
		if (allegro_keys[KEY_ESC]) {
			_note("User exits the simulation from user interface");
			m_goodbye = true;
		}

		if ((allegro_char & 0xff) == 'n' && !start_simulation) {
			std::cout << "ADD " << std::endl;
			_warn("THIS CODE IS NOT IMPLEMENTED NOW");
			/*
			m_world->m_objects.push_back(
				make_shared<c_cjddev>(
					cjddev_detail_random_name(), 
					// gui_mouse_x, gui_mouse_y,
					gui_cursor_x, gui_cursor_y,
					cjddev_detail_random_addr()));
					*/
		}

        if(allegro_keys[KEY_F1]){
            //auto ptr = get_move_object(gui_mouse_x,gui_mouse_y);


						//  TODO  -in allegro?   -not entire screen?    
						/*
            try{
                if(ptr != NULL){
                    int col_num =0;
                    textout_ex(smallWindow, font, ptr->get_name().c_str(), 0, 0, makecol(0, 0, 255), -1);

                        if(c_cjddev* tmp = dynamic_cast<c_cjddev *>(ptr.get()) ){
                            char* addr =(char *) malloc(45);
                             sprintf(addr,"address: %ld",tmp->get_address());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);
                             sprintf(addr,"neighbors: %d",(int)tmp->get_neighbors().size());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);
                             sprintf(addr,"waitng: %d",(int)tmp->num_of_wating());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);

//                    		textout_ex(smallWindow, font, ptr->get_name().c_str(), 0, 0, makecol(0, 0, 255), -1);{
                            free (addr);
                        }

												if (use_draw_allegro) { 
													// draw the information window
                        	blit (smallWindow,m_frame,0,0,m_frame->w-200,m_frame->h-200,screen->w/8, screen->h/4);
												}

                    }
            }
						catch(...) {}
						*/

//            std::cout<<ptr->get_name().c_str()<<std::endl;
        }
				

        if(allegro_keys[KEY_F2]){
//            BITMAP* screen = gui_get_screen();
          int m_x =0;
          int m_y =0;
          static unsigned int num =0;
            if(num>=m_world->m_objects.size()){
                num=0;
            }
           try{

//                auto obj = m_world->m_objects.at(0);
//                m_x = m_world->m_objects.at(num)->get_x() - (screen->w/2);
//                m_y = m_world->m_objects.at(num)->get_y() - (screen->h/2);
                  m_x =  m_world->m_objects.at(num)->get_x()*m_gui->camera_zoom - (allegro_mouse_x);
                  m_y =  m_world->m_objects.at(num)->get_y()*m_gui->camera_zoom - (allegro_mouse_y);


                //    std::cout<< screen->w<<" "<<screen->h<<" "<<screen->x_ofs<<" "<<screen->y_ofs<<std::endl;

                    m_gui->camera_x = m_x ;
                    m_gui->camera_y = m_y;


                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    num++;
            }catch(...)
            {

            }

        }


		// animation & tick
		if (m_frame_number % g_max_anim_frame == 0 && !simulation_pause) {
			frame_checkpoint = m_frame_number;
			m_world->tick(); // <===
		}


		// === main user interface ===

		// the mode
		typedef enum { e_mode_node, e_mode_camera } t_mode;
		t_mode mode;
		mode = e_mode_node; // by default we will move/edit etc the node (or entityt)
		if (allegro_shifts & KB_SHIFT_FLAG) mode = e_mode_camera; // with key SHIFT we move camera instea

		// mode: camera movement etc
		if (mode == e_mode_camera) {
			if (allegro_keys[KEY_LEFT]) m_gui->camera_x -= 10;
			if (allegro_keys[KEY_RIGHT]) m_gui->camera_x += 10;
            if (allegro_keys[KEY_UP]) m_gui->camera_y -= 10;
			if (allegro_keys[KEY_DOWN]) m_gui->camera_y += 10;

			const double zoom_speed = 1.1;
            if (allegro_keys[KEY_PGUP]) m_gui->camera_zoom *= zoom_speed;
			if (allegro_keys[KEY_PGDN]) m_gui->camera_zoom /= zoom_speed;
		}

        // rotate and zoom in/out the scene
        if(allegro_keys[KEY_Z]) {
            //camera_offset+=0.1;
            zoom+=0.1;
            _dbg1("zoom: " << zoom);
        }

        if(allegro_keys[KEY_X]) {
            //camera_offset-=0.1;
            zoom-=0.1;
            _dbg1("zoom: " << zoom);
        }
        if(allegro_keys[KEY_C]) {
            view_angle+=1.0;
            //farVal+=10;
            _dbg1("view_angle: " << view_angle);
        }
        if(allegro_keys[KEY_V]) {
            view_angle-=1.0;
            _dbg1("view_angle: " << view_angle);
        }
        if(allegro_keys[KEY_Q]) {
            camera_step_z+=0.1;
        }
        if(allegro_keys[KEY_W]) {
            camera_step_z -= 0.1;

            if(camera_step_z <= -11.0) camera_step_z=-11.0;
        }

		// === text debug on screen ===

		string mouse_pos_str = std::to_string(gui_mouse_x) + " " + std::to_string(gui_mouse_y);
		string fps_str = "fps ???";
		if (loop_miliseconds != 0) {
			fps_str = "fps: " + std::to_string(1000 / loop_miliseconds);
		}

		const int txt_h = 12; // line height (separation between lines)
		int txt_x = 10, txt_y = 10; // starting position of text

		if (use_draw_allegro) {

			string pck_speed_str = "sending packets speed - " + std::to_string(450 - g_max_anim_frame);
			textout_ex(m_frame, font, mouse_pos_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
			textout_ex(m_frame, font, fps_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
			textout_ex(m_frame, font, ("Frame nr.: " +
																 std::to_string(m_frame_number)).c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);

			textout_ex(m_frame, font, pck_speed_str.c_str(), 100, 10, makecol(0, 0, 255), -1);

					if(allegro_keys[KEY_H])
			{
				int tex_y = 10;
				int lineh = 10;
				textout_ex(m_frame, font, "s - start", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "p - pause", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "f - send FTP", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "t - select target", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "r - select source", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "d - remove node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "n - add node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "enter/esc - exit", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "Arrows: move selected node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "SHIFT-Arrows: move the camera", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "SHIFT-PageUp/Down: zimm in/out", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "F1: info about node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "F2: next node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
					} else{

							textout_ex(m_frame, font, "h - help", 1140, 30, makecol(0, 0, 255), -1);
					}
		}
		if (use_draw_opengl) {
			// TODO @opengl
            //textout_ex(m_frame, font, mouse_pos_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
            float offset = 0.03;
            float tex_y = 0.9;
            float tex_x = 0.7;
            string pck_speed_str = "sending packets speed - " + std::to_string(450 - g_max_anim_frame);
            glColor4f(0.0,0.0,1.0,0.0);
            //glScalef(0.2f,0.2f,0.2f);
            //glLoadIdentity();
            glPushMatrix();
            glEnable(GL_BLEND);
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y, 0.0, mouse_pos_str.c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y-=offset, 0.0, fps_str.c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y-=offset, 0.0, ("Frame nr.: " + std::to_string(m_frame_number)).c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.7, 0.97, 0.0, pck_speed_str.c_str());
            glDisable(GL_BLEND);
            glPopMatrix();

            if(allegro_keys[KEY_H]) {
                _dbg1("KEY_H - opengl");
                //glLoadIdentity();
                glPushMatrix();
                glEnable(GL_BLEND);
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y, 0.0,"s - start");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"p - pause");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"f - send FTP");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"t - select target");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"r - select source");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"d - remove node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"n - add node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"enter/esc - exit");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"Arrows: move selected node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"SHIFT-Arrows: move the camera");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"SHIFT-PageUp/Down: zoom in/out");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"F1: info about node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"F2: next node");
                glDisable(GL_BLEND);
                glPopMatrix();

            } else {
                //glLoadIdentity();
                glPushMatrix();
                glEnable(GL_BLEND);
                //allegro_gl_printf(s_font_allegl.get(), 0.8, 0.9, 0.0,0xFF0000,"h - help");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y, 0.0,"h - help");
                //glBlendFunc(GL_ONE, GL_ZERO);
                glDisable(GL_BLEND);
                glPopMatrix();
            }
		}


		//_dbg3("m_world->m_objects.size(): " << m_world->m_objects.size());
		//_dbg3("get_move_object ret: " << get_move_object(gui_mouse_x, gui_mouse_y));
		int move_object_index = get_move_object(gui_mouse_x, gui_mouse_y); ///< -1 if 'empty'

		if (move_object_index != -1) { // working with selected object
			m_gui->m_selected_object = m_world->m_objects.begin();
			std::advance(m_gui->m_selected_object, move_object_index);
			auto selected_object = m_gui->m_selected_object;
			(*selected_object)->m_selected = true;
			c_entity *selected_object_raw = dynamic_cast<c_entity *>((*selected_object).get());
			c_osi2_switch *selected_switch = dynamic_cast<c_osi2_switch *>((*selected_object).get());
			
		//	selected_switch->send_hello_to_neighbors(); // TODO
			
			//shared_ptr<c_cjddev> selected_device = std::dynamic_pointer_cast<c_cjddev>(selected_object);
			if (selected_object != m_world->m_objects.end()) { // editing the selected object
				// TODO: add connect
				/*if (gui_mouse_b == 1 && !print_connect_line) {
					print_connect_line = true;
					connect_node = std::dynamic_pointer_cast<c_cjddev>(selected_object);
					last_click_time = std::chrono::steady_clock::now();
				}

				if (gui_mouse_b == 1 && print_connect_line &&
				    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(500)) {
					// assert( connect_node && selected_object  );
					connect_node->add_neighbor(std::dynamic_pointer_cast<c_cjddev>(selected_object));
					(std::dynamic_pointer_cast<c_cjddev>(selected_object))->add_neighbor(std::dynamic_pointer_cast<c_cjddev>(connect_node));
					print_connect_line = false;
				}*/

				if (mode == e_mode_node) { // working with selected object - moving
					if (!print_connect_line) {
						int speed = 5;
						if (allegro_keys[KEY_LEFT])
							selected_object_raw->m_x += -speed;
						if (allegro_keys[KEY_RIGHT])
							selected_object_raw->m_x += speed;
						if (allegro_keys[KEY_DOWN])
							selected_object_raw->m_y += speed;
						if (allegro_keys[KEY_UP])
							selected_object_raw->m_y += -speed;
					}
				} // moving selected object
			}
/*
			if ((allegro_char & 0xff) == 's' && !start_simulation) {
				if (!m_gui->m_source || !m_gui->m_target) {
					std::cout << "please choose target and source node\n";
				} else {
					m_gui->m_source->buy_net(m_gui->m_target->get_address());
					start_simulation = true;
					simulation_pause = false;
				}
			}

			if ((allegro_char & 0xff) == 'd' && selected_device && !start_simulation) {
				for (shared_ptr<c_cjddev> &it : selected_device->get_neighbors()) {
					selected_device->remove_neighbor(it);
					it->remove_neighbor(selected_device);
				}

				for (auto it = m_world->m_objects.begin(); it != m_world->m_objects.end(); ++it) {
					if (it->get() == selected_device.get()) {
						m_world->m_objects.erase(it);
						break;
					}
				}
			}

			if ((allegro_char & 0xff) == 't' && selected_device && !start_simulation) {
				m_gui->m_target = selected_device;
			}

			if ((allegro_char & 0xff) == 'r' && selected_device && !start_simulation) {
				m_gui->m_source = selected_device;
			}

			if ((allegro_char & 0xff) == 'f') {
				if (!m_gui->m_source || !m_gui->m_target)
					std::cout << "please choose target and source node\n";
				else {
					m_gui->m_source->send_ftp_packet(m_gui->m_target->get_address(), "FTP data");
					last_click_time = std::chrono::steady_clock::now();
				}
			}
*/

			// === animation clock controll ===
			if ((allegro_char & 0xff) == 'p') {
				simulation_pause = !simulation_pause;
				last_click_time = std::chrono::steady_clock::now();
			}

			if (allegro_keys[KEY_MINUS_PAD] && g_max_anim_frame < 400 &&
			    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(loop_miliseconds)) {
				//std::cout << m_frame_number-frame_checkpoint << " - " << g_max_anim_frame << " mod: " << (m_frame_number-frame_checkpoint) % g_max_anim_frame <<  std::endl;
				g_max_anim_frame += 1;
				last_click_time = std::chrono::steady_clock::now();
			}

			if (allegro_keys[KEY_PLUS_PAD] && g_max_anim_frame > 10 &&
			    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(loop_miliseconds)) {
				//std::cout << m_frame_number-frame_checkpoint << " + " << g_max_anim_frame << " mod: " << (m_frame_number-frame_checkpoint) % g_max_anim_frame <<  std::endl;
				g_max_anim_frame -= 1;
				last_click_time = std::chrono::steady_clock::now();
			}
			
		}

		// === animation clock operations ===
		
        m_world->draw(*m_drawtarget.get()); // <===== DRAW THE WORLD

		/*
		if ((m_frame_number - frame_checkpoint) < g_max_anim_frame) {
			m_world->draw(*m_drawtarget.get(), (m_frame_number - frame_checkpoint) % g_max_anim_frame); // <==
		} else {
			m_world->draw(*m_drawtarget.get(), g_max_anim_frame);
		}
		*/

		if (print_connect_line) { // the line the creates new connections
			if (use_draw_allegro) {
				line(m_frame, connect_node->m_x, connect_node->m_y, allegro_mouse_x, allegro_mouse_y, makecol(0, 255, 255));
			}
            // TODO @opengl
            if (use_draw_opengl) {
                glColor3f(0.0f,1.0f,1.0f);
                glLineWidth(1.0);
                glScalef(1.0f,1.0f,1.0f);

                const int vx = m_gui->view_x(connect_node->m_x), vy = m_gui->view_y(connect_node->m_y); // position in viewport - because camera position
                //float start_line_x = ((connect_node->m_x)-0.5*SCREEN_W)/(0.5*SCREEN_W);
                //float start_line_y = -((connect_node->m_y)-0.5*SCREEN_H)/(0.5*SCREEN_H);
                float start_line_x = (vx-0.5*SCREEN_W)/(0.5*SCREEN_W);
                float start_line_y = -(vy-0.5*SCREEN_H)/(0.5*SCREEN_H);
                float end_line_x = (allegro_mouse_x-0.5*SCREEN_W)/(0.5*SCREEN_W);
                float end_line_y = -(allegro_mouse_y-0.5*SCREEN_H)/(0.5*SCREEN_H);

                //_dbg1("connect_node: " << connect_node->m_x << " " << connect_node->m_y);
                //_dbg1("allegro_mouse: " << allegro_mouse_x << " " << allegro_mouse_y);
                //_dbg1("start_line: " << start_line_x << " " << start_line_y);
                //_dbg1("end_line: " << end_line_x << " " << end_line_y);

                //glLoadIdentity();
                glPushMatrix();
                glBegin(GL_LINES);
                glVertex3f(start_line_x,start_line_y,0.0f);
                glVertex3f(end_line_x,end_line_y,0.0f);
                glEnd();
                glPopMatrix();
            }
		}
		if (allegro_mouse_b == 2) { // end/stop the line that creates new connections
			print_connect_line = false;
		}




		{
			auto x = allegro_mouse_x, y = allegro_mouse_y;
			int r = 5, rr = 4;

			if (use_draw_allegro) {
				line(m_frame, x - rr, y, x + rr, y, makecol(0, 0, 0));
				line(m_frame, x, y - rr, x, y + rr, makecol(0, 0, 0));
				circle(m_frame, x, y, r, makecol(255, 255, 255));
			}
			// TODO @opengl
            if(use_draw_opengl) {
                float opengl_mouse_x = (x-SCREEN_W*0.5)/(0.5*SCREEN_W);
                float opengl_mouse_y = -(y-SCREEN_H*0.5)/(0.5*SCREEN_H);
                float cursor_size=0.01;

                //_dbg1("mouse_x mouse_y: " << mouse_x << " " << mouse_y);
                //_dbg1("screenW screenH: " << SCREEN_W << " " << SCREEN_H);
                //glLoadIdentity();
                //glScalef(1/camera_offset, 1/camera_offset, 1.0);
                //glScalef(1.0*zoom, 1.0*zoom, 1.0*zoom);
                glPushMatrix();
                glScalef(1.0f,1.0f,1.0f);
                glTranslatef(opengl_mouse_x,opengl_mouse_y,0.0f);
                //glTranslatef(m_gui->view_x_rev(mouse_x),m_gui->view_y_rev(mouse_y),0.0f);
                glColor3f(0.0, 0.0, 0.0);

                // draw cursor
                glBegin(GL_LINES);
                glVertex2f(-1.0f*cursor_size,0.0f);
                glVertex2f(1.0f*cursor_size,0.0f);
                glVertex2f(0.0f,-1.0f*cursor_size);
                glVertex2f(0.0f,1.0f*cursor_size);
                glEnd();
                glPopMatrix();
            }

		}


		// === show frame ===

		if (use_draw_allegro) {
			//_dbg1("Allegro: frame done. fps = " << fps_str);
			scare_mouse();
			blit(m_frame, m_screen, 0, 0, 0, 0, m_frame->w, m_frame->h);
			unscare_mouse();
			if (!simulation_pause) {
				++m_frame_number;
			}
		}
		if (use_draw_opengl) {
            //_dbg1("OpenGL: frame flip. fps = " << fps_str);
			allegro_gl_flip();
		}

		for (auto &object : m_world->m_objects) {
			object->m_selected = false;
		}
		
//		std::this_thread::sleep_for(std::chrono::milliseconds(10));
		auto stop_time = std::chrono::high_resolution_clock::now();
		auto diff = stop_time - start_time;
		loop_miliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count();
	}

	std::ofstream out_file("../layout/current/out.map.txt");
	out_file << *m_world << std::endl;
}